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/jarvar-base/src/uk/co/peopleandroid/jarvar/internals/SoftDSP.java b/jarvar-base/src/uk/co/peopleandroid/jarvar/internals/SoftDSP.java index a2fb7af..3f7c538 100644 --- a/jarvar-base/src/uk/co/peopleandroid/jarvar/internals/SoftDSP.java +++ b/jarvar-base/src/uk/co/peopleandroid/jarvar/internals/SoftDSP.java @@ -1,54 +1,54 @@ package uk.co.peopleandroid.jarvar.internals; public class SoftDSP extends Thread { boolean running = true; public void run() { while(running) { eval(); Thread.yield(); } } public void destroy() { running = false; } int mem[] = new int[1024]; void eval() { int pc = mem[0]; int a = pc >>> 24;//pc int b = (pc >> 16) & 255;//inf int c = (pc >> 8) & 255;//zero int d = pc & 255;//NaN int i = mem[a];//instruction int ia = i >>> 24; int ib = (i >> 16) & 255; int ic = (i >> 8) & 255; int id = i & 255; float x = asF(ia); x *= x; x *= asF(id); x = asF(ic) - x; x *= asF(ib); - mem[ia] = asI(x); - a = (a++) & 255; + a++; if(x == Float.NaN) a = d; if(x == Float.NEGATIVE_INFINITY || x == Float.POSITIVE_INFINITY) a = b; if(x == 0.0) a = c; - pc = (a << 24) | (b << 16) | (c << 8) | d;//restore pc + pc = (a << 24) | (pc & 0xffffff);//restore pc mem[0] = pc; + mem[ia] = asI(x);//as jump vectoring allowed!!! } float asF(int idx) { return Float.intBitsToFloat(mem[idx]); } int asI(float val) { return Float.floatToIntBits(val); } }
false
true
void eval() { int pc = mem[0]; int a = pc >>> 24;//pc int b = (pc >> 16) & 255;//inf int c = (pc >> 8) & 255;//zero int d = pc & 255;//NaN int i = mem[a];//instruction int ia = i >>> 24; int ib = (i >> 16) & 255; int ic = (i >> 8) & 255; int id = i & 255; float x = asF(ia); x *= x; x *= asF(id); x = asF(ic) - x; x *= asF(ib); mem[ia] = asI(x); a = (a++) & 255; if(x == Float.NaN) a = d; if(x == Float.NEGATIVE_INFINITY || x == Float.POSITIVE_INFINITY) a = b; if(x == 0.0) a = c; pc = (a << 24) | (b << 16) | (c << 8) | d;//restore pc mem[0] = pc; }
void eval() { int pc = mem[0]; int a = pc >>> 24;//pc int b = (pc >> 16) & 255;//inf int c = (pc >> 8) & 255;//zero int d = pc & 255;//NaN int i = mem[a];//instruction int ia = i >>> 24; int ib = (i >> 16) & 255; int ic = (i >> 8) & 255; int id = i & 255; float x = asF(ia); x *= x; x *= asF(id); x = asF(ic) - x; x *= asF(ib); a++; if(x == Float.NaN) a = d; if(x == Float.NEGATIVE_INFINITY || x == Float.POSITIVE_INFINITY) a = b; if(x == 0.0) a = c; pc = (a << 24) | (pc & 0xffffff);//restore pc mem[0] = pc; mem[ia] = asI(x);//as jump vectoring allowed!!! }
diff --git a/SimpleAndroidApp/src/org/ivan/simple/welcome/StartActivity.java b/SimpleAndroidApp/src/org/ivan/simple/welcome/StartActivity.java index b8eb2ca..30105f5 100644 --- a/SimpleAndroidApp/src/org/ivan/simple/welcome/StartActivity.java +++ b/SimpleAndroidApp/src/org/ivan/simple/welcome/StartActivity.java @@ -1,172 +1,171 @@ package org.ivan.simple.welcome; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.util.SparseArray; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import org.ivan.simple.PandaApplication; import org.ivan.simple.PandaBaseActivity; import org.ivan.simple.R; import org.ivan.simple.choose.LevelChooseActivity; import org.ivan.simple.utils.PandaButtonsPanel; import java.util.Timer; import java.util.TimerTask; public class StartActivity extends PandaBaseActivity { public static final String SET_ID = "Id of levels set"; public static final String LAST_FINISHED_SET = "Last finished set of levels"; public static final int PACKS_IN_ROW = 3; private final String[] levelsCaptions = {"ACCESS", "BUTTON", "ZOMBIE", "SYSTEM"}; public final int levCount = levelsCaptions.length; private SparseArray<ImageView> levButtons = new SparseArray<ImageView>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // hide screen title setContentView(R.layout.activity_start); findViewById(R.id.activity_content).setBackgroundDrawable(app().getBackground()); TextView caption = (TextView) findViewById(R.id.text_view); caption.setTypeface(app().getFontProvider().bold()); caption.setTextSize(TypedValue.COMPLEX_UNIT_PX, app().displayHeight / 10); // caption.setText(String.format("max memory: %d KiB", Runtime.getRuntime().maxMemory() / 1024)); initPacksButtons(); View backBtn = prepare(R.drawable.back); View settingsBtn = prepare(R.drawable.settings); PandaButtonsPanel bp = (PandaButtonsPanel) findViewById(R.id.level_packs_bp); bp.customAddView(backBtn); bp.customAddView(settingsBtn); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); settingsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { gotoSettingsScreen(); } }); } private int lastFinishedSet() { return getSharedPreferences(LevelChooseActivity.CONFIG, MODE_PRIVATE) .getInt(LAST_FINISHED_SET, 0); } private float chestRatio = 173f / 225f; private void initPacksButtons() { TableLayout buttonsPane = (TableLayout) findViewById(R.id.packs_panel); TableRow row = null; TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); TableRow.LayoutParams packButtonParam = createPackLayoutParams(); for(int i = 0; i < levCount; i++) { if(i % PACKS_IN_ROW == 0) { row = new TableRow(this); buttonsPane.addView(row, rowParams); } ImageView levbtn = new ImageView(this); // levbtn.setText(levelsCaptions[i]); final int id = i + 1; if(id <= lastFinishedSet() + 1) { levbtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.chest_open)); levbtn.setEnabled(true); } else { levbtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.chest_close)); levbtn.setEnabled(false); } levbtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startPack(id); } }); row.addView(levbtn, packButtonParam); levButtons.put(id, levbtn); // levbtn.getLayoutParams().width = (int) (displayWidth * 0.85); // levbtn.getLayoutParams().height = (int) (displayHeight * 0.20); } } private TableRow.LayoutParams createPackLayoutParams() { float availableWidth = app().displayWidth * 0.8f; float availableHeight = app().displayHeight * 0.55f; int chestWidth = (int) (availableWidth / PACKS_IN_ROW); int chestHeight = (int) (availableHeight / Math.ceil((float) levCount / PACKS_IN_ROW)); if(chestWidth * chestRatio < chestHeight) { chestHeight = (int) (chestWidth * chestRatio); } else { chestWidth = (int) (chestHeight / chestRatio); } TableRow.LayoutParams packButtonParam = new TableRow.LayoutParams(chestWidth, chestHeight); packButtonParam.setMargins(10, 10, 10, 10); return packButtonParam; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK && requestCode == 0) { System.out.println("Choose activity results!"); boolean setComplete = data.getBooleanExtra(LevelChooseActivity.SET_COMPLETE, false); int startedSet = data.getIntExtra(SET_ID, 0); int packToOpenId = startedSet + 1; final ImageView packToOpen; - setComplete = true; if(setComplete && (packToOpen = levButtons.get(packToOpenId)) != null) { final AnimationDrawable chestOpening = app().loadAnimationFromFolder("animations/menu/pack_opening"); chestOpening.setOneShot(true); packToOpen.setBackgroundDrawable(chestOpening); // TODO rake here, get rid of alpha channel manipulation, calculate chests sizes instead packToOpen.post(new Runnable() { @Override public void run() { chestOpening.start(); new Timer().schedule(new TimerTask() { @Override public void run() { chestOpening.stop(); packToOpen.post(new Runnable() { @Override public void run() { packToOpen.setBackgroundDrawable(getResources().getDrawable(R.drawable.chest_open)); } }); } }, chestOpening.getNumberOfFrames() * PandaApplication.ONE_FRAME_DURATION); } }); packToOpen.setEnabled(true); } } } private void startPack(int setId) { Intent intent = new Intent(this, LevelChooseActivity.class); intent.putExtra(SET_ID, setId); startActivityForResult(intent, 0); } }
true
true
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK && requestCode == 0) { System.out.println("Choose activity results!"); boolean setComplete = data.getBooleanExtra(LevelChooseActivity.SET_COMPLETE, false); int startedSet = data.getIntExtra(SET_ID, 0); int packToOpenId = startedSet + 1; final ImageView packToOpen; setComplete = true; if(setComplete && (packToOpen = levButtons.get(packToOpenId)) != null) { final AnimationDrawable chestOpening = app().loadAnimationFromFolder("animations/menu/pack_opening"); chestOpening.setOneShot(true); packToOpen.setBackgroundDrawable(chestOpening); // TODO rake here, get rid of alpha channel manipulation, calculate chests sizes instead packToOpen.post(new Runnable() { @Override public void run() { chestOpening.start(); new Timer().schedule(new TimerTask() { @Override public void run() { chestOpening.stop(); packToOpen.post(new Runnable() { @Override public void run() { packToOpen.setBackgroundDrawable(getResources().getDrawable(R.drawable.chest_open)); } }); } }, chestOpening.getNumberOfFrames() * PandaApplication.ONE_FRAME_DURATION); } }); packToOpen.setEnabled(true); } } }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK && requestCode == 0) { System.out.println("Choose activity results!"); boolean setComplete = data.getBooleanExtra(LevelChooseActivity.SET_COMPLETE, false); int startedSet = data.getIntExtra(SET_ID, 0); int packToOpenId = startedSet + 1; final ImageView packToOpen; if(setComplete && (packToOpen = levButtons.get(packToOpenId)) != null) { final AnimationDrawable chestOpening = app().loadAnimationFromFolder("animations/menu/pack_opening"); chestOpening.setOneShot(true); packToOpen.setBackgroundDrawable(chestOpening); // TODO rake here, get rid of alpha channel manipulation, calculate chests sizes instead packToOpen.post(new Runnable() { @Override public void run() { chestOpening.start(); new Timer().schedule(new TimerTask() { @Override public void run() { chestOpening.stop(); packToOpen.post(new Runnable() { @Override public void run() { packToOpen.setBackgroundDrawable(getResources().getDrawable(R.drawable.chest_open)); } }); } }, chestOpening.getNumberOfFrames() * PandaApplication.ONE_FRAME_DURATION); } }); packToOpen.setEnabled(true); } } }
diff --git a/src/de/_13ducks/cor/game/server/ServerPathfinder.java b/src/de/_13ducks/cor/game/server/ServerPathfinder.java index d7a47a8..672b0d9 100644 --- a/src/de/_13ducks/cor/game/server/ServerPathfinder.java +++ b/src/de/_13ducks/cor/game/server/ServerPathfinder.java @@ -1,299 +1,302 @@ /* * 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; import de._13ducks.cor.game.FloatingPointPosition; import de._13ducks.cor.game.SimplePosition; import de._13ducks.cor.game.server.movement.Edge; import de._13ducks.cor.game.server.movement.FreePolygon; import de._13ducks.cor.game.server.movement.MovementMap; import java.util.*; import org.apache.commons.collections.buffer.PriorityBuffer; import de._13ducks.cor.game.server.movement.Node; /** * Der Serverpathfinder. * Sucht Wege zwischen Knoten (Nodes) * Um einen echten Weg zu bekommen, muss der Weg danach noch überarbeitet werden, aber das ist nicht Aufgabe des * Pathfinders. * @author tfg */ public final class ServerPathfinder { /** * Niemand kann einen Pathfinder erstellen, dies ist eine Utilityclass */ private ServerPathfinder() { } public static synchronized List<Node> findPath(Node startNode, Node targetNode) { if (startNode == null || targetNode == null) { System.out.println("FixMe: SPathfinder, irregular call: " + startNode + "-->" + targetNode); return null; } if (startNode.equals(targetNode)) { return new ArrayList<Node>(); } PriorityBuffer open = new PriorityBuffer(); // Liste für entdeckte Knoten LinkedHashSet<Node> containopen = new LinkedHashSet<Node>(); // Auch für entdeckte Knoten, hiermit kann viel schneller festgestellt werden, ob ein bestimmter Knoten schon enthalten ist. LinkedHashSet<Node> closed = new LinkedHashSet<Node>(); // Liste für fertig bearbeitete Knoten double cost_t = 0; //Movement Kosten (gerade 5, diagonal 7, wird später festgelegt) startNode.setCost(0); //Kosten für das Startfeld (von dem aus berechnet wird) sind natürlich 0 open.add(startNode); //Startfeld in die openlist containopen.add(startNode); targetNode.setParent(null); //"Vorgängerfeld" vom Zielfeld noch nicht bekannt for (int j = 0; j < 40000; j++) { //Anzahl der maximalen Durchläufe, bis Wegfindung aufgibt if (open.isEmpty()) { //Abbruch, wenn openlist leer ist => es gibt keinen Weg return null; } // Sortieren nicht mehr nötig, PriorityBuffer bewahrt die Felder in der Reihenfolge ihrer Priority - also dem F-Wert auf Node current = (Node) open.remove(); //der Eintrag aus der openlist mit dem niedrigesten F-Wert rausholen und gleich löschen containopen.remove(current); if (current.equals(targetNode)) { //Abbruch, weil Weg von Start nach Ziel gefunden wurde targetNode.setParent(current.getParent()); //"Vorgängerfeld" von Ziel bekannt break; } // Aus der open wurde current bereits gelöscht, jetzt in die closed verschieben closed.add(current); List<Node> neighbors = current.getReachableNodes(); for (Node node : neighbors) { if (closed.contains(node)) { continue; } // Kosten dort hin berechnen cost_t = current.movementCostTo(node); if (containopen.contains(node)) { //Wenn sich der Knoten in der openlist befindet, muss berechnet werden, ob es einen kürzeren Weg gibt if (current.getCost() + cost_t < node.getCost()) { //kürzerer Weg gefunden? node.setCost(current.getCost() + cost_t); //-> Wegkosten neu berechnen node.setValF(node.getCost() + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start + Luftlinie zum Ziel node.setParent(current); //aktuelles Feld wird zum Vorgängerfeld } } else { node.setCost(current.getCost() + cost_t); node.setHeuristic((Math.abs((targetNode.getX() - node.getX())) + Math.abs((targetNode.getY() - node.getY()))) * 3); // geschätzte Distanz zum Ziel //Die Zahl am Ende der Berechnung ist der Aufwand der Wegsuche //5 ist schnell, 4 normal, 3 dauert lange node.setParent(current); // Parent ist die RogPosition, von dem der aktuelle entdeckt wurde node.setValF(node.getCost() + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start aus + Luftlinie zum Ziel open.add(node); // in openlist hinzufügen containopen.add(node); } } } if (targetNode.getParent() == null) { //kein Weg gefunden return null; } ArrayList<Node> pathrev = new ArrayList(); //Pfad aus parents erstellen, von Ziel nach Start while (!targetNode.equals(startNode)) { pathrev.add(targetNode); targetNode = targetNode.getParent(); } pathrev.add(startNode); ArrayList<Node> path = new ArrayList(); //Pfad umkehren, sodass er von Start nach Ziel ist for (int k = pathrev.size() - 1; k >= 0; k--) { path.add(pathrev.get(k)); } return path; //Pfad zurückgeben } public static List<SimplePosition> optimizePath(List<Node> path, SimplePosition startPos, SimplePosition endPos, MovementMap moveMap) { // Besseres, iteratives Vorgehen // Vorbereitungen: Der Weg muss Start und Ziel beinhalten path.add(0, startPos.toNode()); - path.add(endPos.toNode()); + // Ende muss seinen Polygon kennen: + Node endNode = endPos.toNode(); + endNode.addPolygon(moveMap.containingPoly(endNode.x(), endNode.y())); + path.add(endNode); FreePolygon startPolygon = moveMap.containingPoly(startPos.x(), startPos.y()); boolean improved = true; while (improved) { improved = false; FreePolygon currentPoly = startPolygon; // Weg durchgehen for (int i = 1; i < path.size() - 1; i++) { Node pre = path.get(i - 1); Node cur = path.get(i); Node nxt = path.get(i + 1); // Testweise Kante zwischen pre und nxt erstellen Edge edge = new Edge(pre, nxt); // Im Folgenden wird untersucht, ob der neue Weg "edge" passierbar ist. // Eventuell müssen für Polygonwechsel neue Nodes eingefügt werden LinkedList<Node> extraNodes = new LinkedList<Node>(); // Damit wir beim Dreieckwechsel nicht wieder zurück gehen: Node lastNode = null; boolean routeAllowed = true; // Jetzt so lange weiter laufen, bis wir im Ziel-Polygon sind while (!nxt.getPolygons().contains(currentPoly)) { // Untersuchen, ob es eine Seite des currentPolygons gibt, die sich mit der alternativRoute schneidet List<Edge> edges = currentPoly.calcEdges(); Edge intersecting = null; for (Edge testedge : edges) { // Gibts da einen Schnitt? SimplePosition intersection = edge.intersectionWithEdgeNotAllowed(testedge); if (intersection != null && !intersection.equals(lastNode)) { intersecting = testedge; break; } } // Kandidat für den nächsten Polygon FreePolygon nextPoly = null; // Kante gefunden if (intersecting != null) { // Von dieser Kante die Enden suchen nextPoly = getOtherPoly(intersecting.getStart(), intersecting.getEnd(), currentPoly); } if (intersecting != null && nextPoly != null) { // Wir haben einen Schnittpunkt und eine Kante gefunden, sind jetzt also in einem neuen Polygon // Extra Node einfügen Node extraNode = intersecting.intersectionWithEdgeNotAllowed(edge).toNode(); if (extraNode.equals(cur)) { // Abbruch, das ist eine Gerade, hier kann man nicht abkürzen! FreePolygon currentCand = commonSector(cur, nxt); if (currentCand != null) { currentPoly = currentCand; } routeAllowed = false; break; } extraNode.addPolygon(nextPoly); extraNode.addPolygon(currentPoly); extraNodes.add(extraNode); lastNode = extraNode; currentPoly = nextPoly; // Der nächste Schleifendurchlauf wird den nächsten Polygon untersuchen } else { // Es gab leider keinen betretbaren Polygon hier. // Das bedeutet, dass wir die Suche abbrechen können, der derzeit untersuchte Wegpunkt (cur) // Ist also unverzichtbar. // Es soll also der nächste Punkt untersucht werden, also die for einfach weiter laufen // Eventuell muss aber der currentPoly geändert werden. // CurrentPoly ändern, wenn in neuem Sektor: FreePolygon currentCand = commonSector(cur, nxt); if (currentCand != null) { currentPoly = currentCand; } routeAllowed = false; break; } } // Wenn der neue Weg gültig war, einbauen. Sonst weiter mit dem nächsten Knoten if (routeAllowed) { // Den ursprünglichen Knoten löschen und die neuen Einbauen path.remove(i); path.addAll(i, extraNodes); // Der Weg wurde geändert, die for muss neu starten improved = true; break; } // Wenn wir hier hinkommen, soll der nächste Knoten getestet werden. extraNodes.clear(); } } // Hier ist der Weg fertig optimiert // Start wieder löschen und zurückgeben path.remove(0); // Das Sektorsystem unterscheidet strikt zwischen SimplePosition und Node, deshalb die letzte durch eine Simple ersetzten Node last = path.remove(path.size() - 1); LinkedList<SimplePosition> retList = new LinkedList<SimplePosition>(); for (Node n : path) { retList.add(n); } // Jetzt wieder einfügen retList.add(new FloatingPointPosition(last.x(), last.y())); return retList; } private static FreePolygon getOtherPoly(Node n1, Node n2, FreePolygon myself) { for (FreePolygon poly : n1.getPolygons()) { if (poly.equals(myself)) { continue; } if (n2.getPolygons().contains(poly)) { return poly; } } return null; } /** * Findet einen Sektor, den beide Knoten gemeinsam haben * @param n1 Knoten 1 * @param n2 Knoten 2 */ private static FreePolygon commonSector(Node n1, Node n2) { for (FreePolygon poly : n1.getPolygons()) { if (n2.getPolygons().contains(poly)) { return poly; } } return null; } }
true
true
public static List<SimplePosition> optimizePath(List<Node> path, SimplePosition startPos, SimplePosition endPos, MovementMap moveMap) { // Besseres, iteratives Vorgehen // Vorbereitungen: Der Weg muss Start und Ziel beinhalten path.add(0, startPos.toNode()); path.add(endPos.toNode()); FreePolygon startPolygon = moveMap.containingPoly(startPos.x(), startPos.y()); boolean improved = true; while (improved) { improved = false; FreePolygon currentPoly = startPolygon; // Weg durchgehen for (int i = 1; i < path.size() - 1; i++) { Node pre = path.get(i - 1); Node cur = path.get(i); Node nxt = path.get(i + 1); // Testweise Kante zwischen pre und nxt erstellen Edge edge = new Edge(pre, nxt); // Im Folgenden wird untersucht, ob der neue Weg "edge" passierbar ist. // Eventuell müssen für Polygonwechsel neue Nodes eingefügt werden LinkedList<Node> extraNodes = new LinkedList<Node>(); // Damit wir beim Dreieckwechsel nicht wieder zurück gehen: Node lastNode = null; boolean routeAllowed = true; // Jetzt so lange weiter laufen, bis wir im Ziel-Polygon sind while (!nxt.getPolygons().contains(currentPoly)) { // Untersuchen, ob es eine Seite des currentPolygons gibt, die sich mit der alternativRoute schneidet List<Edge> edges = currentPoly.calcEdges(); Edge intersecting = null; for (Edge testedge : edges) { // Gibts da einen Schnitt? SimplePosition intersection = edge.intersectionWithEdgeNotAllowed(testedge); if (intersection != null && !intersection.equals(lastNode)) { intersecting = testedge; break; } } // Kandidat für den nächsten Polygon FreePolygon nextPoly = null; // Kante gefunden if (intersecting != null) { // Von dieser Kante die Enden suchen nextPoly = getOtherPoly(intersecting.getStart(), intersecting.getEnd(), currentPoly); } if (intersecting != null && nextPoly != null) { // Wir haben einen Schnittpunkt und eine Kante gefunden, sind jetzt also in einem neuen Polygon // Extra Node einfügen Node extraNode = intersecting.intersectionWithEdgeNotAllowed(edge).toNode(); if (extraNode.equals(cur)) { // Abbruch, das ist eine Gerade, hier kann man nicht abkürzen! FreePolygon currentCand = commonSector(cur, nxt); if (currentCand != null) { currentPoly = currentCand; } routeAllowed = false; break; } extraNode.addPolygon(nextPoly); extraNode.addPolygon(currentPoly); extraNodes.add(extraNode); lastNode = extraNode; currentPoly = nextPoly; // Der nächste Schleifendurchlauf wird den nächsten Polygon untersuchen } else { // Es gab leider keinen betretbaren Polygon hier. // Das bedeutet, dass wir die Suche abbrechen können, der derzeit untersuchte Wegpunkt (cur) // Ist also unverzichtbar. // Es soll also der nächste Punkt untersucht werden, also die for einfach weiter laufen // Eventuell muss aber der currentPoly geändert werden. // CurrentPoly ändern, wenn in neuem Sektor: FreePolygon currentCand = commonSector(cur, nxt); if (currentCand != null) { currentPoly = currentCand; } routeAllowed = false; break; } } // Wenn der neue Weg gültig war, einbauen. Sonst weiter mit dem nächsten Knoten if (routeAllowed) { // Den ursprünglichen Knoten löschen und die neuen Einbauen path.remove(i); path.addAll(i, extraNodes); // Der Weg wurde geändert, die for muss neu starten improved = true; break; } // Wenn wir hier hinkommen, soll der nächste Knoten getestet werden. extraNodes.clear(); } } // Hier ist der Weg fertig optimiert // Start wieder löschen und zurückgeben path.remove(0); // Das Sektorsystem unterscheidet strikt zwischen SimplePosition und Node, deshalb die letzte durch eine Simple ersetzten Node last = path.remove(path.size() - 1); LinkedList<SimplePosition> retList = new LinkedList<SimplePosition>(); for (Node n : path) { retList.add(n); } // Jetzt wieder einfügen retList.add(new FloatingPointPosition(last.x(), last.y())); return retList; }
public static List<SimplePosition> optimizePath(List<Node> path, SimplePosition startPos, SimplePosition endPos, MovementMap moveMap) { // Besseres, iteratives Vorgehen // Vorbereitungen: Der Weg muss Start und Ziel beinhalten path.add(0, startPos.toNode()); // Ende muss seinen Polygon kennen: Node endNode = endPos.toNode(); endNode.addPolygon(moveMap.containingPoly(endNode.x(), endNode.y())); path.add(endNode); FreePolygon startPolygon = moveMap.containingPoly(startPos.x(), startPos.y()); boolean improved = true; while (improved) { improved = false; FreePolygon currentPoly = startPolygon; // Weg durchgehen for (int i = 1; i < path.size() - 1; i++) { Node pre = path.get(i - 1); Node cur = path.get(i); Node nxt = path.get(i + 1); // Testweise Kante zwischen pre und nxt erstellen Edge edge = new Edge(pre, nxt); // Im Folgenden wird untersucht, ob der neue Weg "edge" passierbar ist. // Eventuell müssen für Polygonwechsel neue Nodes eingefügt werden LinkedList<Node> extraNodes = new LinkedList<Node>(); // Damit wir beim Dreieckwechsel nicht wieder zurück gehen: Node lastNode = null; boolean routeAllowed = true; // Jetzt so lange weiter laufen, bis wir im Ziel-Polygon sind while (!nxt.getPolygons().contains(currentPoly)) { // Untersuchen, ob es eine Seite des currentPolygons gibt, die sich mit der alternativRoute schneidet List<Edge> edges = currentPoly.calcEdges(); Edge intersecting = null; for (Edge testedge : edges) { // Gibts da einen Schnitt? SimplePosition intersection = edge.intersectionWithEdgeNotAllowed(testedge); if (intersection != null && !intersection.equals(lastNode)) { intersecting = testedge; break; } } // Kandidat für den nächsten Polygon FreePolygon nextPoly = null; // Kante gefunden if (intersecting != null) { // Von dieser Kante die Enden suchen nextPoly = getOtherPoly(intersecting.getStart(), intersecting.getEnd(), currentPoly); } if (intersecting != null && nextPoly != null) { // Wir haben einen Schnittpunkt und eine Kante gefunden, sind jetzt also in einem neuen Polygon // Extra Node einfügen Node extraNode = intersecting.intersectionWithEdgeNotAllowed(edge).toNode(); if (extraNode.equals(cur)) { // Abbruch, das ist eine Gerade, hier kann man nicht abkürzen! FreePolygon currentCand = commonSector(cur, nxt); if (currentCand != null) { currentPoly = currentCand; } routeAllowed = false; break; } extraNode.addPolygon(nextPoly); extraNode.addPolygon(currentPoly); extraNodes.add(extraNode); lastNode = extraNode; currentPoly = nextPoly; // Der nächste Schleifendurchlauf wird den nächsten Polygon untersuchen } else { // Es gab leider keinen betretbaren Polygon hier. // Das bedeutet, dass wir die Suche abbrechen können, der derzeit untersuchte Wegpunkt (cur) // Ist also unverzichtbar. // Es soll also der nächste Punkt untersucht werden, also die for einfach weiter laufen // Eventuell muss aber der currentPoly geändert werden. // CurrentPoly ändern, wenn in neuem Sektor: FreePolygon currentCand = commonSector(cur, nxt); if (currentCand != null) { currentPoly = currentCand; } routeAllowed = false; break; } } // Wenn der neue Weg gültig war, einbauen. Sonst weiter mit dem nächsten Knoten if (routeAllowed) { // Den ursprünglichen Knoten löschen und die neuen Einbauen path.remove(i); path.addAll(i, extraNodes); // Der Weg wurde geändert, die for muss neu starten improved = true; break; } // Wenn wir hier hinkommen, soll der nächste Knoten getestet werden. extraNodes.clear(); } } // Hier ist der Weg fertig optimiert // Start wieder löschen und zurückgeben path.remove(0); // Das Sektorsystem unterscheidet strikt zwischen SimplePosition und Node, deshalb die letzte durch eine Simple ersetzten Node last = path.remove(path.size() - 1); LinkedList<SimplePosition> retList = new LinkedList<SimplePosition>(); for (Node n : path) { retList.add(n); } // Jetzt wieder einfügen retList.add(new FloatingPointPosition(last.x(), last.y())); return retList; }
diff --git a/src/main/battlecode/doc/RobotDoc.java b/src/main/battlecode/doc/RobotDoc.java index cb346fc0..b705cf17 100644 --- a/src/main/battlecode/doc/RobotDoc.java +++ b/src/main/battlecode/doc/RobotDoc.java @@ -1,96 +1,96 @@ package battlecode.doc; import java.util.ArrayList; import java.util.List; import java.util.Map; import battlecode.common.RobotType; import com.sun.javadoc.*; import com.sun.tools.doclets.Taglet; public class RobotDoc implements Taglet { public static void register(Map<String, Taglet> map) { map.put("robot", new RobotDoc()); } public String getName() { return "robot"; } public boolean inConstructor() { return false; } public boolean inField() { return true; } public boolean inMethod() { return false; } public boolean inOverview() { return false; } public boolean inPackage() { return false; } public boolean inType() { return false; } public boolean isInlineTag() { return false; } public String toString(Tag tag) { throw new IllegalArgumentException("The component tag may not be used inline."); } String [] members; int n; static public void append(StringBuilder builder, String label, String value) { builder.append(String.format("<strong>%s:</strong> %s<br />",label,value)); } public String toString(String comp) { RobotType rt; try { rt = RobotType.valueOf(comp); } catch(IllegalArgumentException e) { return null; } StringBuilder builder = new StringBuilder(); try { append(builder,"Level",rt.level.name()); append(builder,"Max Energon",String.format("%1.0f",rt.maxEnergon)); append(builder,"Max Flux",String.format("%1.0f", rt.maxFlux)); if(rt.spawnCost>0) append(builder,"Spawn Cost",String.format("%1.0f",rt.spawnCost)); if(rt.moveDelayOrthogonal>0) { append(builder,"Move Delay Orthogonal",String.format("%d",rt.moveDelayOrthogonal)); append(builder,"Move Delay Diagonal",String.format("%d",rt.moveDelayDiagonal)); // display cost for archons even though it's zero append(builder,"Move Cost",String.format("%1.1f",rt.moveCost)); } if(rt.sensorAngle > 0) { append(builder,"Sensor Radius Squared",String.format("%d",rt.sensorRadiusSquared)); append(builder,"Sensor Angle",String.format("%1.0f",rt.sensorAngle)); } if(rt.canAttackAir || rt.canAttackGround) { append(builder,"Min Attack Radius Squared",String.format("%d",rt.attackRadiusMinSquared)); append(builder,"Max Attack Radius Squared",String.format("%d",rt.attackRadiusMaxSquared)); append(builder,"Attack Angle",String.format("%1.0f",rt.attackAngle)); - append(builder,"Attack Power",String.format("%1.0f",rt.attackPower)); + append(builder,"Attack Power",String.format("%1.1f",rt.attackPower)); append(builder,"Attack Delay",String.format("%d",rt.attackDelay)); String attacks; if(rt.canAttackAir && rt.canAttackGround) attacks = "Air, Ground"; else if(rt.canAttackAir) attacks = "Air"; else attacks = "Ground"; append(builder,"Attacks",attacks); } } catch(Exception e) { e.printStackTrace(); } return builder.toString(); } public String toString(Tag [] tags) { if(members==null) members = System.getProperty("battlecode.doc.members").split("\n"); String [] member; if(n<members.length) member = members[n++].split("\\."); else return null; if("RobotType".equals(member[0])) return toString(member[1]); else return null; } }
true
true
public String toString(String comp) { RobotType rt; try { rt = RobotType.valueOf(comp); } catch(IllegalArgumentException e) { return null; } StringBuilder builder = new StringBuilder(); try { append(builder,"Level",rt.level.name()); append(builder,"Max Energon",String.format("%1.0f",rt.maxEnergon)); append(builder,"Max Flux",String.format("%1.0f", rt.maxFlux)); if(rt.spawnCost>0) append(builder,"Spawn Cost",String.format("%1.0f",rt.spawnCost)); if(rt.moveDelayOrthogonal>0) { append(builder,"Move Delay Orthogonal",String.format("%d",rt.moveDelayOrthogonal)); append(builder,"Move Delay Diagonal",String.format("%d",rt.moveDelayDiagonal)); // display cost for archons even though it's zero append(builder,"Move Cost",String.format("%1.1f",rt.moveCost)); } if(rt.sensorAngle > 0) { append(builder,"Sensor Radius Squared",String.format("%d",rt.sensorRadiusSquared)); append(builder,"Sensor Angle",String.format("%1.0f",rt.sensorAngle)); } if(rt.canAttackAir || rt.canAttackGround) { append(builder,"Min Attack Radius Squared",String.format("%d",rt.attackRadiusMinSquared)); append(builder,"Max Attack Radius Squared",String.format("%d",rt.attackRadiusMaxSquared)); append(builder,"Attack Angle",String.format("%1.0f",rt.attackAngle)); append(builder,"Attack Power",String.format("%1.0f",rt.attackPower)); append(builder,"Attack Delay",String.format("%d",rt.attackDelay)); String attacks; if(rt.canAttackAir && rt.canAttackGround) attacks = "Air, Ground"; else if(rt.canAttackAir) attacks = "Air"; else attacks = "Ground"; append(builder,"Attacks",attacks); } } catch(Exception e) { e.printStackTrace(); } return builder.toString(); }
public String toString(String comp) { RobotType rt; try { rt = RobotType.valueOf(comp); } catch(IllegalArgumentException e) { return null; } StringBuilder builder = new StringBuilder(); try { append(builder,"Level",rt.level.name()); append(builder,"Max Energon",String.format("%1.0f",rt.maxEnergon)); append(builder,"Max Flux",String.format("%1.0f", rt.maxFlux)); if(rt.spawnCost>0) append(builder,"Spawn Cost",String.format("%1.0f",rt.spawnCost)); if(rt.moveDelayOrthogonal>0) { append(builder,"Move Delay Orthogonal",String.format("%d",rt.moveDelayOrthogonal)); append(builder,"Move Delay Diagonal",String.format("%d",rt.moveDelayDiagonal)); // display cost for archons even though it's zero append(builder,"Move Cost",String.format("%1.1f",rt.moveCost)); } if(rt.sensorAngle > 0) { append(builder,"Sensor Radius Squared",String.format("%d",rt.sensorRadiusSquared)); append(builder,"Sensor Angle",String.format("%1.0f",rt.sensorAngle)); } if(rt.canAttackAir || rt.canAttackGround) { append(builder,"Min Attack Radius Squared",String.format("%d",rt.attackRadiusMinSquared)); append(builder,"Max Attack Radius Squared",String.format("%d",rt.attackRadiusMaxSquared)); append(builder,"Attack Angle",String.format("%1.0f",rt.attackAngle)); append(builder,"Attack Power",String.format("%1.1f",rt.attackPower)); append(builder,"Attack Delay",String.format("%d",rt.attackDelay)); String attacks; if(rt.canAttackAir && rt.canAttackGround) attacks = "Air, Ground"; else if(rt.canAttackAir) attacks = "Air"; else attacks = "Ground"; append(builder,"Attacks",attacks); } } catch(Exception e) { e.printStackTrace(); } return builder.toString(); }
diff --git a/src/main/java/org/oztrack/controller/UserController.java b/src/main/java/org/oztrack/controller/UserController.java index 344e7750..efd20e1c 100644 --- a/src/main/java/org/oztrack/controller/UserController.java +++ b/src/main/java/org/oztrack/controller/UserController.java @@ -1,111 +1,113 @@ package org.oztrack.controller; import org.apache.commons.lang3.StringUtils; import org.oztrack.app.OzTrackApplication; import org.oztrack.app.OzTrackConfiguration; import org.oztrack.data.access.UserDao; import org.oztrack.data.model.User; import org.oztrack.util.OzTrackUtil; import org.oztrack.validator.UserFormValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class UserController { @Autowired private OzTrackConfiguration configuration; @Autowired private UserDao userDao; @InitBinder("user") public void initUserBinder(WebDataBinder binder) { binder.setAllowedFields( "username", "title", "firstName", "lastName", "dataSpaceAgentDescription", "organisation", "email" ); } @ModelAttribute("user") public User getUser(@PathVariable(value="id") Long id) throws Exception { return userDao.getById(id); } @RequestMapping(value="/users/{id}/edit", method=RequestMethod.GET) public String getEditView( @ModelAttribute(value="user") User user, @RequestHeader(value="eppn", required=false) String aafIdHeader, @RequestParam(value="aafId", required=false) String aafIdParam, @RequestParam(value="update", defaultValue="false") boolean update ) { User currentUser = OzTrackUtil.getCurrentUser(SecurityContextHolder.getContext().getAuthentication(), userDao); if (currentUser == null || !currentUser.equals(user)) { return "redirect:/login"; } if (configuration.isAafEnabled()) { if (StringUtils.isNotBlank(aafIdParam) && StringUtils.equals(aafIdParam, aafIdHeader)) { user.setAafId(aafIdHeader); } } return "user-form"; } @RequestMapping(value="/users/{id}", method=RequestMethod.PUT) public String processUpdate( Model model, @ModelAttribute(value="user") User user, @RequestHeader(value="eppn", required=false) String aafIdHeader, @RequestParam(value="aafId", required=false) String aafIdParam, @RequestParam(value="password", required=false) String newPassword, @RequestParam(value="password2", required=false) String newPassword2, BindingResult bindingResult ) throws Exception { User currentUser = OzTrackUtil.getCurrentUser(SecurityContextHolder.getContext().getAuthentication(), userDao); if (currentUser == null || !currentUser.equals(user)) { return "redirect:/login"; } if (OzTrackApplication.getApplicationContext().isAafEnabled()) { if (StringUtils.isBlank(aafIdParam)) { user.setAafId(null); } - else if (StringUtils.equals(aafIdHeader, aafIdParam)) { - user.setAafId(aafIdHeader); - } - else { - throw new RuntimeException("Attempt to set AAF ID without being logged in"); + else if (!StringUtils.equals(user.getAafId(), aafIdParam)) { + if (StringUtils.equals(aafIdHeader, aafIdParam)) { + user.setAafId(aafIdHeader); + } + else { + throw new RuntimeException("Attempt to set AAF ID without being logged in"); + } } } new UserFormValidator(userDao).validate(user, bindingResult); if (!StringUtils.equals(newPassword, newPassword2)) { bindingResult.rejectValue("password", "error.password.mismatch", "Passwords do not match"); } else if (StringUtils.isBlank(user.getPassword()) && StringUtils.isBlank(user.getAafId())) { bindingResult.rejectValue("password", "error.empty.field", "Please enter password"); } if (bindingResult.hasErrors()) { return "user-form"; } if (StringUtils.isNotBlank(newPassword)) { user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt())); } userDao.save(user); return "redirect:/projects"; } }
true
true
public String processUpdate( Model model, @ModelAttribute(value="user") User user, @RequestHeader(value="eppn", required=false) String aafIdHeader, @RequestParam(value="aafId", required=false) String aafIdParam, @RequestParam(value="password", required=false) String newPassword, @RequestParam(value="password2", required=false) String newPassword2, BindingResult bindingResult ) throws Exception { User currentUser = OzTrackUtil.getCurrentUser(SecurityContextHolder.getContext().getAuthentication(), userDao); if (currentUser == null || !currentUser.equals(user)) { return "redirect:/login"; } if (OzTrackApplication.getApplicationContext().isAafEnabled()) { if (StringUtils.isBlank(aafIdParam)) { user.setAafId(null); } else if (StringUtils.equals(aafIdHeader, aafIdParam)) { user.setAafId(aafIdHeader); } else { throw new RuntimeException("Attempt to set AAF ID without being logged in"); } } new UserFormValidator(userDao).validate(user, bindingResult); if (!StringUtils.equals(newPassword, newPassword2)) { bindingResult.rejectValue("password", "error.password.mismatch", "Passwords do not match"); } else if (StringUtils.isBlank(user.getPassword()) && StringUtils.isBlank(user.getAafId())) { bindingResult.rejectValue("password", "error.empty.field", "Please enter password"); } if (bindingResult.hasErrors()) { return "user-form"; } if (StringUtils.isNotBlank(newPassword)) { user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt())); } userDao.save(user); return "redirect:/projects"; }
public String processUpdate( Model model, @ModelAttribute(value="user") User user, @RequestHeader(value="eppn", required=false) String aafIdHeader, @RequestParam(value="aafId", required=false) String aafIdParam, @RequestParam(value="password", required=false) String newPassword, @RequestParam(value="password2", required=false) String newPassword2, BindingResult bindingResult ) throws Exception { User currentUser = OzTrackUtil.getCurrentUser(SecurityContextHolder.getContext().getAuthentication(), userDao); if (currentUser == null || !currentUser.equals(user)) { return "redirect:/login"; } if (OzTrackApplication.getApplicationContext().isAafEnabled()) { if (StringUtils.isBlank(aafIdParam)) { user.setAafId(null); } else if (!StringUtils.equals(user.getAafId(), aafIdParam)) { if (StringUtils.equals(aafIdHeader, aafIdParam)) { user.setAafId(aafIdHeader); } else { throw new RuntimeException("Attempt to set AAF ID without being logged in"); } } } new UserFormValidator(userDao).validate(user, bindingResult); if (!StringUtils.equals(newPassword, newPassword2)) { bindingResult.rejectValue("password", "error.password.mismatch", "Passwords do not match"); } else if (StringUtils.isBlank(user.getPassword()) && StringUtils.isBlank(user.getAafId())) { bindingResult.rejectValue("password", "error.empty.field", "Please enter password"); } if (bindingResult.hasErrors()) { return "user-form"; } if (StringUtils.isNotBlank(newPassword)) { user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt())); } userDao.save(user); return "redirect:/projects"; }
diff --git a/src/main/java/edu/usf/cutr/realtime/hart/services/HartToGtfsRealtimeServiceV2.java b/src/main/java/edu/usf/cutr/realtime/hart/services/HartToGtfsRealtimeServiceV2.java index 2456be4..b051ae1 100644 --- a/src/main/java/edu/usf/cutr/realtime/hart/services/HartToGtfsRealtimeServiceV2.java +++ b/src/main/java/edu/usf/cutr/realtime/hart/services/HartToGtfsRealtimeServiceV2.java @@ -1,352 +1,356 @@ /** * Copyright 2012 University of South Florida * * 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 edu.usf.cutr.realtime.hart.services; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Singleton; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeLibrary; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeMutableProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.transit.realtime.GtfsRealtime.FeedEntity; import com.google.transit.realtime.GtfsRealtime.FeedMessage; import com.google.transit.realtime.GtfsRealtime.Position; import com.google.transit.realtime.GtfsRealtime.TripDescriptor; import com.google.transit.realtime.GtfsRealtime.TripUpdate; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate; import com.google.transit.realtime.GtfsRealtime.VehicleDescriptor; import com.google.transit.realtime.GtfsRealtime.VehiclePosition; import com.google.transit.realtime.GtfsRealtimeOneBusAway; import com.google.transit.realtime.GtfsRealtimeOneBusAway.OneBusAwayTripUpdate; import edu.usf.cutr.realtime.hart.models.TransitDataV2; import edu.usf.cutr.realtime.hart.rt.fake.StopTimesCsvDecrypt; import edu.usf.cutr.realtime.hart.sql.ResultSetDecryptV2; import edu.usf.cutr.realtime.hart.sql.RetrieveTransitDataV2; import edu.usf.cutr.realtime.hart.sql.connection.Properties; /** * * @author Khoa Tran * */ @Singleton public class HartToGtfsRealtimeServiceV2{ private static final Logger _log = LoggerFactory.getLogger(HartToGtfsRealtimeServiceV2.class); private volatile FeedMessage _tripUpdatesMessage = GtfsRealtimeLibrary.createFeedMessageBuilder().build(); private volatile FeedMessage _vehiclePositionsMessage = GtfsRealtimeLibrary.createFeedMessageBuilder().build(); // private final FeedMessage _alertsMessage = GtfsRealtimeLibrary.createFeedMessageBuilder().build(); private GtfsRealtimeMutableProvider _gtfsRealtimeProvider; private ScheduledExecutorService _executor; private Connection _conn = null; private RetrieveTransitDataV2 _rtd = null; private final String TRIP_UPDATE_PREFIX = "trip_update_"; private final String VEHICLE_POSITION_PREFIX = "vehicle_position_"; /** * How often data will be updated, in seconds */ private int _refreshInterval = 30; public HartToGtfsRealtimeServiceV2(){ Properties connProps = getConnectionProperties(); _conn = getConnection(connProps); _rtd = new RetrieveTransitDataV2(); } public void setRefreshInterval(int refreshInterval) { _refreshInterval = refreshInterval; } @Inject public void setGtfsRealtimeProvider(GtfsRealtimeMutableProvider gtfsRealtimeProvider) { _gtfsRealtimeProvider = gtfsRealtimeProvider; } @PostConstruct public void start() { _log.info("starting GTFS-realtime service"); _executor = Executors.newSingleThreadScheduledExecutor(); _executor.scheduleAtFixedRate(new RefreshTransitData(), 0, _refreshInterval, TimeUnit.SECONDS); } @PreDestroy public void stop() { _log.info("stopping GTFS-realtime service"); _executor.shutdownNow(); } private Properties getConnectionProperties(){ Properties connProps = new Properties(); try { connProps.load(new FileInputStream("..\\config.properties")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block _log.error("Config file is not found: " + e.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block _log.error("Failed to read connection properties: " + e.getMessage()); } return connProps; } private Connection getConnection(Properties connProps){ Connection conn = null; String connString = "jdbc:sqlserver://" + connProps.getHost() + ":" + connProps.getPortNumber() + ";database=" + connProps.getDatabaseName() + ";user=" + connProps.getUser() + ";password=" + connProps.getPassword(); _log.info("Connection String: "+connString); try { conn = DriverManager.getConnection(connString); } catch (SQLException e) { // TODO Auto-generated catch block _log.error("Failed to connect to " + connProps.getDatabaseName() + " database: " + e.getMessage()); } return conn; } private ArrayList<TransitDataV2> getOrbcadTransitData() throws Exception{ ResultSet rs = _rtd.executeQuery(_conn); if(rs == null){ _conn = null; throw new Exception("ResultSet for SELECT query is null"); } ResultSetDecryptV2 rsd = new ResultSetDecryptV2(rs); ArrayList<TransitDataV2> transitData = rsd.decrypt(); _log.info(transitData.toString()); return transitData; } private ArrayList<TransitDataV2> getOrbcadTransitDataFake(){ StopTimesCsvDecrypt stcd = new StopTimesCsvDecrypt(); ArrayList<TransitDataV2> transitData = stcd.decrypt(); _log.info(transitData.toString()); return transitData; } private void buildTripUpdates(ArrayList<TransitDataV2> transitData){ FeedMessage.Builder tripUpdates = GtfsRealtimeLibrary.createFeedMessageBuilder(); ArrayList<StopTimeUpdate> stopTimeUpdateSet = new ArrayList<StopTimeUpdate>(); for(int i=0; i<transitData.size(); i++){ TransitDataV2 td = transitData.get(i); String vehicleId = td.getVehicleId(); int delay = td.getDelay(); // in seconds double lat = td.getVehicleLat(); double lon = td.getVehicleLon(); int speed = td.getVehicleSpeed(); int bearing = td.getVehicleBearing(); int seq = td.getSequenceNumber(); Timestamp time = td.getVehicleTime(); String stopId = td.getStopId(); String routeId = td.getRouteId(); String tripId = td.getTripId(); /** * StopTime Event */ StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder(); arrival.setDelay(delay); arrival.setUncertainty(30); /** * StopTime Update */ StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); if(stopId==null){ continue; } stopTimeUpdate.setStopSequence(seq); stopTimeUpdate.setStopId(stopId); stopTimeUpdate.setArrival(arrival); + // Google requested adding departure delays for Google Transit (Issue #7). + // Since we don't have explicit departure delay info from OrbCAD, + // at the suggestion of Google we will just use arrival delay as a substitute + stopTimeUpdate.setDeparture(arrival); stopTimeUpdateSet.add(stopTimeUpdate.build()); if(i!=transitData.size()-1 && tripId.equalsIgnoreCase(transitData.get(i+1).getTripId())){ continue; } /** * Trip Descriptor */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); tripDescriptor.setTripId(tripId); /** * Vehicle Descriptor */ VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); if(vehicleId!=null && !vehicleId.isEmpty()) { vehicleDescriptor.setId(vehicleId); } TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.addAllStopTimeUpdate(stopTimeUpdateSet); stopTimeUpdateSet.clear(); tripUpdate.setTrip(tripDescriptor); if(vehicleId!=null && !vehicleId.isEmpty()) { tripUpdate.setVehicle(vehicleDescriptor); } // OneBusAwayTripUpdate.Builder obaTripUpdate = OneBusAwayTripUpdate.newBuilder(); // obaTripUpdate.setDelay(delay); // tripUpdate.setExtension(GtfsRealtimeOneBusAway.obaTripUpdate, obaTripUpdate.build()); FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(TRIP_UPDATE_PREFIX+tripId); tripUpdateEntity.setTripUpdate(tripUpdate); tripUpdates.addEntity(tripUpdateEntity); } _tripUpdatesMessage = tripUpdates.build(); _gtfsRealtimeProvider.setTripUpdates(_tripUpdatesMessage); } private void buildVehiclePositions(ArrayList<TransitDataV2> transitData){ FeedMessage.Builder vehiclePositions = GtfsRealtimeLibrary.createFeedMessageBuilder(); HashSet<String> vehicleIdSet = new HashSet<String>(); for(int i=0; i<transitData.size(); i++){ TransitDataV2 td = transitData.get(i); String vehicleId = td.getVehicleId(); int delay = td.getDelay(); // in seconds double lat = td.getVehicleLat(); double lon = td.getVehicleLon(); int speed = td.getVehicleSpeed(); int bearing = td.getVehicleBearing(); int seq = td.getSequenceNumber(); Timestamp time = td.getVehicleTime(); String stopId = td.getStopId(); String routeId = td.getRouteId(); String tripId = td.getTripId(); if(!vehicleIdSet.contains(vehicleId)){ vehicleIdSet.add(vehicleId); } else { continue; } /** * Trip Descriptor */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); tripDescriptor.setTripId(tripId); /** * Vehicle Descriptor */ VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); vehicleDescriptor.setId(vehicleId); /** * To construct our VehiclePosition, we create a position for the vehicle. * We add the position to a VehiclePosition builder, along with the trip * and vehicle descriptors. */ Position.Builder position = Position.newBuilder(); position.setLatitude((float) lat); position.setLongitude((float) lon); position.setSpeed((float) speed); position.setBearing((float) bearing); VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder(); vehiclePosition.setPosition(position); vehiclePosition.setTrip(tripDescriptor); vehiclePosition.setVehicle(vehicleDescriptor); FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder(); vehiclePositionEntity.setId(VEHICLE_POSITION_PREFIX+vehicleId); vehiclePositionEntity.setVehicle(vehiclePosition); vehiclePositions.addEntity(vehiclePositionEntity); } _vehiclePositionsMessage = vehiclePositions.build(); _gtfsRealtimeProvider.setVehiclePositions(_vehiclePositionsMessage); } public void writeGtfsRealtimeOutput() throws Exception { _log.info("Writing Hart GTFS realtime..."); if(_conn==null){ Properties connProps = getConnectionProperties(); _conn = getConnection(connProps); } if(_conn==null) { throw new Exception("Database Connection is null"); } else { ArrayList<TransitDataV2> transitData = getOrbcadTransitData(); // ArrayList<TransitDataV2> transitData = getOrbcadTransitDataFake(); buildTripUpdates(transitData); buildVehiclePositions(transitData); _log.info("tripUpdates = "+_tripUpdatesMessage.getEntityCount()); _log.info("vehiclePositions = "+_vehiclePositionsMessage.getEntityCount()); } } private class RefreshTransitData implements Runnable { @Override public void run() { try { _log.info("refreshing vehicles"); writeGtfsRealtimeOutput(); } catch (Exception ex) { _log.error("Failed to refresh TransitData: " + ex.getMessage()); } } } }
true
true
private void buildTripUpdates(ArrayList<TransitDataV2> transitData){ FeedMessage.Builder tripUpdates = GtfsRealtimeLibrary.createFeedMessageBuilder(); ArrayList<StopTimeUpdate> stopTimeUpdateSet = new ArrayList<StopTimeUpdate>(); for(int i=0; i<transitData.size(); i++){ TransitDataV2 td = transitData.get(i); String vehicleId = td.getVehicleId(); int delay = td.getDelay(); // in seconds double lat = td.getVehicleLat(); double lon = td.getVehicleLon(); int speed = td.getVehicleSpeed(); int bearing = td.getVehicleBearing(); int seq = td.getSequenceNumber(); Timestamp time = td.getVehicleTime(); String stopId = td.getStopId(); String routeId = td.getRouteId(); String tripId = td.getTripId(); /** * StopTime Event */ StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder(); arrival.setDelay(delay); arrival.setUncertainty(30); /** * StopTime Update */ StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); if(stopId==null){ continue; } stopTimeUpdate.setStopSequence(seq); stopTimeUpdate.setStopId(stopId); stopTimeUpdate.setArrival(arrival); stopTimeUpdateSet.add(stopTimeUpdate.build()); if(i!=transitData.size()-1 && tripId.equalsIgnoreCase(transitData.get(i+1).getTripId())){ continue; } /** * Trip Descriptor */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); tripDescriptor.setTripId(tripId); /** * Vehicle Descriptor */ VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); if(vehicleId!=null && !vehicleId.isEmpty()) { vehicleDescriptor.setId(vehicleId); } TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.addAllStopTimeUpdate(stopTimeUpdateSet); stopTimeUpdateSet.clear(); tripUpdate.setTrip(tripDescriptor); if(vehicleId!=null && !vehicleId.isEmpty()) { tripUpdate.setVehicle(vehicleDescriptor); } // OneBusAwayTripUpdate.Builder obaTripUpdate = OneBusAwayTripUpdate.newBuilder(); // obaTripUpdate.setDelay(delay); // tripUpdate.setExtension(GtfsRealtimeOneBusAway.obaTripUpdate, obaTripUpdate.build()); FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(TRIP_UPDATE_PREFIX+tripId); tripUpdateEntity.setTripUpdate(tripUpdate); tripUpdates.addEntity(tripUpdateEntity); } _tripUpdatesMessage = tripUpdates.build(); _gtfsRealtimeProvider.setTripUpdates(_tripUpdatesMessage); }
private void buildTripUpdates(ArrayList<TransitDataV2> transitData){ FeedMessage.Builder tripUpdates = GtfsRealtimeLibrary.createFeedMessageBuilder(); ArrayList<StopTimeUpdate> stopTimeUpdateSet = new ArrayList<StopTimeUpdate>(); for(int i=0; i<transitData.size(); i++){ TransitDataV2 td = transitData.get(i); String vehicleId = td.getVehicleId(); int delay = td.getDelay(); // in seconds double lat = td.getVehicleLat(); double lon = td.getVehicleLon(); int speed = td.getVehicleSpeed(); int bearing = td.getVehicleBearing(); int seq = td.getSequenceNumber(); Timestamp time = td.getVehicleTime(); String stopId = td.getStopId(); String routeId = td.getRouteId(); String tripId = td.getTripId(); /** * StopTime Event */ StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder(); arrival.setDelay(delay); arrival.setUncertainty(30); /** * StopTime Update */ StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); if(stopId==null){ continue; } stopTimeUpdate.setStopSequence(seq); stopTimeUpdate.setStopId(stopId); stopTimeUpdate.setArrival(arrival); // Google requested adding departure delays for Google Transit (Issue #7). // Since we don't have explicit departure delay info from OrbCAD, // at the suggestion of Google we will just use arrival delay as a substitute stopTimeUpdate.setDeparture(arrival); stopTimeUpdateSet.add(stopTimeUpdate.build()); if(i!=transitData.size()-1 && tripId.equalsIgnoreCase(transitData.get(i+1).getTripId())){ continue; } /** * Trip Descriptor */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); tripDescriptor.setTripId(tripId); /** * Vehicle Descriptor */ VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); if(vehicleId!=null && !vehicleId.isEmpty()) { vehicleDescriptor.setId(vehicleId); } TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.addAllStopTimeUpdate(stopTimeUpdateSet); stopTimeUpdateSet.clear(); tripUpdate.setTrip(tripDescriptor); if(vehicleId!=null && !vehicleId.isEmpty()) { tripUpdate.setVehicle(vehicleDescriptor); } // OneBusAwayTripUpdate.Builder obaTripUpdate = OneBusAwayTripUpdate.newBuilder(); // obaTripUpdate.setDelay(delay); // tripUpdate.setExtension(GtfsRealtimeOneBusAway.obaTripUpdate, obaTripUpdate.build()); FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(TRIP_UPDATE_PREFIX+tripId); tripUpdateEntity.setTripUpdate(tripUpdate); tripUpdates.addEntity(tripUpdateEntity); } _tripUpdatesMessage = tripUpdates.build(); _gtfsRealtimeProvider.setTripUpdates(_tripUpdatesMessage); }
diff --git a/omod/src/test/java/org/openmrs/module/emr/page/controller/consult/ConsultPageControllerTest.java b/omod/src/test/java/org/openmrs/module/emr/page/controller/consult/ConsultPageControllerTest.java index b877c630..cb6faf6b 100644 --- a/omod/src/test/java/org/openmrs/module/emr/page/controller/consult/ConsultPageControllerTest.java +++ b/omod/src/test/java/org/openmrs/module/emr/page/controller/consult/ConsultPageControllerTest.java @@ -1,123 +1,123 @@ /* * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.emr.page.controller.consult; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatcher; import org.mockito.MockitoAnnotations; import org.openmrs.Concept; import org.openmrs.ConceptName; import org.openmrs.Location; import org.openmrs.Patient; import org.openmrs.PersonName; import org.openmrs.Provider; import org.openmrs.api.ConceptService; import org.openmrs.module.emr.EmrConstants; import org.openmrs.module.emr.EmrContext; import org.openmrs.module.emr.EmrProperties; import org.openmrs.module.emr.TestUiUtils; import org.openmrs.module.emr.consult.ConsultNote; import org.openmrs.module.emr.consult.ConsultService; import org.openmrs.module.emrapi.diagnosis.CodedOrFreeTextAnswer; import org.openmrs.module.emrapi.diagnosis.Diagnosis; import org.springframework.mock.web.MockHttpSession; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.Mock; /** * */ public class ConsultPageControllerTest { @Mock ConsultService consultService; @Mock ConceptService conceptService; @Mock EmrProperties emrProperties; @Before public void initMocks() { MockitoAnnotations.initMocks(this); } @Test public void testSubmit() throws Exception { int primaryConceptNameId = 2460; int secondaryConceptId = 3; final String secondaryText = "Fatigue from too much testing"; final String freeTextComments = "30 year old male, presenting with..."; String diagnosisJson1 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"PRIMARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.CONCEPT_NAME_PREFIX + primaryConceptNameId + "\" }"; String diagnosisJson2 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"SECONDARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.CONCEPT_PREFIX + secondaryConceptId + "\" }"; String diagnosisJson3 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"SECONDARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.NON_CODED_PREFIX + secondaryText + "\" }"; Concept conceptFor2460 = new Concept(); final ConceptName conceptName2460 = new ConceptName(); conceptName2460.setConcept(conceptFor2460); final Concept concept3 = new Concept(); when(conceptService.getConceptName(primaryConceptNameId)).thenReturn(conceptName2460); when(conceptService.getConcept(secondaryConceptId)).thenReturn(concept3); Patient patient = new Patient(); patient.addName(new PersonName("Jean", "Paul", "Marie")); final Location sessionLocation = new Location(); final Provider currentProvider = new Provider(); EmrContext emrContext = new EmrContext(); emrContext.setSessionLocation(sessionLocation); emrContext.setCurrentProvider(currentProvider); MockHttpSession httpSession = new MockHttpSession(); ConsultPageController controller = new ConsultPageController(); String result = controller.post(patient, asList(diagnosisJson1, diagnosisJson2, diagnosisJson3), freeTextComments, httpSession, consultService, conceptService, emrProperties, emrContext, new TestUiUtils()); assertThat(result, startsWith("redirect:")); assertThat(httpSession.getAttribute(EmrConstants.SESSION_ATTRIBUTE_INFO_MESSAGE), notNullValue()); verify(consultService).saveConsultNote(argThat(new ArgumentMatcher<ConsultNote>() { @Override public boolean matches(Object o) { ConsultNote actual = (ConsultNote) o; - return actual.getPrimaryDiagnosis().equals(new Diagnosis(new CodedOrFreeTextAnswer(conceptName2460), Diagnosis.Order.PRIMARY)) && - containsInAnyOrder(new Diagnosis(new CodedOrFreeTextAnswer(concept3), Diagnosis.Order.SECONDARY), - new Diagnosis(new CodedOrFreeTextAnswer(secondaryText), Diagnosis.Order.SECONDARY)).matches(actual.getAdditionalDiagnoses()) && + return containsInAnyOrder(new Diagnosis(new CodedOrFreeTextAnswer(conceptName2460), Diagnosis.Order.PRIMARY), + new Diagnosis(new CodedOrFreeTextAnswer(concept3), Diagnosis.Order.SECONDARY), + new Diagnosis(new CodedOrFreeTextAnswer(secondaryText), Diagnosis.Order.SECONDARY)).matches(actual.getDiagnoses()) && actual.getComments().equals(freeTextComments) && actual.getEncounterLocation().equals(sessionLocation) && actual.getClinician().equals(currentProvider); } })); } }
true
true
public void testSubmit() throws Exception { int primaryConceptNameId = 2460; int secondaryConceptId = 3; final String secondaryText = "Fatigue from too much testing"; final String freeTextComments = "30 year old male, presenting with..."; String diagnosisJson1 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"PRIMARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.CONCEPT_NAME_PREFIX + primaryConceptNameId + "\" }"; String diagnosisJson2 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"SECONDARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.CONCEPT_PREFIX + secondaryConceptId + "\" }"; String diagnosisJson3 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"SECONDARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.NON_CODED_PREFIX + secondaryText + "\" }"; Concept conceptFor2460 = new Concept(); final ConceptName conceptName2460 = new ConceptName(); conceptName2460.setConcept(conceptFor2460); final Concept concept3 = new Concept(); when(conceptService.getConceptName(primaryConceptNameId)).thenReturn(conceptName2460); when(conceptService.getConcept(secondaryConceptId)).thenReturn(concept3); Patient patient = new Patient(); patient.addName(new PersonName("Jean", "Paul", "Marie")); final Location sessionLocation = new Location(); final Provider currentProvider = new Provider(); EmrContext emrContext = new EmrContext(); emrContext.setSessionLocation(sessionLocation); emrContext.setCurrentProvider(currentProvider); MockHttpSession httpSession = new MockHttpSession(); ConsultPageController controller = new ConsultPageController(); String result = controller.post(patient, asList(diagnosisJson1, diagnosisJson2, diagnosisJson3), freeTextComments, httpSession, consultService, conceptService, emrProperties, emrContext, new TestUiUtils()); assertThat(result, startsWith("redirect:")); assertThat(httpSession.getAttribute(EmrConstants.SESSION_ATTRIBUTE_INFO_MESSAGE), notNullValue()); verify(consultService).saveConsultNote(argThat(new ArgumentMatcher<ConsultNote>() { @Override public boolean matches(Object o) { ConsultNote actual = (ConsultNote) o; return actual.getPrimaryDiagnosis().equals(new Diagnosis(new CodedOrFreeTextAnswer(conceptName2460), Diagnosis.Order.PRIMARY)) && containsInAnyOrder(new Diagnosis(new CodedOrFreeTextAnswer(concept3), Diagnosis.Order.SECONDARY), new Diagnosis(new CodedOrFreeTextAnswer(secondaryText), Diagnosis.Order.SECONDARY)).matches(actual.getAdditionalDiagnoses()) && actual.getComments().equals(freeTextComments) && actual.getEncounterLocation().equals(sessionLocation) && actual.getClinician().equals(currentProvider); } })); }
public void testSubmit() throws Exception { int primaryConceptNameId = 2460; int secondaryConceptId = 3; final String secondaryText = "Fatigue from too much testing"; final String freeTextComments = "30 year old male, presenting with..."; String diagnosisJson1 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"PRIMARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.CONCEPT_NAME_PREFIX + primaryConceptNameId + "\" }"; String diagnosisJson2 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"SECONDARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.CONCEPT_PREFIX + secondaryConceptId + "\" }"; String diagnosisJson3 = "{ \"certainty\": \"PRESUMED\", \"diagnosisOrder\": \"SECONDARY\", \"diagnosis\": \"" + CodedOrFreeTextAnswer.NON_CODED_PREFIX + secondaryText + "\" }"; Concept conceptFor2460 = new Concept(); final ConceptName conceptName2460 = new ConceptName(); conceptName2460.setConcept(conceptFor2460); final Concept concept3 = new Concept(); when(conceptService.getConceptName(primaryConceptNameId)).thenReturn(conceptName2460); when(conceptService.getConcept(secondaryConceptId)).thenReturn(concept3); Patient patient = new Patient(); patient.addName(new PersonName("Jean", "Paul", "Marie")); final Location sessionLocation = new Location(); final Provider currentProvider = new Provider(); EmrContext emrContext = new EmrContext(); emrContext.setSessionLocation(sessionLocation); emrContext.setCurrentProvider(currentProvider); MockHttpSession httpSession = new MockHttpSession(); ConsultPageController controller = new ConsultPageController(); String result = controller.post(patient, asList(diagnosisJson1, diagnosisJson2, diagnosisJson3), freeTextComments, httpSession, consultService, conceptService, emrProperties, emrContext, new TestUiUtils()); assertThat(result, startsWith("redirect:")); assertThat(httpSession.getAttribute(EmrConstants.SESSION_ATTRIBUTE_INFO_MESSAGE), notNullValue()); verify(consultService).saveConsultNote(argThat(new ArgumentMatcher<ConsultNote>() { @Override public boolean matches(Object o) { ConsultNote actual = (ConsultNote) o; return containsInAnyOrder(new Diagnosis(new CodedOrFreeTextAnswer(conceptName2460), Diagnosis.Order.PRIMARY), new Diagnosis(new CodedOrFreeTextAnswer(concept3), Diagnosis.Order.SECONDARY), new Diagnosis(new CodedOrFreeTextAnswer(secondaryText), Diagnosis.Order.SECONDARY)).matches(actual.getDiagnoses()) && actual.getComments().equals(freeTextComments) && actual.getEncounterLocation().equals(sessionLocation) && actual.getClinician().equals(currentProvider); } })); }
diff --git a/loci/formats/ome/OMEXMLMetadata.java b/loci/formats/ome/OMEXMLMetadata.java index 0cac614d9..8873b9a90 100644 --- a/loci/formats/ome/OMEXMLMetadata.java +++ b/loci/formats/ome/OMEXMLMetadata.java @@ -1,215 +1,215 @@ // // OMEXMLMetadata.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.ome; import java.util.Arrays; import java.util.Vector; import loci.formats.*; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; import ome.xml.DOMUtil; import ome.xml.OMEXMLNode; import org.w3c.dom.Element; /** * A utility class for constructing and manipulating OME-XML DOMs. * It is the superclass for for all versions of OME-XML. It requires the * ome.xml package to compile (part of ome-java.jar). * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/ome/OMEXMLMetadata.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/ome/OMEXMLMetadata.java">SVN</a></dd></dl> * * @author Curtis Rueden ctrueden at wisc.edu * @author Melissa Linkert linkert at wisc.edu */ public abstract class OMEXMLMetadata implements MetadataStore, MetadataRetrieve { // -- Fields -- /** The root element of OME-XML. */ protected OMEXMLNode root; /** Each channel's global minimum. */ protected double[] channelMinimum; /** Each channel's global maximum. */ protected double[] channelMaximum; /** DOM element that backs the first Image's CustomAttributes node. */ private Element imageCA; // -- Constructors -- /** Creates a new OME-XML metadata object. */ public OMEXMLMetadata() { } // -- OMEXMLMetadata API methods -- /** * Dumps the given OME-XML DOM tree to a string. * @return OME-XML as a string. */ public abstract String dumpXML(); /** Adds the key/value pair as a new OriginalMetadata node. */ public void populateOriginalMetadata(String key, String value) { if (imageCA == null) { Element ome = root.getDOMElement(); Element image = DOMUtil.getChildElement("Image", ome); if (image == null) { - setImageName(null, 0); // force creation of Image element + setImageName("", 0); // HACK - force creation of Image element image = DOMUtil.getChildElement("Image", ome); } imageCA = DOMUtil.getChildElement("CustomAttributes", image); if (imageCA == null) { imageCA = DOMUtil.createChild(image, "CustomAttributes", true); } } final String originalMetadata = "OriginalMetadata"; Vector omList = DOMUtil.getChildElements(originalMetadata, imageCA); if (omList.size() == 0) { Element std = DOMUtil.createChild(root.getDOMElement(), "SemanticTypeDefinitions"); DOMUtil.setAttribute("xmlns", "http://www.openmicroscopy.org/XMLschemas/STD/RC2/STD.xsd", std); Element st = DOMUtil.createChild(std, "SemanticType"); DOMUtil.setAttribute("Name", originalMetadata, st); DOMUtil.setAttribute("AppliesTo", "I", st); Element nameElement = DOMUtil.createChild(st, "Element"); DOMUtil.setAttribute("Name", "Name", nameElement); DOMUtil.setAttribute("DBLocation", "ORIGINAL_METADATA.NAME", nameElement); DOMUtil.setAttribute("DataType", "string", nameElement); Element valueElement = DOMUtil.createChild(st, "Element"); DOMUtil.setAttribute("Name", "Value", valueElement); DOMUtil.setAttribute("DBLocation", "ORIGINAL_METADATA.VALUE", valueElement); DOMUtil.setAttribute("DataType", "string", valueElement); } Element om = DOMUtil.createChild(imageCA, originalMetadata); DOMUtil.setAttribute("ID", root.makeID(originalMetadata), om); DOMUtil.setAttribute("Name", key, om); DOMUtil.setAttribute("Value", value, om); } // -- MetadataRetrieve API methods -- /* @see loci.formats.MetadataRetrieve#getGlobalMin(Integer, Integer) */ public Double getGlobalMin(Integer pixels, Integer channel) { // TODO FIX -- why no usage of pixels? int ndx = i2i(channel); if (channelMinimum == null || ndx >= channelMinimum.length) return null; return new Double(channelMinimum[ndx]); } /* @see loci.formats.MetadataRetrieve#getGlobalMax(Integer, Integer) */ public Double getGlobalMax(Integer pixels, Integer channel) { // TODO FIX -- why no usage of pixels? int ndx = i2i(channel); if (channelMaximum == null || ndx >= channelMaximum.length) return null; return new Double(channelMaximum[ndx]); } // -- MetadataStore API methods -- /* @see loci.formats.MetadataStore#getRoot() */ public Object getRoot() { return root; } /* * @see loci.formats.MetadataStore#setChannelGlobalMinMax(int, * Double, Double, Integer) */ public void setChannelGlobalMinMax(int channel, Double globalMin, Double globalMax, Integer i) { int ndx = i == null ? 0 : i.intValue(); // Since we will need this information for default display options creation // but don't have a place really to store this in OME-XML we're just going // to store it in instance variables. if (channelMinimum == null || channelMinimum.length <= channel) { // expand channel minimum list double[] min = new double[channel + 1]; Arrays.fill(min, Double.NaN); if (channelMinimum != null) { System.arraycopy(channelMinimum, 0, min, 0, channelMinimum.length); } channelMinimum = min; } if (channelMaximum == null || channelMaximum.length <= channel) { // expand channel maximum list double[] max = new double[channel + 1]; Arrays.fill(max, Double.NaN); if (channelMaximum != null) { System.arraycopy(channelMaximum, 0, max, 0, channelMaximum.length); } channelMaximum = max; } // Now that the array initialization hocus-pocus has been completed // let's do the work. channelMinimum[channel] = globalMin.doubleValue(); channelMaximum[channel] = globalMax.doubleValue(); } // -- Helper methods -- /** Issues the given message as a warning. */ protected void warn(String msg) { LogTools.println(msg); } /** Converts the given Integer into a primitive int. */ protected int i2i(Integer i) { return i == null ? 0 : i.intValue(); } // -- Type conversion methods -- /** Converts Dimensions.PixelSizeC Float value to Integer. */ protected Integer dimensionsPixelSizeCToInteger(Float value) { return new Integer(value.intValue()); } /** Converts Integer value to Dimensions.PixelSizeC Float. */ protected Float dimensionsPixelSizeCFromInteger(Integer value) { return new Float(value.floatValue()); } /** Converts Laser.FrequencyDoubled Boolean value to Integer. */ protected Integer laserFrequencyDoubledToInteger(Boolean value) { return new Integer(value.booleanValue() ? 2 : 1); } /** Converts Integer value to Laser.FrequencyDoubled Boolean. */ protected Boolean laserFrequencyDoubledFromInteger(Integer value) { return value.intValue() == 2 ? Boolean.TRUE : Boolean.FALSE; } }
true
true
public void populateOriginalMetadata(String key, String value) { if (imageCA == null) { Element ome = root.getDOMElement(); Element image = DOMUtil.getChildElement("Image", ome); if (image == null) { setImageName(null, 0); // force creation of Image element image = DOMUtil.getChildElement("Image", ome); } imageCA = DOMUtil.getChildElement("CustomAttributes", image); if (imageCA == null) { imageCA = DOMUtil.createChild(image, "CustomAttributes", true); } } final String originalMetadata = "OriginalMetadata"; Vector omList = DOMUtil.getChildElements(originalMetadata, imageCA); if (omList.size() == 0) { Element std = DOMUtil.createChild(root.getDOMElement(), "SemanticTypeDefinitions"); DOMUtil.setAttribute("xmlns", "http://www.openmicroscopy.org/XMLschemas/STD/RC2/STD.xsd", std); Element st = DOMUtil.createChild(std, "SemanticType"); DOMUtil.setAttribute("Name", originalMetadata, st); DOMUtil.setAttribute("AppliesTo", "I", st); Element nameElement = DOMUtil.createChild(st, "Element"); DOMUtil.setAttribute("Name", "Name", nameElement); DOMUtil.setAttribute("DBLocation", "ORIGINAL_METADATA.NAME", nameElement); DOMUtil.setAttribute("DataType", "string", nameElement); Element valueElement = DOMUtil.createChild(st, "Element"); DOMUtil.setAttribute("Name", "Value", valueElement); DOMUtil.setAttribute("DBLocation", "ORIGINAL_METADATA.VALUE", valueElement); DOMUtil.setAttribute("DataType", "string", valueElement); } Element om = DOMUtil.createChild(imageCA, originalMetadata); DOMUtil.setAttribute("ID", root.makeID(originalMetadata), om); DOMUtil.setAttribute("Name", key, om); DOMUtil.setAttribute("Value", value, om); }
public void populateOriginalMetadata(String key, String value) { if (imageCA == null) { Element ome = root.getDOMElement(); Element image = DOMUtil.getChildElement("Image", ome); if (image == null) { setImageName("", 0); // HACK - force creation of Image element image = DOMUtil.getChildElement("Image", ome); } imageCA = DOMUtil.getChildElement("CustomAttributes", image); if (imageCA == null) { imageCA = DOMUtil.createChild(image, "CustomAttributes", true); } } final String originalMetadata = "OriginalMetadata"; Vector omList = DOMUtil.getChildElements(originalMetadata, imageCA); if (omList.size() == 0) { Element std = DOMUtil.createChild(root.getDOMElement(), "SemanticTypeDefinitions"); DOMUtil.setAttribute("xmlns", "http://www.openmicroscopy.org/XMLschemas/STD/RC2/STD.xsd", std); Element st = DOMUtil.createChild(std, "SemanticType"); DOMUtil.setAttribute("Name", originalMetadata, st); DOMUtil.setAttribute("AppliesTo", "I", st); Element nameElement = DOMUtil.createChild(st, "Element"); DOMUtil.setAttribute("Name", "Name", nameElement); DOMUtil.setAttribute("DBLocation", "ORIGINAL_METADATA.NAME", nameElement); DOMUtil.setAttribute("DataType", "string", nameElement); Element valueElement = DOMUtil.createChild(st, "Element"); DOMUtil.setAttribute("Name", "Value", valueElement); DOMUtil.setAttribute("DBLocation", "ORIGINAL_METADATA.VALUE", valueElement); DOMUtil.setAttribute("DataType", "string", valueElement); } Element om = DOMUtil.createChild(imageCA, originalMetadata); DOMUtil.setAttribute("ID", root.makeID(originalMetadata), om); DOMUtil.setAttribute("Name", key, om); DOMUtil.setAttribute("Value", value, om); }
diff --git a/src/main/java/ru/jilime/documentum/Monitor.java b/src/main/java/ru/jilime/documentum/Monitor.java index a5c87d3..0e3c2b2 100644 --- a/src/main/java/ru/jilime/documentum/Monitor.java +++ b/src/main/java/ru/jilime/documentum/Monitor.java @@ -1,475 +1,475 @@ package ru.jilime.documentum; import com.documentum.com.DfClientX; import com.documentum.com.IDfClientX; import com.documentum.fc.client.*; import com.documentum.fc.common.DfException; import com.documentum.fc.common.DfLogger; import com.documentum.fc.common.IDfId; import com.documentum.fc.common.IDfLoginInfo; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.ParseException; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; public class Monitor { private static String OS = System.getProperty("os.name").toLowerCase(); public static void main(String[] args) throws DfException { Options options = construct(); IDfSession dfSession = initial(args, options); CommandLineParser parser = new BasicParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("S")) { System.out.println(getSessionCount(dfSession).toString()); } if (line.hasOption("i")) { System.out.println(statusOfIA(dfSession)); } if (line.hasOption("W")) { System.out.println(getDeadWorkflows(dfSession).toString()); } if (line.hasOption("b")) { System.out.println(getBadWorkitems(dfSession).toString()); } if (line.hasOption("F")) { if (checkFTSearch(dfSession)) System.out.print(0); } if (line.hasOption("C")) { if (fetchContent(dfSession)) System.out.print(0); } if (line.hasOption("q")) { System.out.println(getFTFailedQueueSize(dfSession, line.getOptionValue("q")).toString()); } if (line.hasOption("Q")) { System.out.println(getQueueSize(dfSession).toString()); } if (line.hasOption("Qt")) { - System.out.println(getQueueSize(dfSession).toString()); + System.out.println(getTotalQueueSize(dfSession).toString()); } } catch (Throwable t) { DfLogger.fatal(dfSession, t.getMessage(), null, t); DfLogger.error(Monitor.class, "Exception while parsing ", null, t); } finally { assert dfSession != null; dfSession.disconnect(); } } private static Options construct() { Options options = new Options(); options.addOption("u", "username", true, "user name in docbase"); options.addOption("p", "password", true, "password in docbase"); options.addOption("d", "docbase", true, "docbase name"); options.addOption("S", "sessions", false, "list sessions count"); options.addOption("i", "indexagent", false, "show indexagents statuses"); options.addOption("W", "workflows", false, "show bad workflows count"); options.addOption("b", "workitems", false, "show bad workitems count"); options.addOption("C", "content", false, "fetching content from docbase"); options.addOption("F", "search", false, "search in Fulltext"); options.addOption("q", "queue", true, "show total number of failed queued items (for user)"); options.addOption("Q", "queueitem", false, "show total number of queued items marked for deletion"); options.addOption("Qt", "totalqueueitem", false, "show total number of queue items"); return options; } private static IDfSession initial(String[] args, Options options) throws DfException { CommandLineParser parser = new BasicParser(); IDfSession session = null; String username = null; String password = null; String docbase = null; if (args.length < 1) { System.out.println("Class usage info:"); printUsage(options, System.out); } try { // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption("u")) { username = line.getOptionValue("u"); } if (line.hasOption("p")) { password = line.getOptionValue("p"); } if (line.hasOption("d")) { docbase = line.getOptionValue("d"); } session = connect(username, password, docbase); } catch (ParseException e) { DfLogger.error(Monitor.class, "Exception while parsing ", null, e); printUsage(options, System.out); } return session; } public static void printUsage(final Options options, final OutputStream out) { final PrintWriter writer = new PrintWriter(out); final HelpFormatter usageFormatter = new HelpFormatter(); usageFormatter.printUsage(writer, 80, Monitor.class.getName(), options); writer.close(); } private static Integer getSessionCount(IDfSession dfSession) throws DfException { isConnected(dfSession); final String s = "EXECUTE show_sessions"; IDfQuery query = new DfQuery(); query.setDQL(s); int count = 0; IDfCollection collection = null; try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); while (collection.next()) { String status = collection.getString("session_status"); if (status.equals("Active")) { count++; } } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return count; } private static List getIndexName(IDfSession dfSession) throws DfException { isConnected(dfSession); final String s = ("select fti.index_name,iac.object_name as instance_name from dm_f" + "ulltext_index fti, dm_ftindex_agent_config iac where fti.index_n" + "ame = iac.index_name and fti.is_standby = false and iac.force_i" + "nactive = false"); List result = new ArrayList<String>(); IDfCollection collection = null; IDfQuery query = new DfQuery(); query.setDQL(s); DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); while (collection.next()) { result.add(new IndexAgentInfo(collection.getString("index_name").trim(), collection.getString("instance_name").trim())); DfLogger.debug(Monitor.class, result.toString(), null, null); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return result; } private static Integer getDeadWorkflows(IDfSession dfSession) throws DfException { isConnected(dfSession); final String s = "SELECT count(*) as cnt FROM dm_workflow w WHERE any w.r_act_state in (3,4)"; IDfQuery query = new DfQuery(); query.setDQL(s); int count = 0; IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); if (collection.next()) { count = collection.getInt("cnt"); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return count; } private static Integer getBadWorkitems(IDfSession dfSession) throws DfException { isConnected(dfSession); final String s = "select count(*) as cnt from dmi_workitem w, dm_workflow" + " wf where w.r_workflow_id = wf.r_object_id " + "and a_wq_name not in (select r_object_id from dm_server_config)"; IDfQuery query = new DfQuery(); query.setDQL(s); int count = 0; IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); if (collection.next()) { count = collection.getInt("cnt"); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return count; } private static Integer getFTFailedQueueSize(IDfSession dfSession, String user) throws DfException { isConnected(dfSession); final String s = "select count(*) as cnt from dmi_queue_item where name = ''{0}''" + " and task_state not in (''failed'',''warning'')"; IDfQuery query = new DfQuery(); String dql = MessageFormat.format(s, user); query.setDQL(dql); int count = 0; IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); if (collection.next()) { count = collection.getInt("cnt"); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return count; } private static Integer getQueueSize(IDfSession dfSession) throws DfException { isConnected(dfSession); final String s = "select count(*) as cnt from dmi_queue_item where delete_flag=1 and date_send < date(today)-15"; IDfQuery query = new DfQuery(); query.setDQL(s); int count = 0; IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); if (collection.next()) { count = collection.getInt("cnt"); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return count; } private static Integer getTotalQueueSize(IDfSession dfSession) throws DfException { isConnected(dfSession); final String s = "select count(*) as cnt from dmi_queue_item"; IDfQuery query = new DfQuery(); query.setDQL(s); int count = 0; IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); if (collection.next()) { count = collection.getInt("cnt"); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return count; } private static Boolean checkFTSearch(IDfSession dfSession) throws DfException { isConnected(dfSession); final String s = "select count(r_object_id) as cnt from dm_sysobject" + " SEARCH DOCUMENT CONTAINS 'test' enable(return_top 1)"; IDfQuery query = new DfQuery(); query.setDQL(s); int count = 0; IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); if (collection.next()) { count = collection.getInt("cnt"); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } return count >= 1; } private static Boolean fetchContent(IDfSession dfSession) throws DfException, IOException { isConnected(dfSession); final String s = "select r_object_id from dm_document" + " where folder('/System/Sysadmin/Reports') enable (RETURN_TOP 1)"; IDfQuery query = new DfQuery(); query.setDQL(s); Boolean ret = null; String filename = null; try { if (isWindows()) { filename = "C:\\TEMP\\file.txt"; } else if (isUnix()) { filename = "/tmp/file.txt"; } } catch (Exception e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_QUERY); collection.next(); IDfId id = collection.getId("r_object_id"); IDfSysObject sysObject = (IDfSysObject) dfSession.getObject(id); DfLogger.debug(Monitor.class, id.toString(), null, null); sysObject.getFile(filename); DfLogger.debug(Monitor.class, sysObject.getFile(filename), null, null); } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } try { ret = makeFile(filename); } catch (IOException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } return ret; } private static Boolean makeFile(String filename) throws IOException { File file = new File(filename); file.deleteOnExit(); return file.exists(); } private static IDfSession connect(String username, String password, String docbase) throws DfException { IDfClientX clientx = new DfClientX(); IDfClient client = clientx.getLocalClient(); IDfLoginInfo iLogin = clientx.getLoginInfo(); iLogin.setUser(username); iLogin.setPassword(password); IDfSession dfSession = null; try { dfSession = client.newSession(docbase, iLogin); DfLogger.debug(Monitor.class, dfSession.toString(), null, null); } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, null); } finally { DfLogger.info(Monitor.class, "Success owning session in docbase " + docbase, null, null); } return dfSession; } private static boolean isWindows() { return (OS.contains("win")); } private static boolean isUnix() { return (OS.contains("nix") || OS.contains("nux") || OS.contains("sunos") || OS.contains("aix") || OS.contains("HPUX")); } private static boolean isConnected(IDfSession dfSession) { return dfSession != null; } private static String statusOfIA(IDfSession dfSession) throws DfException { isConnected(dfSession); String ret = null; List list = getIndexName(dfSession); DfLogger.debug(Monitor.class, list.toString(), null, null); IndexAgentInfo agentInfo; for (Object aList : list) { agentInfo = (IndexAgentInfo) aList; String instanceName = agentInfo != null ? agentInfo.get_instance_name() : null; String indexName = agentInfo != null ? agentInfo.get_index_name() : null; String s = "NULL,FTINDEX_AGENT_ADMIN,NAME,S," + indexName + ",AGENT_INSTANCE_NAME,S," + instanceName + ",ACTION,S,status"; IDfQuery query = new DfQuery(); query.setDQL(s); IDfCollection collection = null; DfLogger.debug(Monitor.class, query.getDQL(), null, null); try { collection = query.execute(dfSession, IDfQuery.DF_APPLY); dfSession.getMessage(1); collection.next(); int count = collection.getValueCount("name"); for (int ix = 0; ix < count; ix++) { String indexAgentName = collection.getRepeatingString("name", ix); String status = collection.getRepeatingString("status", ix); if (Integer.parseInt(status) == 200) { ret = indexAgentName.concat(" is in not responsible state"); } else if (Integer.parseInt(status) == 100) { ret = indexAgentName.concat(" is shutdown"); } else if (Integer.parseInt(status) == 0) { ret = indexAgentName.concat(" is running"); } DfLogger.debug(Monitor.class, indexAgentName.concat("\n") + indexName.concat("\n") + instanceName.concat("\n"), null, null); } } catch (DfException e) { DfLogger.error(Monitor.class, e.getMessage(), null, e); } finally { if (collection != null) { collection.close(); } } } return ret; } public static class IndexAgentInfo { private String m_index_name; private String m_instance_name; public IndexAgentInfo(String index_name, String instance_name) { this.m_index_name = index_name; this.m_instance_name = instance_name; } public String get_index_name() { return m_index_name; } public String get_instance_name() { return m_instance_name; } } }
true
true
public static void main(String[] args) throws DfException { Options options = construct(); IDfSession dfSession = initial(args, options); CommandLineParser parser = new BasicParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("S")) { System.out.println(getSessionCount(dfSession).toString()); } if (line.hasOption("i")) { System.out.println(statusOfIA(dfSession)); } if (line.hasOption("W")) { System.out.println(getDeadWorkflows(dfSession).toString()); } if (line.hasOption("b")) { System.out.println(getBadWorkitems(dfSession).toString()); } if (line.hasOption("F")) { if (checkFTSearch(dfSession)) System.out.print(0); } if (line.hasOption("C")) { if (fetchContent(dfSession)) System.out.print(0); } if (line.hasOption("q")) { System.out.println(getFTFailedQueueSize(dfSession, line.getOptionValue("q")).toString()); } if (line.hasOption("Q")) { System.out.println(getQueueSize(dfSession).toString()); } if (line.hasOption("Qt")) { System.out.println(getQueueSize(dfSession).toString()); } } catch (Throwable t) { DfLogger.fatal(dfSession, t.getMessage(), null, t); DfLogger.error(Monitor.class, "Exception while parsing ", null, t); } finally { assert dfSession != null; dfSession.disconnect(); } }
public static void main(String[] args) throws DfException { Options options = construct(); IDfSession dfSession = initial(args, options); CommandLineParser parser = new BasicParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("S")) { System.out.println(getSessionCount(dfSession).toString()); } if (line.hasOption("i")) { System.out.println(statusOfIA(dfSession)); } if (line.hasOption("W")) { System.out.println(getDeadWorkflows(dfSession).toString()); } if (line.hasOption("b")) { System.out.println(getBadWorkitems(dfSession).toString()); } if (line.hasOption("F")) { if (checkFTSearch(dfSession)) System.out.print(0); } if (line.hasOption("C")) { if (fetchContent(dfSession)) System.out.print(0); } if (line.hasOption("q")) { System.out.println(getFTFailedQueueSize(dfSession, line.getOptionValue("q")).toString()); } if (line.hasOption("Q")) { System.out.println(getQueueSize(dfSession).toString()); } if (line.hasOption("Qt")) { System.out.println(getTotalQueueSize(dfSession).toString()); } } catch (Throwable t) { DfLogger.fatal(dfSession, t.getMessage(), null, t); DfLogger.error(Monitor.class, "Exception while parsing ", null, t); } finally { assert dfSession != null; dfSession.disconnect(); } }
diff --git a/eclipse_files/src/agent/test/V0_JUnit_PartsRobotAgent_CameraAgent_Test_NormativeScenario.java b/eclipse_files/src/agent/test/V0_JUnit_PartsRobotAgent_CameraAgent_Test_NormativeScenario.java index 6e418ab8..bd38c035 100644 --- a/eclipse_files/src/agent/test/V0_JUnit_PartsRobotAgent_CameraAgent_Test_NormativeScenario.java +++ b/eclipse_files/src/agent/test/V0_JUnit_PartsRobotAgent_CameraAgent_Test_NormativeScenario.java @@ -1,308 +1,308 @@ package agent.test; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import DeviceGraphics.NestGraphics; import agent.CameraAgent; import agent.NestAgent; import agent.PartsRobotAgent; import agent.CameraAgent.NestStatus; import agent.PartsRobotAgent.MyKitStatus; import agent.data.Kit; import agent.data.Part; import junit.framework.TestCase; /** * This tests the Parts Robot and Camera in the normative scenario. The UUT is * the interaction between the Nest, Camera and Parts Robot. The camera captures * a pair of full nests and sends the partsrobot a list of good parts. Parts * Robot then finishes filling a kit and the camera is asked to inspect the kit. * @author Daniel Paje */ public class V0_JUnit_PartsRobotAgent_CameraAgent_Test_NormativeScenario extends TestCase { protected NestAgent nest; protected NestAgent nest2; protected PartsRobotAgent partsrobot; protected CameraAgent camera; protected Date date; private final URL URL = V0_JUnit_PartsRobotAgent_CameraAgent_Test_NormativeScenario.class .getResource("."); private final String FILEPATH = URL.toString().replace("file:", ""); @Override protected void setUp() { nest = new NestAgent("nest"); nest2 = new NestAgent("nest2"); partsrobot = new PartsRobotAgent("partsrobot"); camera = new CameraAgent("camera"); camera.setNest(nest); camera.setNest(nest2); for (int i = 0; i < 6; i++) { camera.setNest(new NestAgent("nest" + i)); } camera.setPartsRobot(partsrobot); nest.setCamera(camera); nest2.setCamera(camera); nest.setGraphicalRepresentation(new NestGraphics(null,0,null)); nest2.setGraphicalRepresentation(new NestGraphics(null,0,null)); date = new Date(); } @Override protected void tearDown() { nest = null; nest2 = null; partsrobot = null; camera = null; date = null; } public void testNormativeScenario() throws InterruptedException { List<Part> partsList = new ArrayList<Part>(); for (int i = 0; i < 9; i++) { Part p = new Part(); nest.msgHereIsPart(p); partsList.add(p); } List<CameraAgent.MyNest> MyNests = camera.getNests(); CameraAgent.MyNest MyNest = null; CameraAgent.MyNest MyNest2 = null; Kit kit = new Kit(nest.getTypesOfParts()); for (CameraAgent.MyNest mn : MyNests) { if (mn.nest == nest) { MyNest = mn; } else if (mn.nest == nest2) { MyNest2 = mn; } } partsrobot.msgUseThisKit(kit); // Need a reference to the MyKit object that the partsrobot is // building PartsRobotAgent.MyKit MyKit = null; for (PartsRobotAgent.MyKit mk : partsrobot.getMyKits()) { if (mk.kit == kit) { MyKit = mk; break; } } assertEquals("Nest should have 9 parts", 9, nest.currentParts.size()); assertEquals("Camera should have 8 nests", 8, camera.getNests().size()); // Start the test for (int i = 0; i < 4; i++) { /* * The nest's part count will keep decreasing but for this test, we * want to know that the partsrobot is picking up parts successfully * so the camera will receive the nest full message even if the nest * isn't actually full. */ camera.msgIAmFull(nest); // Invoke Camera's scheduler camera.pickAndExecuteAnAction(); // No rules should have passed as only 1 nest is full camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired takePictureOfNest() assertEquals( "Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); // CameraGraphics sends this when the camera has taken a photograph // of // both nests. - camera.msgTakePictureNestDone(nest.guiNest); - camera.msgTakePictureNestDone(nest2.guiNest); + camera.msgTakePictureNestDone(nest.guiNest,true,nest2.guiNest,true); + //camera.msgTakePictureNestDone(nest2.guiNest); assertEquals( "Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired tellPartsRobot() assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); // Camera's scheduler should have again fired tellPartsRobot() assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals( "Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); // Camera now sleeps until the kit is assembled /* * If the scheduler fires now, the code blocks if the previous * animation isn't complete, so simulate completing the pickUpPart * animation and releasing the animation permit. In this test case, * we do this before invoking the scheduler as this test runs in a * single thread (and will get stuck if partsrobot attempts to * acquire a permit) whereas in the factory, the PartsRobotGraphics * will be running in another thread. */ partsrobot.msgPickUpPartDone(); // Now it's safe to invoke the scheduler partsrobot.pickAndExecuteAnAction(); } // The Parts Robot now needs to place parts, once for each arm it has // full. for (int i = 0; i < 4; i++) { /* * Parts robot needs a semaphore permit again, simulating that the * animation for placing the part into the kit is done. */ partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); } // Now we need 4 more parts to place as a kit has 9 parts. for (int i = 0; i < 4; i++) { camera.msgIAmFull(nest); camera.pickAndExecuteAnAction(); camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); assertEquals( "Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); - camera.msgTakePictureNestDone(nest.guiNest); - camera.msgTakePictureNestDone(nest2.guiNest); + camera.msgTakePictureNestDone(nest.guiNest,true,nest2.guiNest,true); + // camera.msgTakePictureNestDone(nest2.guiNest); assertEquals( "Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals( "Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); partsrobot.msgPickUpPartDone(); partsrobot.pickAndExecuteAnAction(); } for (int i = 0; i < 4; i++) { partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); } // One last part to place camera.msgIAmFull(nest); camera.pickAndExecuteAnAction(); camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); - camera.msgTakePictureNestDone(nest.guiNest); - camera.msgTakePictureNestDone(nest2.guiNest); + camera.msgTakePictureNestDone(nest.guiNest,true,nest2.guiNest,true); + //camera.msgTakePictureNestDone(nest2.guiNest); assertEquals("Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals("Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals("Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); partsrobot.msgPickUpPartDone(); partsrobot.pickAndExecuteAnAction(); partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); // Kit is now done assertEquals("Parts Robot's MyKit's status should now be 'Done'", MyKitStatus.Done, MyKit.MKS); /* * Wake up camera to perform the final inspection of the kit before it * leaves this section. Note that this is after the KitRobot has moved * it into the inspection area. */ camera.msgInspectKit(kit); CameraAgent.MyKit CameraKit = null; for (CameraAgent.MyKit mk : camera.getKits()) { if (mk.kit == kit) { CameraKit = mk; break; } } camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired takePictureOfKit() assertEquals( "Camera's MyKit's status should now be 'picture being taken'", CameraAgent.KitStatus.PICTURE_BEING_TAKEN, CameraKit.ks); // In the normative scenario, assume the kit is good - camera.msgTakePictureKitDone(kit, true); + camera.msgTakePictureKitDone(kit.kitGraphics, true); assertEquals("Camera's MyKit's status should now be 'done'", CameraAgent.KitStatus.DONE, CameraKit.ks); assertTrue("Camera's MyKit's should have passed the inspection", CameraKit.kitDone); // At this point the camera will message the kitrobot and the test is // concluded. } public String getFILEPATH() { return FILEPATH; } }
false
true
public void testNormativeScenario() throws InterruptedException { List<Part> partsList = new ArrayList<Part>(); for (int i = 0; i < 9; i++) { Part p = new Part(); nest.msgHereIsPart(p); partsList.add(p); } List<CameraAgent.MyNest> MyNests = camera.getNests(); CameraAgent.MyNest MyNest = null; CameraAgent.MyNest MyNest2 = null; Kit kit = new Kit(nest.getTypesOfParts()); for (CameraAgent.MyNest mn : MyNests) { if (mn.nest == nest) { MyNest = mn; } else if (mn.nest == nest2) { MyNest2 = mn; } } partsrobot.msgUseThisKit(kit); // Need a reference to the MyKit object that the partsrobot is // building PartsRobotAgent.MyKit MyKit = null; for (PartsRobotAgent.MyKit mk : partsrobot.getMyKits()) { if (mk.kit == kit) { MyKit = mk; break; } } assertEquals("Nest should have 9 parts", 9, nest.currentParts.size()); assertEquals("Camera should have 8 nests", 8, camera.getNests().size()); // Start the test for (int i = 0; i < 4; i++) { /* * The nest's part count will keep decreasing but for this test, we * want to know that the partsrobot is picking up parts successfully * so the camera will receive the nest full message even if the nest * isn't actually full. */ camera.msgIAmFull(nest); // Invoke Camera's scheduler camera.pickAndExecuteAnAction(); // No rules should have passed as only 1 nest is full camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired takePictureOfNest() assertEquals( "Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); // CameraGraphics sends this when the camera has taken a photograph // of // both nests. camera.msgTakePictureNestDone(nest.guiNest); camera.msgTakePictureNestDone(nest2.guiNest); assertEquals( "Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired tellPartsRobot() assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); // Camera's scheduler should have again fired tellPartsRobot() assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals( "Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); // Camera now sleeps until the kit is assembled /* * If the scheduler fires now, the code blocks if the previous * animation isn't complete, so simulate completing the pickUpPart * animation and releasing the animation permit. In this test case, * we do this before invoking the scheduler as this test runs in a * single thread (and will get stuck if partsrobot attempts to * acquire a permit) whereas in the factory, the PartsRobotGraphics * will be running in another thread. */ partsrobot.msgPickUpPartDone(); // Now it's safe to invoke the scheduler partsrobot.pickAndExecuteAnAction(); } // The Parts Robot now needs to place parts, once for each arm it has // full. for (int i = 0; i < 4; i++) { /* * Parts robot needs a semaphore permit again, simulating that the * animation for placing the part into the kit is done. */ partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); } // Now we need 4 more parts to place as a kit has 9 parts. for (int i = 0; i < 4; i++) { camera.msgIAmFull(nest); camera.pickAndExecuteAnAction(); camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); assertEquals( "Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); camera.msgTakePictureNestDone(nest.guiNest); camera.msgTakePictureNestDone(nest2.guiNest); assertEquals( "Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals( "Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); partsrobot.msgPickUpPartDone(); partsrobot.pickAndExecuteAnAction(); } for (int i = 0; i < 4; i++) { partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); } // One last part to place camera.msgIAmFull(nest); camera.pickAndExecuteAnAction(); camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); camera.msgTakePictureNestDone(nest.guiNest); camera.msgTakePictureNestDone(nest2.guiNest); assertEquals("Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals("Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals("Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); partsrobot.msgPickUpPartDone(); partsrobot.pickAndExecuteAnAction(); partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); // Kit is now done assertEquals("Parts Robot's MyKit's status should now be 'Done'", MyKitStatus.Done, MyKit.MKS); /* * Wake up camera to perform the final inspection of the kit before it * leaves this section. Note that this is after the KitRobot has moved * it into the inspection area. */ camera.msgInspectKit(kit); CameraAgent.MyKit CameraKit = null; for (CameraAgent.MyKit mk : camera.getKits()) { if (mk.kit == kit) { CameraKit = mk; break; } } camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired takePictureOfKit() assertEquals( "Camera's MyKit's status should now be 'picture being taken'", CameraAgent.KitStatus.PICTURE_BEING_TAKEN, CameraKit.ks); // In the normative scenario, assume the kit is good camera.msgTakePictureKitDone(kit, true); assertEquals("Camera's MyKit's status should now be 'done'", CameraAgent.KitStatus.DONE, CameraKit.ks); assertTrue("Camera's MyKit's should have passed the inspection", CameraKit.kitDone); // At this point the camera will message the kitrobot and the test is // concluded. }
public void testNormativeScenario() throws InterruptedException { List<Part> partsList = new ArrayList<Part>(); for (int i = 0; i < 9; i++) { Part p = new Part(); nest.msgHereIsPart(p); partsList.add(p); } List<CameraAgent.MyNest> MyNests = camera.getNests(); CameraAgent.MyNest MyNest = null; CameraAgent.MyNest MyNest2 = null; Kit kit = new Kit(nest.getTypesOfParts()); for (CameraAgent.MyNest mn : MyNests) { if (mn.nest == nest) { MyNest = mn; } else if (mn.nest == nest2) { MyNest2 = mn; } } partsrobot.msgUseThisKit(kit); // Need a reference to the MyKit object that the partsrobot is // building PartsRobotAgent.MyKit MyKit = null; for (PartsRobotAgent.MyKit mk : partsrobot.getMyKits()) { if (mk.kit == kit) { MyKit = mk; break; } } assertEquals("Nest should have 9 parts", 9, nest.currentParts.size()); assertEquals("Camera should have 8 nests", 8, camera.getNests().size()); // Start the test for (int i = 0; i < 4; i++) { /* * The nest's part count will keep decreasing but for this test, we * want to know that the partsrobot is picking up parts successfully * so the camera will receive the nest full message even if the nest * isn't actually full. */ camera.msgIAmFull(nest); // Invoke Camera's scheduler camera.pickAndExecuteAnAction(); // No rules should have passed as only 1 nest is full camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired takePictureOfNest() assertEquals( "Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); // CameraGraphics sends this when the camera has taken a photograph // of // both nests. camera.msgTakePictureNestDone(nest.guiNest,true,nest2.guiNest,true); //camera.msgTakePictureNestDone(nest2.guiNest); assertEquals( "Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired tellPartsRobot() assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); // Camera's scheduler should have again fired tellPartsRobot() assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals( "Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); // Camera now sleeps until the kit is assembled /* * If the scheduler fires now, the code blocks if the previous * animation isn't complete, so simulate completing the pickUpPart * animation and releasing the animation permit. In this test case, * we do this before invoking the scheduler as this test runs in a * single thread (and will get stuck if partsrobot attempts to * acquire a permit) whereas in the factory, the PartsRobotGraphics * will be running in another thread. */ partsrobot.msgPickUpPartDone(); // Now it's safe to invoke the scheduler partsrobot.pickAndExecuteAnAction(); } // The Parts Robot now needs to place parts, once for each arm it has // full. for (int i = 0; i < 4; i++) { /* * Parts robot needs a semaphore permit again, simulating that the * animation for placing the part into the kit is done. */ partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); } // Now we need 4 more parts to place as a kit has 9 parts. for (int i = 0; i < 4; i++) { camera.msgIAmFull(nest); camera.pickAndExecuteAnAction(); camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); assertEquals( "Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); camera.msgTakePictureNestDone(nest.guiNest,true,nest2.guiNest,true); // camera.msgTakePictureNestDone(nest2.guiNest); assertEquals( "Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals( "Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); partsrobot.msgPickUpPartDone(); partsrobot.pickAndExecuteAnAction(); } for (int i = 0; i < 4; i++) { partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); } // One last part to place camera.msgIAmFull(nest); camera.pickAndExecuteAnAction(); camera.msgIAmFull(nest2); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest.state); assertEquals( "Camera should have set nest2's status to 'photographing'", NestStatus.PHOTOGRAPHING, MyNest2.state); camera.msgTakePictureNestDone(nest.guiNest,true,nest2.guiNest,true); //camera.msgTakePictureNestDone(nest2.guiNest); assertEquals("Camera should have set nest's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest.state); assertEquals("Camera should have set nest2's status to 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Camera should have set nest's status to 'not ready'", NestStatus.NOT_READY, MyNest.state); assertEquals("Nest2's status should still be 'photographed'", NestStatus.PHOTOGRAPHED, MyNest2.state); camera.pickAndExecuteAnAction(); assertEquals("Nest2's status should still be 'not ready'", NestStatus.NOT_READY, MyNest2.state); assertEquals("Camera should have set nest2's status to 'not ready'", NestStatus.NOT_READY, MyNest2.state); partsrobot.msgPickUpPartDone(); partsrobot.pickAndExecuteAnAction(); partsrobot.msgGivePartToKitDone(); partsrobot.pickAndExecuteAnAction(); // Kit is now done assertEquals("Parts Robot's MyKit's status should now be 'Done'", MyKitStatus.Done, MyKit.MKS); /* * Wake up camera to perform the final inspection of the kit before it * leaves this section. Note that this is after the KitRobot has moved * it into the inspection area. */ camera.msgInspectKit(kit); CameraAgent.MyKit CameraKit = null; for (CameraAgent.MyKit mk : camera.getKits()) { if (mk.kit == kit) { CameraKit = mk; break; } } camera.pickAndExecuteAnAction(); // Camera's scheduler should have fired takePictureOfKit() assertEquals( "Camera's MyKit's status should now be 'picture being taken'", CameraAgent.KitStatus.PICTURE_BEING_TAKEN, CameraKit.ks); // In the normative scenario, assume the kit is good camera.msgTakePictureKitDone(kit.kitGraphics, true); assertEquals("Camera's MyKit's status should now be 'done'", CameraAgent.KitStatus.DONE, CameraKit.ks); assertTrue("Camera's MyKit's should have passed the inspection", CameraKit.kitDone); // At this point the camera will message the kitrobot and the test is // concluded. }
diff --git a/src/main/java/org/apache/commons/net/telnet/TelnetInputStream.java b/src/main/java/org/apache/commons/net/telnet/TelnetInputStream.java index 722c3045..9d8a3b2c 100644 --- a/src/main/java/org/apache/commons/net/telnet/TelnetInputStream.java +++ b/src/main/java/org/apache/commons/net/telnet/TelnetInputStream.java @@ -1,629 +1,629 @@ /* * 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.commons.net.telnet; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; /*** * * <p> * * <p> * <p> * @author Daniel F. Savarese * @author Bruno D'Avanzo ***/ final class TelnetInputStream extends BufferedInputStream implements Runnable { static final int _STATE_DATA = 0, _STATE_IAC = 1, _STATE_WILL = 2, _STATE_WONT = 3, _STATE_DO = 4, _STATE_DONT = 5, _STATE_SB = 6, _STATE_SE = 7, _STATE_CR = 8, _STATE_IAC_SB = 9; private boolean __hasReachedEOF, __isClosed; private boolean __readIsWaiting; private int __receiveState, __queueHead, __queueTail, __bytesAvailable; private final int[] __queue; private final TelnetClient __client; private final Thread __thread; private IOException __ioException; /* TERMINAL-TYPE option (start)*/ private final int __suboption[] = new int[256]; private int __suboption_count = 0; /* TERMINAL-TYPE option (end)*/ private boolean __threaded; TelnetInputStream(InputStream input, TelnetClient client, boolean readerThread) { super(input); __client = client; __receiveState = _STATE_DATA; __isClosed = true; __hasReachedEOF = false; // Make it 2049, because when full, one slot will go unused, and we // want a 2048 byte buffer just to have a round number (base 2 that is) __queue = new int[2049]; __queueHead = 0; __queueTail = 0; __bytesAvailable = 0; __ioException = null; __readIsWaiting = false; __threaded = false; if(readerThread) __thread = new Thread(this); else __thread = null; } TelnetInputStream(InputStream input, TelnetClient client) { this(input, client, true); } void _start() { if(__thread == null) return; int priority; __isClosed = false; // TODO remove this // Need to set a higher priority in case JVM does not use pre-emptive // threads. This should prevent scheduler induced deadlock (rather than // deadlock caused by a bug in this code). priority = Thread.currentThread().getPriority() + 1; if (priority > Thread.MAX_PRIORITY) priority = Thread.MAX_PRIORITY; __thread.setPriority(priority); __thread.setDaemon(true); __thread.start(); __threaded = true; } // synchronized(__client) critical sections are to protect against // TelnetOutputStream writing through the telnet client at same time // as a processDo/Will/etc. command invoked from TelnetInputStream // tries to write. private int __read(boolean mayBlock) throws IOException { int ch; while (true) { // If there is no more data AND we were told not to block, just return -2. (More efficient than exception.) if(!mayBlock && super.available() == 0) return -2; // Otherwise, exit only when we reach end of stream. if ((ch = super.read()) < 0) return -1; ch = (ch & 0xff); /* Code Section added for supporting AYT (start)*/ synchronized (__client) { __client._processAYTResponse(); } /* Code Section added for supporting AYT (end)*/ /* Code Section added for supporting spystreams (start)*/ __client._spyRead(ch); /* Code Section added for supporting spystreams (end)*/ switch (__receiveState) { case _STATE_CR: if (ch == '\0') { // Strip null continue; } // How do we handle newline after cr? // else if (ch == '\n' && _requestedDont(TelnetOption.ECHO) && // Handle as normal data by falling through to _STATE_DATA case //$FALL-THROUGH$ case _STATE_DATA: if (ch == TelnetCommand.IAC) { __receiveState = _STATE_IAC; continue; } if (ch == '\r') { synchronized (__client) { if (__client._requestedDont(TelnetOption.BINARY)) __receiveState = _STATE_CR; else __receiveState = _STATE_DATA; } } else __receiveState = _STATE_DATA; break; case _STATE_IAC: switch (ch) { case TelnetCommand.WILL: __receiveState = _STATE_WILL; continue; case TelnetCommand.WONT: __receiveState = _STATE_WONT; continue; case TelnetCommand.DO: __receiveState = _STATE_DO; continue; case TelnetCommand.DONT: __receiveState = _STATE_DONT; continue; /* TERMINAL-TYPE option (start)*/ case TelnetCommand.SB: __suboption_count = 0; __receiveState = _STATE_SB; continue; /* TERMINAL-TYPE option (end)*/ case TelnetCommand.IAC: __receiveState = _STATE_DATA; - break; + break; // exit to enclosing switch to return IAC from read default: - break; + __receiveState = _STATE_DATA; + continue; // move on the next char, i.e. ignore IAC+unknown } - __receiveState = _STATE_DATA; - continue; + break; // exit and return from read case _STATE_WILL: synchronized (__client) { __client._processWill(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_WONT: synchronized (__client) { __client._processWont(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_DO: synchronized (__client) { __client._processDo(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_DONT: synchronized (__client) { __client._processDont(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; /* TERMINAL-TYPE option (start)*/ case _STATE_SB: switch (ch) { case TelnetCommand.IAC: __receiveState = _STATE_IAC_SB; continue; default: // store suboption char __suboption[__suboption_count++] = ch; break; } __receiveState = _STATE_SB; continue; case _STATE_IAC_SB: switch (ch) { case TelnetCommand.SE: synchronized (__client) { __client._processSuboption(__suboption, __suboption_count); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; default: __receiveState = _STATE_SB; break; } __receiveState = _STATE_DATA; continue; /* TERMINAL-TYPE option (end)*/ } break; } return ch; } // synchronized(__client) critical sections are to protect against // TelnetOutputStream writing through the telnet client at same time // as a processDo/Will/etc. command invoked from TelnetInputStream // tries to write. private void __processChar(int ch) throws InterruptedException { // Critical section because we're altering __bytesAvailable, // __queueTail, and the contents of _queue. synchronized (__queue) { while (__bytesAvailable >= __queue.length - 1) { // The queue is full. We need to wait before adding any more data to it. Hopefully the stream owner // will consume some data soon! if(__threaded) { __queue.notify(); try { __queue.wait(); } catch (InterruptedException e) { throw e; } } else { // We've been asked to add another character to the queue, but it is already full and there's // no other thread to drain it. This should not have happened! throw new IllegalStateException("Queue is full! Cannot process another character."); } } // Need to do this in case we're not full, but block on a read if (__readIsWaiting && __threaded) { __queue.notify(); } __queue[__queueTail] = ch; ++__bytesAvailable; if (++__queueTail >= __queue.length) __queueTail = 0; } } @Override public int read() throws IOException { // Critical section because we're altering __bytesAvailable, // __queueHead, and the contents of _queue in addition to // testing value of __hasReachedEOF. synchronized (__queue) { while (true) { if (__ioException != null) { IOException e; e = __ioException; __ioException = null; throw e; } if (__bytesAvailable == 0) { // Return -1 if at end of file if (__hasReachedEOF) return -1; // Otherwise, we have to wait for queue to get something if(__threaded) { __queue.notify(); try { __readIsWaiting = true; __queue.wait(); __readIsWaiting = false; } catch (InterruptedException e) { throw new InterruptedIOException("Fatal thread interruption during read."); } } else { //__alreadyread = false; __readIsWaiting = true; int ch; boolean mayBlock = true; // block on the first read only do { try { if ((ch = __read(mayBlock)) < 0) if(ch != -2) return (ch); } catch (InterruptedIOException e) { synchronized (__queue) { __ioException = e; __queue.notifyAll(); try { __queue.wait(100); } catch (InterruptedException interrupted) { } } return (-1); } try { if(ch != -2) { __processChar(ch); } } catch (InterruptedException e) { if (__isClosed) return (-1); } // Reads should not block on subsequent iterations. Potentially, this could happen if the // remaining buffered socket data consists entirely of Telnet command sequence and no "user" data. mayBlock = false; } // Continue reading as long as there is data available and the queue is not full. while (super.available() > 0 && __bytesAvailable < __queue.length - 1); __readIsWaiting = false; } continue; } else { int ch; ch = __queue[__queueHead]; if (++__queueHead >= __queue.length) __queueHead = 0; --__bytesAvailable; // Need to explicitly notify() so available() works properly if(__bytesAvailable == 0 && __threaded) { __queue.notify(); } return ch; } } } } /*** * Reads the next number of bytes from the stream into an array and * returns the number of bytes read. Returns -1 if the end of the * stream has been reached. * <p> * @param buffer The byte array in which to store the data. * @return The number of bytes read. Returns -1 if the * end of the message has been reached. * @exception IOException If an error occurs in reading the underlying * stream. ***/ @Override public int read(byte buffer[]) throws IOException { return read(buffer, 0, buffer.length); } /*** * Reads the next number of bytes from the stream into an array and returns * the number of bytes read. Returns -1 if the end of the * message has been reached. The characters are stored in the array * starting from the given offset and up to the length specified. * <p> * @param buffer The byte array in which to store the data. * @param offset The offset into the array at which to start storing data. * @param length The number of bytes to read. * @return The number of bytes read. Returns -1 if the * end of the stream has been reached. * @exception IOException If an error occurs while reading the underlying * stream. ***/ @Override public int read(byte buffer[], int offset, int length) throws IOException { int ch, off; if (length < 1) return 0; // Critical section because run() may change __bytesAvailable synchronized (__queue) { if (length > __bytesAvailable) length = __bytesAvailable; } if ((ch = read()) == -1) return -1; off = offset; do { buffer[offset++] = (byte)ch; } while (--length > 0 && (ch = read()) != -1); //__client._spyRead(buffer, off, offset - off); return (offset - off); } /*** Returns false. Mark is not supported. ***/ @Override public boolean markSupported() { return false; } @Override public int available() throws IOException { // Critical section because run() may change __bytesAvailable synchronized (__queue) { return __bytesAvailable; } } // Cannot be synchronized. Will cause deadlock if run() is blocked // in read because BufferedInputStream read() is synchronized. @Override public void close() throws IOException { // Completely disregard the fact thread may still be running. // We can't afford to block on this close by waiting for // thread to terminate because few if any JVM's will actually // interrupt a system read() from the interrupt() method. super.close(); synchronized (__queue) { __hasReachedEOF = true; __isClosed = true; if (__thread != null && __thread.isAlive()) { __thread.interrupt(); } __queue.notifyAll(); } __threaded = false; } public void run() { int ch; try { _outerLoop: while (!__isClosed) { try { if ((ch = __read(true)) < 0) break; } catch (InterruptedIOException e) { synchronized (__queue) { __ioException = e; __queue.notifyAll(); try { __queue.wait(100); } catch (InterruptedException interrupted) { if (__isClosed) break _outerLoop; } continue; } } catch(RuntimeException re) { // We treat any runtime exceptions as though the // stream has been closed. We close the // underlying stream just to be sure. super.close(); // Breaking the loop has the effect of setting // the state to closed at the end of the method. break _outerLoop; } try { __processChar(ch); } catch (InterruptedException e) { if (__isClosed) break _outerLoop; } } } catch (IOException ioe) { synchronized (__queue) { __ioException = ioe; } } synchronized (__queue) { __isClosed = true; // Possibly redundant __hasReachedEOF = true; __queue.notify(); } __threaded = false; } } /* Emacs configuration * Local variables: ** * mode: java ** * c-basic-offset: 4 ** * indent-tabs-mode: nil ** * End: ** */
false
true
private int __read(boolean mayBlock) throws IOException { int ch; while (true) { // If there is no more data AND we were told not to block, just return -2. (More efficient than exception.) if(!mayBlock && super.available() == 0) return -2; // Otherwise, exit only when we reach end of stream. if ((ch = super.read()) < 0) return -1; ch = (ch & 0xff); /* Code Section added for supporting AYT (start)*/ synchronized (__client) { __client._processAYTResponse(); } /* Code Section added for supporting AYT (end)*/ /* Code Section added for supporting spystreams (start)*/ __client._spyRead(ch); /* Code Section added for supporting spystreams (end)*/ switch (__receiveState) { case _STATE_CR: if (ch == '\0') { // Strip null continue; } // How do we handle newline after cr? // else if (ch == '\n' && _requestedDont(TelnetOption.ECHO) && // Handle as normal data by falling through to _STATE_DATA case //$FALL-THROUGH$ case _STATE_DATA: if (ch == TelnetCommand.IAC) { __receiveState = _STATE_IAC; continue; } if (ch == '\r') { synchronized (__client) { if (__client._requestedDont(TelnetOption.BINARY)) __receiveState = _STATE_CR; else __receiveState = _STATE_DATA; } } else __receiveState = _STATE_DATA; break; case _STATE_IAC: switch (ch) { case TelnetCommand.WILL: __receiveState = _STATE_WILL; continue; case TelnetCommand.WONT: __receiveState = _STATE_WONT; continue; case TelnetCommand.DO: __receiveState = _STATE_DO; continue; case TelnetCommand.DONT: __receiveState = _STATE_DONT; continue; /* TERMINAL-TYPE option (start)*/ case TelnetCommand.SB: __suboption_count = 0; __receiveState = _STATE_SB; continue; /* TERMINAL-TYPE option (end)*/ case TelnetCommand.IAC: __receiveState = _STATE_DATA; break; default: break; } __receiveState = _STATE_DATA; continue; case _STATE_WILL: synchronized (__client) { __client._processWill(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_WONT: synchronized (__client) { __client._processWont(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_DO: synchronized (__client) { __client._processDo(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_DONT: synchronized (__client) { __client._processDont(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; /* TERMINAL-TYPE option (start)*/ case _STATE_SB: switch (ch) { case TelnetCommand.IAC: __receiveState = _STATE_IAC_SB; continue; default: // store suboption char __suboption[__suboption_count++] = ch; break; } __receiveState = _STATE_SB; continue; case _STATE_IAC_SB: switch (ch) { case TelnetCommand.SE: synchronized (__client) { __client._processSuboption(__suboption, __suboption_count); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; default: __receiveState = _STATE_SB; break; } __receiveState = _STATE_DATA; continue; /* TERMINAL-TYPE option (end)*/ } break; } return ch; }
private int __read(boolean mayBlock) throws IOException { int ch; while (true) { // If there is no more data AND we were told not to block, just return -2. (More efficient than exception.) if(!mayBlock && super.available() == 0) return -2; // Otherwise, exit only when we reach end of stream. if ((ch = super.read()) < 0) return -1; ch = (ch & 0xff); /* Code Section added for supporting AYT (start)*/ synchronized (__client) { __client._processAYTResponse(); } /* Code Section added for supporting AYT (end)*/ /* Code Section added for supporting spystreams (start)*/ __client._spyRead(ch); /* Code Section added for supporting spystreams (end)*/ switch (__receiveState) { case _STATE_CR: if (ch == '\0') { // Strip null continue; } // How do we handle newline after cr? // else if (ch == '\n' && _requestedDont(TelnetOption.ECHO) && // Handle as normal data by falling through to _STATE_DATA case //$FALL-THROUGH$ case _STATE_DATA: if (ch == TelnetCommand.IAC) { __receiveState = _STATE_IAC; continue; } if (ch == '\r') { synchronized (__client) { if (__client._requestedDont(TelnetOption.BINARY)) __receiveState = _STATE_CR; else __receiveState = _STATE_DATA; } } else __receiveState = _STATE_DATA; break; case _STATE_IAC: switch (ch) { case TelnetCommand.WILL: __receiveState = _STATE_WILL; continue; case TelnetCommand.WONT: __receiveState = _STATE_WONT; continue; case TelnetCommand.DO: __receiveState = _STATE_DO; continue; case TelnetCommand.DONT: __receiveState = _STATE_DONT; continue; /* TERMINAL-TYPE option (start)*/ case TelnetCommand.SB: __suboption_count = 0; __receiveState = _STATE_SB; continue; /* TERMINAL-TYPE option (end)*/ case TelnetCommand.IAC: __receiveState = _STATE_DATA; break; // exit to enclosing switch to return IAC from read default: __receiveState = _STATE_DATA; continue; // move on the next char, i.e. ignore IAC+unknown } break; // exit and return from read case _STATE_WILL: synchronized (__client) { __client._processWill(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_WONT: synchronized (__client) { __client._processWont(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_DO: synchronized (__client) { __client._processDo(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; case _STATE_DONT: synchronized (__client) { __client._processDont(ch); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; /* TERMINAL-TYPE option (start)*/ case _STATE_SB: switch (ch) { case TelnetCommand.IAC: __receiveState = _STATE_IAC_SB; continue; default: // store suboption char __suboption[__suboption_count++] = ch; break; } __receiveState = _STATE_SB; continue; case _STATE_IAC_SB: switch (ch) { case TelnetCommand.SE: synchronized (__client) { __client._processSuboption(__suboption, __suboption_count); __client._flushOutputStream(); } __receiveState = _STATE_DATA; continue; default: __receiveState = _STATE_SB; break; } __receiveState = _STATE_DATA; continue; /* TERMINAL-TYPE option (end)*/ } break; } return ch; }
diff --git a/library-ui/src/com/eyeem/poll/AnimatedPollAdapter.java b/library-ui/src/com/eyeem/poll/AnimatedPollAdapter.java index c62207f..a8f6e8c 100644 --- a/library-ui/src/com/eyeem/poll/AnimatedPollAdapter.java +++ b/library-ui/src/com/eyeem/poll/AnimatedPollAdapter.java @@ -1,99 +1,104 @@ package com.eyeem.poll; import android.widget.BaseAdapter; import android.widget.ListView; import com.eyeem.storage.Storage; import com.handmark.pulltorefresh.library.PullToRefreshListView; import java.util.HashSet; public abstract class AnimatedPollAdapter extends BaseAdapter implements PollListView.PollAdapter { public HashSet<String> seenIds = new HashSet<String>(); protected String firstId; protected int offsetPy; @Override public void notifyDataWillChange(ListView listView) { boolean pullToRefreshList = false; try { pullToRefreshList = listView.getParent().getParent() instanceof PullToRefreshListView; } catch (Throwable t) {} int i = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); if (i >= 0 || (pullToRefreshList && i+1 >= 0)) { // pull to refresh library adds a framelayout header by default so // we need to compensate for that firstId = idForPosition(i < 0 ? 0 : i); offsetPy = listView.getChildAt(0) == null ? 0 : listView.getChildAt(0).getTop(); } else { firstId = null; offsetPy = 0; } } @Override public void notifyDataWithAction(Storage.Subscription.Action action, final ListView listView) { if (Storage.Subscription.ADD_UPFRONT.equals(action.name)) { boolean paused = isScrollingPaused(listView); notifyDataSetChanged(); int index = positionForId(firstId); firstId = null; final int px = offsetPy; if (!paused && index > 0) { listView.setSelectionFromTop(index + listView.getHeaderViewsCount(), px); if (index == 1) { listView.postDelayed(new Runnable() { int counter = 0; @Override public void run() { int offset = listView.getFirstVisiblePosition(); if (offset == 0 || counter == 1) { listView.setSelection(0); return; } int distance = 0; int duration = 1000 * (offset + 1); if (listView.getChildCount() > 0) distance = listView.getChildAt(0).getHeight() * offset; // approx listView.smoothScrollBy(-distance, duration); listView.postDelayed(this, duration); counter++; } }, 500); } else { // TODO new items indicator listView.setSelection(0); } } else { - listView.setSelectionFromTop(index + listView.getHeaderViewsCount(), px); + if (!isScrollingPaused(listView)) { + // otherwise pull to refresh library starts to behave erratic + listView.setSelectionFromTop(index, px); // should prolly be 0, 0 args but I'm too afraid of implications + } else { + listView.setSelectionFromTop(index + listView.getHeaderViewsCount(), px); + } } } else { notifyDataSetChanged(); if (firstId != null) { listView.setSelectionFromTop(positionForId(firstId) + listView.getHeaderViewsCount(), offsetPy); firstId = null; } } } public boolean isScrollingPaused(ListView lv) { return lv.getFirstVisiblePosition() != 0; } @Override public long getItemId(int position) { return position; } @Override public HashSet<String> seenIds() { return seenIds; } @Override public void clearViewCache() {} }
true
true
public void notifyDataWithAction(Storage.Subscription.Action action, final ListView listView) { if (Storage.Subscription.ADD_UPFRONT.equals(action.name)) { boolean paused = isScrollingPaused(listView); notifyDataSetChanged(); int index = positionForId(firstId); firstId = null; final int px = offsetPy; if (!paused && index > 0) { listView.setSelectionFromTop(index + listView.getHeaderViewsCount(), px); if (index == 1) { listView.postDelayed(new Runnable() { int counter = 0; @Override public void run() { int offset = listView.getFirstVisiblePosition(); if (offset == 0 || counter == 1) { listView.setSelection(0); return; } int distance = 0; int duration = 1000 * (offset + 1); if (listView.getChildCount() > 0) distance = listView.getChildAt(0).getHeight() * offset; // approx listView.smoothScrollBy(-distance, duration); listView.postDelayed(this, duration); counter++; } }, 500); } else { // TODO new items indicator listView.setSelection(0); } } else { listView.setSelectionFromTop(index + listView.getHeaderViewsCount(), px); } } else { notifyDataSetChanged(); if (firstId != null) { listView.setSelectionFromTop(positionForId(firstId) + listView.getHeaderViewsCount(), offsetPy); firstId = null; } } }
public void notifyDataWithAction(Storage.Subscription.Action action, final ListView listView) { if (Storage.Subscription.ADD_UPFRONT.equals(action.name)) { boolean paused = isScrollingPaused(listView); notifyDataSetChanged(); int index = positionForId(firstId); firstId = null; final int px = offsetPy; if (!paused && index > 0) { listView.setSelectionFromTop(index + listView.getHeaderViewsCount(), px); if (index == 1) { listView.postDelayed(new Runnable() { int counter = 0; @Override public void run() { int offset = listView.getFirstVisiblePosition(); if (offset == 0 || counter == 1) { listView.setSelection(0); return; } int distance = 0; int duration = 1000 * (offset + 1); if (listView.getChildCount() > 0) distance = listView.getChildAt(0).getHeight() * offset; // approx listView.smoothScrollBy(-distance, duration); listView.postDelayed(this, duration); counter++; } }, 500); } else { // TODO new items indicator listView.setSelection(0); } } else { if (!isScrollingPaused(listView)) { // otherwise pull to refresh library starts to behave erratic listView.setSelectionFromTop(index, px); // should prolly be 0, 0 args but I'm too afraid of implications } else { listView.setSelectionFromTop(index + listView.getHeaderViewsCount(), px); } } } else { notifyDataSetChanged(); if (firstId != null) { listView.setSelectionFromTop(positionForId(firstId) + listView.getHeaderViewsCount(), offsetPy); firstId = null; } } }
diff --git a/FatTnt/src/me/asofold/bukkit/fattnt/propagation/ArrayPropagation.java b/FatTnt/src/me/asofold/bukkit/fattnt/propagation/ArrayPropagation.java index f0cfb74..0be7100 100644 --- a/FatTnt/src/me/asofold/bukkit/fattnt/propagation/ArrayPropagation.java +++ b/FatTnt/src/me/asofold/bukkit/fattnt/propagation/ArrayPropagation.java @@ -1,453 +1,454 @@ package me.asofold.bukkit.fattnt.propagation; import java.util.LinkedList; import java.util.List; import java.util.Random; import me.asofold.bukkit.fattnt.FatTnt; import me.asofold.bukkit.fattnt.config.Defaults; import me.asofold.bukkit.fattnt.config.ExplosionSettings; import me.asofold.bukkit.fattnt.config.Settings; import me.asofold.bukkit.fattnt.effects.ExplosionManager; import me.asofold.bukkit.fattnt.utils.Utils; import org.bukkit.World; import org.bukkit.block.Block; public class ArrayPropagation extends Propagation { private int[] sequence; private float[] strength; private int[] ids; private int seqMax = 0; private int center = -1; private int fY = 0; private int fZ = 0; private int izMax = 0; private int iCenter = -1; /** * Stats: number of visited blocks (some count double) */ private int n = 0; /** * Explosion center block coords. */ private int cx = 0; private int cy = 0; private int cz = 0; private static final int[] ortDir = new int[]{2,4,6,8,10,12}; long tsLastIdle = System.currentTimeMillis(); private final float[] rand = new float[1024]; /** * Blocks destroyed by the xplosion. */ private List<Block> blocks = null; /** * opposite direction:<br> * 0: no direction<br> * 1: reserved: diagonal<br> * 2: x+<br> * 3: reserved: diagonal<br> * 4: x-<br> * 5: reserved: diagonal<br> * 6: y+<br> * 7: reserved: diagonal<br> * 8: y-<br> * 9: reserved: diagonal<br> * 10: z+<br> * 11: reserved: diagonal<br> * 12: z-<br> */ private static final int[] oDir = new int[]{ 0, // 0: no direction maps to no direction 0, // UNUSED 4, // x+ -> x- 0, // UNUSED 2, // x- -> x+ 0, // UNUSED 8, // y+ -> y- 0, // UNUSED 6, // y- -> y+ 0, // UNUSED 12, // z+ -> z- 0, // UNUSED 10, // z- -> z+ } ; /** * x increment by direction. */ private static final int[] xInc = new int[]{ 0, // 0: no direction maps to no direction 0, // UNUSED 1, // x+ 0, // UNUSED -1, // x- 0, // UNUSED 0, // y+ 0, // UNUSED 0, // y- 0, // UNUSED 0, // z+ 0, // UNUSED 0, // z- }; /** * y increment by direction. */ private static final int[] yInc = new int[]{ 0, // 0: no direction maps to no direction 0, // UNUSED 0, // x+ 0, // UNUSED 0, // x- 0, // UNUSED 1, // y+ 0, // UNUSED -1, // y- 0, // UNUSED 0, // z+ 0, // UNUSED 0, // z- }; /** * z increment by direction. */ private static final int[] zInc = new int[]{ 0, // 0: no direction maps to no direction 0, // UNUSED 0, // x+ 0, // UNUSED 0, // x- 0, // UNUSED 0, // y+ 0, // UNUSED 0, // y- 0, // UNUSED 1, // z+ 0, // UNUSED -1, // z- }; /** * Array increments by direction. */ private final int[] aInc = new int[13]; /** * Runtime ints. */ int[][] rInts = null; /** * Runtime floats. */ float[] rFloats = null; /** * Maximum path lenght/recursion depth. */ int maxDepth = 0; public ArrayPropagation(Settings settings) { super(settings); createArrays(); } private void createArrays() { int d = 1 + (int) (maxRadius*2.0); center = 1 + (int) maxRadius; fY = d; fZ = d*d; int sz = d*d*d; izMax = sz - fZ; iCenter = center+ center*fY + center*fZ; // TODO: check if such is right sequence = new int[sz]; strength = new float[sz]; ids = new int[sz]; for ( int i = 0; i<sz; i++){ sequence[i] = 0; } for (int i=0; i<aInc.length; i++){ aInc[i] = xInc[i] + yInc[i]*fY + zInc[i]*fZ; } maxDepth = (1+ (int)maxRadius) * 2; // six times (for 6 directions): rFloats = new float[6*maxDepth]; rInts = new int[6*maxDepth][6]; for (int i = 0; i<6*maxDepth; i++){ rInts[i] = new int[6]; } initRandomArrays(); } private void initRandomArrays() { // random arrays: Random temp = ExplosionManager.random; for (int i = 0; i <rand.length; i++){ rand[i] = temp.nextFloat()-0.5f; } } @Override public final float getStrength(final double x, final double y, final double z) { final int index = getValidIndex(Utils.floor(x), Utils.floor(y), Utils.floor(z)); if (index == -1) return 0.0f; return strength[index]; // effective radius / strength } /** * 1-dim matrix index , still check if out of range: if ( index<0 || index>= strength.length) * @param x * @param y * @param z * @return */ private final int getIndex(final int x, final int y, final int z){ final int dx = center + x - cx; final int dy = center + y - cy; final int dz = center + z - cz ; return dx+fY*dy+fZ*dz; } /** * Return -1 if invalid. * @param x * @param y * @param z * @return */ private final int getValidIndex(final int x, final int y, final int z){ final int index = getIndex(x,y,z); if ( index<0 || index>= strength.length) return -1; if ( sequence[index] != seqMax) return -1; return index; } @Override public final int getTypeId(final int x, final int y, final int z){ final int index = getValidIndex(x, y, z); if (index == -1) return -1; return ids[index]; } @Override public List<Block> getExplodingBlocks(World world, double cx, double cy, double cz, float realRadius, ExplosionSettings settings) { { if (realRadius > settings.maxRadius) realRadius = settings.maxRadius; if (realRadius > maxRadius) realRadius = maxRadius; if (realRadius == 0.0){ // TODO: maybe more checks (minRes). return new LinkedList<Block>(); } final float maxPath = settings.maxPathMultiplier; final float minRes = settings.minResistance; if ( this.blocks != null) this.blocks.clear(); // maybe gc :), should only happen on errors. final List<Block> blocks = new LinkedList<Block>(); // could change this to an array, but .... this.blocks = blocks; seqMax ++; // new round ! // starting at center block decrease weight and check neighbor blocks recursively, while weight > durability continue, only check if (FatTnt.DEBUG) System.out.println(Defaults.msgPrefix+"Explosion at: "+world.getName()+" / "+cx+","+cy+","+cz); this.cx = Utils.floor(cx); this.cy = Utils.floor(cy); this.cz = Utils.floor(cz); n = 0; propagate(world, this.cx, this.cy, this.cz, iCenter, 0, 1+(int)(realRadius*maxPath), realRadius, settings); if (FatTnt.DEBUG) System.out.println(Defaults.msgPrefix+"Strength="+realRadius+"("+maxRadius+"/"+minRes+"), visited="+n+", blocks="+blocks.size()); stats.addStats(FatTnt.statsBlocksVisited, n); this.blocks = null; return blocks; } } /** * TEST VERSION / LOW OPTIMIZATION ! * Recursively collect blocks that get destroyed. * @param w * @param x Current real world pos. * @param y * @param z * @param i index of array(s) * @param dir Last direction taken to this point * @param mpl maximum path length allowed from here. * @param expStr Strength of explosion, or radius * @param seq * @param blocks */ final void propagate(final World w, int x, int y, int z, int i, int dir, int mpl, float expStr, final ExplosionSettings settings){ // preparation: // TODO: also set these from the configuration. final int wyMin = 0; final int wyMax = w.getMaxHeight(); final int yMin; final int yMax; if (settings.confine.enabled.getValue(false)){ yMin = settings.confine.yMin.getValue(wyMin).intValue(); yMax = settings.confine.yMax.getValue(wyMax).intValue(); } else{ yMin = wyMin; yMax = wyMax; } final int seqMax = this.seqMax; final int[][] rInts = this.rInts; final float[] rFloats = this.rFloats; final float[] resistance = settings.resistance; final float[] passthrough = settings.passthrough; final float[] strength = this.strength; final int[] sequence = this.sequence; // kk exaggerated maybe... // set initial checking point: int size = 1; rInts[0] = new int[]{x,y,z,i,dir,Math.min(mpl, maxDepth)}; rFloats[0] = expStr; // ? opt: boolean set = false; => get from stack ! if set continue with set values. int ir = ExplosionManager.random.nextInt(rand.length); final int is = rand.length-1; final int iinc = ExplosionManager.random.nextInt(4) + 1; final float defaultResistance = settings.defaultResistance; final boolean useRand = settings.randRadius > 0; + final float randRadius = settings.randRadius; final float fStraight = settings.fStraight; final float minRes = settings.minResistance; // TODO: use minPassthrough ? // iterate while points to check are there: int n = 0; while (size > 0){ n ++; expStr = rFloats[size-1]; int[] temp = rInts[size-1]; x = temp[0]; y = temp[1]; z = temp[2]; i = temp[3]; dir = temp[4]; mpl = temp[5]; size --; // TODO: can still be optimized in order [...] if (sequence[i] == seqMax){ if ( strength[i] >= expStr) continue; } // Block type check (id): final int id; float dur ; // AIR final boolean ign; final boolean isSeq = sequence[i] == seqMax; if ( y>=yMin && y <= yMax){// TODO: maybe +-1 ? if (isSeq) id = ids[i]; else{ id = w.getBlockTypeIdAt(x,y,z); ids[i] = id; } if ( id == 0 ){ ign = true; dur = resistance[0]; } else if (id>0 && id<4096){ dur = resistance[id]; if ( isSeq && strength[i] >= dur) ign = true; // TODO: might be unnecessary else ign = false; } else{ dur = defaultResistance; ign = true; } } else if (y<wyMin || y>wyMax){ // Outside of world: no destruction, treat as air (use resistance). dur = resistance[0]; id = 0; ign = true; } else{ // Confinement: no destruction, use pass-through resistance. // TODO: Get stored id if available. if (isSeq) id = ids[i]; else{ id = w.getBlockTypeIdAt(x,y,z); ids[i] = id; } dur = passthrough[id]; ign = true; } // Resistance check: // Matrix position: if (!isSeq) sequence[i] = seqMax; strength[i] = expStr; // if ( randDec > 0.0) dur += random.nextFloat()*randDec; if ( dur > expStr){ final float ptRes = passthrough[id]; if (ptRes>expStr) continue;// this block stopped this path of propagation. else{ // passthrough: continue to propagate expStr -= ptRes; } } else{ if (!ign) blocks.add(w.getBlockAt(x,y,z)); expStr -= dur; // decrease after setting the array } // Checks for propagation: if (mpl==0) continue; if (i<fZ || i>izMax) continue; // no propagation from edge on. if (useRand){ // TODO: find out something fast, probably just have a task running filling in random numbers now and then. // TODO: maybe the memory size matters... - expStr += rand[ir]; + expStr += rand[ir] * randRadius; ir += iinc; if (ir>is) ir = mpl; } // TODO: use predefined directions + check here if maximum number of dirction changes is reached ! // propagate: for (int k = 0; k < ortDir.length; k++){ final int nd = ortDir[k]; // (iterate over orthogonal directions) if (nd == oDir[dir]) continue; // prevent walking back. final float effStr; // strength to be used. // Check penalty for propagation in the same direction again: if (nd == dir) effStr = expStr * fStraight; else effStr = expStr; if (effStr<minRes) continue; // not strong enough to propagate through any further block. // Propagate if appropriate (not visited or with smaller strength). final int j = i + aInc[nd]; if (sequence[j]!=seqMax || effStr>strength[j]){ rFloats[size] = effStr; final int[] nInts = rInts[size]; nInts[0] = x+xInc[nd]; nInts[1] = y+yInc[nd]; nInts[2] = z+zInc[nd]; nInts[3] = j; nInts[4] = nd; nInts[5] = mpl-1; size++; } } } this.n = n; } @Override public void onIdle() { if (System.currentTimeMillis() - tsLastIdle >= 30000) initRandomArrays(); } }
false
true
final void propagate(final World w, int x, int y, int z, int i, int dir, int mpl, float expStr, final ExplosionSettings settings){ // preparation: // TODO: also set these from the configuration. final int wyMin = 0; final int wyMax = w.getMaxHeight(); final int yMin; final int yMax; if (settings.confine.enabled.getValue(false)){ yMin = settings.confine.yMin.getValue(wyMin).intValue(); yMax = settings.confine.yMax.getValue(wyMax).intValue(); } else{ yMin = wyMin; yMax = wyMax; } final int seqMax = this.seqMax; final int[][] rInts = this.rInts; final float[] rFloats = this.rFloats; final float[] resistance = settings.resistance; final float[] passthrough = settings.passthrough; final float[] strength = this.strength; final int[] sequence = this.sequence; // kk exaggerated maybe... // set initial checking point: int size = 1; rInts[0] = new int[]{x,y,z,i,dir,Math.min(mpl, maxDepth)}; rFloats[0] = expStr; // ? opt: boolean set = false; => get from stack ! if set continue with set values. int ir = ExplosionManager.random.nextInt(rand.length); final int is = rand.length-1; final int iinc = ExplosionManager.random.nextInt(4) + 1; final float defaultResistance = settings.defaultResistance; final boolean useRand = settings.randRadius > 0; final float fStraight = settings.fStraight; final float minRes = settings.minResistance; // TODO: use minPassthrough ? // iterate while points to check are there: int n = 0; while (size > 0){ n ++; expStr = rFloats[size-1]; int[] temp = rInts[size-1]; x = temp[0]; y = temp[1]; z = temp[2]; i = temp[3]; dir = temp[4]; mpl = temp[5]; size --; // TODO: can still be optimized in order [...] if (sequence[i] == seqMax){ if ( strength[i] >= expStr) continue; } // Block type check (id): final int id; float dur ; // AIR final boolean ign; final boolean isSeq = sequence[i] == seqMax; if ( y>=yMin && y <= yMax){// TODO: maybe +-1 ? if (isSeq) id = ids[i]; else{ id = w.getBlockTypeIdAt(x,y,z); ids[i] = id; } if ( id == 0 ){ ign = true; dur = resistance[0]; } else if (id>0 && id<4096){ dur = resistance[id]; if ( isSeq && strength[i] >= dur) ign = true; // TODO: might be unnecessary else ign = false; } else{ dur = defaultResistance; ign = true; } } else if (y<wyMin || y>wyMax){ // Outside of world: no destruction, treat as air (use resistance). dur = resistance[0]; id = 0; ign = true; } else{ // Confinement: no destruction, use pass-through resistance. // TODO: Get stored id if available. if (isSeq) id = ids[i]; else{ id = w.getBlockTypeIdAt(x,y,z); ids[i] = id; } dur = passthrough[id]; ign = true; } // Resistance check: // Matrix position: if (!isSeq) sequence[i] = seqMax; strength[i] = expStr; // if ( randDec > 0.0) dur += random.nextFloat()*randDec; if ( dur > expStr){ final float ptRes = passthrough[id]; if (ptRes>expStr) continue;// this block stopped this path of propagation. else{ // passthrough: continue to propagate expStr -= ptRes; } } else{ if (!ign) blocks.add(w.getBlockAt(x,y,z)); expStr -= dur; // decrease after setting the array } // Checks for propagation: if (mpl==0) continue; if (i<fZ || i>izMax) continue; // no propagation from edge on. if (useRand){ // TODO: find out something fast, probably just have a task running filling in random numbers now and then. // TODO: maybe the memory size matters... expStr += rand[ir]; ir += iinc; if (ir>is) ir = mpl; } // TODO: use predefined directions + check here if maximum number of dirction changes is reached ! // propagate: for (int k = 0; k < ortDir.length; k++){ final int nd = ortDir[k]; // (iterate over orthogonal directions) if (nd == oDir[dir]) continue; // prevent walking back. final float effStr; // strength to be used. // Check penalty for propagation in the same direction again: if (nd == dir) effStr = expStr * fStraight; else effStr = expStr; if (effStr<minRes) continue; // not strong enough to propagate through any further block. // Propagate if appropriate (not visited or with smaller strength). final int j = i + aInc[nd]; if (sequence[j]!=seqMax || effStr>strength[j]){ rFloats[size] = effStr; final int[] nInts = rInts[size]; nInts[0] = x+xInc[nd]; nInts[1] = y+yInc[nd]; nInts[2] = z+zInc[nd]; nInts[3] = j; nInts[4] = nd; nInts[5] = mpl-1; size++; } } } this.n = n; }
final void propagate(final World w, int x, int y, int z, int i, int dir, int mpl, float expStr, final ExplosionSettings settings){ // preparation: // TODO: also set these from the configuration. final int wyMin = 0; final int wyMax = w.getMaxHeight(); final int yMin; final int yMax; if (settings.confine.enabled.getValue(false)){ yMin = settings.confine.yMin.getValue(wyMin).intValue(); yMax = settings.confine.yMax.getValue(wyMax).intValue(); } else{ yMin = wyMin; yMax = wyMax; } final int seqMax = this.seqMax; final int[][] rInts = this.rInts; final float[] rFloats = this.rFloats; final float[] resistance = settings.resistance; final float[] passthrough = settings.passthrough; final float[] strength = this.strength; final int[] sequence = this.sequence; // kk exaggerated maybe... // set initial checking point: int size = 1; rInts[0] = new int[]{x,y,z,i,dir,Math.min(mpl, maxDepth)}; rFloats[0] = expStr; // ? opt: boolean set = false; => get from stack ! if set continue with set values. int ir = ExplosionManager.random.nextInt(rand.length); final int is = rand.length-1; final int iinc = ExplosionManager.random.nextInt(4) + 1; final float defaultResistance = settings.defaultResistance; final boolean useRand = settings.randRadius > 0; final float randRadius = settings.randRadius; final float fStraight = settings.fStraight; final float minRes = settings.minResistance; // TODO: use minPassthrough ? // iterate while points to check are there: int n = 0; while (size > 0){ n ++; expStr = rFloats[size-1]; int[] temp = rInts[size-1]; x = temp[0]; y = temp[1]; z = temp[2]; i = temp[3]; dir = temp[4]; mpl = temp[5]; size --; // TODO: can still be optimized in order [...] if (sequence[i] == seqMax){ if ( strength[i] >= expStr) continue; } // Block type check (id): final int id; float dur ; // AIR final boolean ign; final boolean isSeq = sequence[i] == seqMax; if ( y>=yMin && y <= yMax){// TODO: maybe +-1 ? if (isSeq) id = ids[i]; else{ id = w.getBlockTypeIdAt(x,y,z); ids[i] = id; } if ( id == 0 ){ ign = true; dur = resistance[0]; } else if (id>0 && id<4096){ dur = resistance[id]; if ( isSeq && strength[i] >= dur) ign = true; // TODO: might be unnecessary else ign = false; } else{ dur = defaultResistance; ign = true; } } else if (y<wyMin || y>wyMax){ // Outside of world: no destruction, treat as air (use resistance). dur = resistance[0]; id = 0; ign = true; } else{ // Confinement: no destruction, use pass-through resistance. // TODO: Get stored id if available. if (isSeq) id = ids[i]; else{ id = w.getBlockTypeIdAt(x,y,z); ids[i] = id; } dur = passthrough[id]; ign = true; } // Resistance check: // Matrix position: if (!isSeq) sequence[i] = seqMax; strength[i] = expStr; // if ( randDec > 0.0) dur += random.nextFloat()*randDec; if ( dur > expStr){ final float ptRes = passthrough[id]; if (ptRes>expStr) continue;// this block stopped this path of propagation. else{ // passthrough: continue to propagate expStr -= ptRes; } } else{ if (!ign) blocks.add(w.getBlockAt(x,y,z)); expStr -= dur; // decrease after setting the array } // Checks for propagation: if (mpl==0) continue; if (i<fZ || i>izMax) continue; // no propagation from edge on. if (useRand){ // TODO: find out something fast, probably just have a task running filling in random numbers now and then. // TODO: maybe the memory size matters... expStr += rand[ir] * randRadius; ir += iinc; if (ir>is) ir = mpl; } // TODO: use predefined directions + check here if maximum number of dirction changes is reached ! // propagate: for (int k = 0; k < ortDir.length; k++){ final int nd = ortDir[k]; // (iterate over orthogonal directions) if (nd == oDir[dir]) continue; // prevent walking back. final float effStr; // strength to be used. // Check penalty for propagation in the same direction again: if (nd == dir) effStr = expStr * fStraight; else effStr = expStr; if (effStr<minRes) continue; // not strong enough to propagate through any further block. // Propagate if appropriate (not visited or with smaller strength). final int j = i + aInc[nd]; if (sequence[j]!=seqMax || effStr>strength[j]){ rFloats[size] = effStr; final int[] nInts = rInts[size]; nInts[0] = x+xInc[nd]; nInts[1] = y+yInc[nd]; nInts[2] = z+zInc[nd]; nInts[3] = j; nInts[4] = nd; nInts[5] = mpl-1; size++; } } } this.n = n; }
diff --git a/runtime/src/com/sun/xml/bind/v2/runtime/unmarshaller/StructureLoader.java b/runtime/src/com/sun/xml/bind/v2/runtime/unmarshaller/StructureLoader.java index ce64d74a..22f70888 100644 --- a/runtime/src/com/sun/xml/bind/v2/runtime/unmarshaller/StructureLoader.java +++ b/runtime/src/com/sun/xml/bind/v2/runtime/unmarshaller/StructureLoader.java @@ -1,283 +1,287 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package com.sun.xml.bind.v2.runtime.unmarshaller; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.xml.namespace.QName; import com.sun.xml.bind.api.AccessorException; import com.sun.xml.bind.v2.WellKnownNamespace; import com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl; import com.sun.xml.bind.v2.runtime.JAXBContextImpl; import com.sun.xml.bind.v2.runtime.JaxBeanInfo; import com.sun.xml.bind.v2.runtime.property.AttributeProperty; import com.sun.xml.bind.v2.runtime.property.Property; import com.sun.xml.bind.v2.runtime.property.StructureLoaderBuilder; import com.sun.xml.bind.v2.runtime.property.UnmarshallerChain; import com.sun.xml.bind.v2.runtime.reflect.Accessor; import com.sun.xml.bind.v2.runtime.reflect.TransducedAccessor; import com.sun.xml.bind.v2.util.QNameMap; import org.xml.sax.Attributes; import org.xml.sax.SAXException; /** * Loads children of an element. * * <p> * This loader works with a single {@link JaxBeanInfo} and handles * attributes, child elements, or child text. * * @author Kohsuke Kawaguchi */ public final class StructureLoader extends Loader { /** * This map statically stores information of the * unmarshaller loader and can be used while unmarshalling * Since creating new QNames is expensive use this optimized * version of the map */ private final QNameMap<ChildLoader> childUnmarshallers = new QNameMap<ChildLoader>(); /** * Loader that processes elements that didn't match anf of the {@link #childUnmarshallers}. * Can be null. */ private /*final*/ ChildLoader catchAll; /** * If we have a loader for processing text. Otherwise null. */ private /*final*/ ChildLoader textHandler; /** * Unmarshallers for attribute values. * May be null if no attribute is expected and {@link #attCatchAll}==null. */ private /*final*/ QNameMap<TransducedAccessor> attUnmarshallers; /** * This will receive all the attributes * that were not processed. Never be null. */ private /*final*/ Accessor<Object,Map<QName,String>> attCatchAll; private final JaxBeanInfo beanInfo; /** * The number of scopes this dispatcher needs to keep active. */ private /*final*/ int frameSize; // this class is potentially useful for general audience, not just for ClassBeanInfoImpl, // but since right now that is the only user, we make the construction code very specific // to ClassBeanInfoImpl. See rev.1.5 of this file for the original general purpose definition. public StructureLoader(ClassBeanInfoImpl beanInfo) { super(true); this.beanInfo = beanInfo; } /** * Completes the initialization. * * <p> * To fix the cyclic reference issue, the main part of the initialization needs to be done * after a {@link StructureLoader} is set to {@link ClassBeanInfoImpl#loader}. */ public void init( JAXBContextImpl context, ClassBeanInfoImpl beanInfo, Accessor<?,Map<QName,String>> attWildcard) { UnmarshallerChain chain = new UnmarshallerChain(context); for (ClassBeanInfoImpl bi = beanInfo; bi != null; bi = bi.superClazz) { for (int i = bi.properties.length - 1; i >= 0; i--) { Property p = bi.properties[i]; switch(p.getKind()) { case ATTRIBUTE: if(attUnmarshallers==null) attUnmarshallers = new QNameMap<TransducedAccessor>(); AttributeProperty ap = (AttributeProperty) p; attUnmarshallers.put(ap.attName.toQName(),ap.xacc); break; case ELEMENT: case REFERENCE: case MAP: case VALUE: p.buildChildElementUnmarshallers(chain,childUnmarshallers); break; } } } this.frameSize = chain.getScopeSize(); textHandler = childUnmarshallers.get(StructureLoaderBuilder.TEXT_HANDLER); catchAll = childUnmarshallers.get(StructureLoaderBuilder.CATCH_ALL); if(attWildcard!=null) { attCatchAll = (Accessor<Object,Map<QName,String>>) attWildcard; // we use attUnmarshallers==null as a sign to skip the attribute processing // altogether, so if we have an att wildcard we need to have an empty qname map. if(attUnmarshallers==null) attUnmarshallers = EMPTY; } else { attCatchAll = null; } } @Override public void startElement(UnmarshallingContext.State state, TagName ea) throws SAXException { UnmarshallingContext context = state.getContext(); // create the object to unmarshal Object child; assert !beanInfo.isImmutable(); // let's see if we can reuse the existing peer object child = context.getInnerPeer(); if(child != null && beanInfo.jaxbType!=child.getClass()) child = null; // unexpected type. if(child != null) beanInfo.reset(child,context); if(child == null) child = context.createInstance(beanInfo); context.recordInnerPeer(child); state.target = child; fireBeforeUnmarshal(beanInfo, child, state); context.startScope(frameSize); if(attUnmarshallers!=null) { Attributes atts = ea.atts; for (int i = 0; i < atts.getLength(); i ++){ String auri = atts.getURI(i); + // may be empty string based on parser settings String alocal = atts.getLocalName(i); - String avalue = atts.getValue(i); + if ("".equals(alocal)) { + alocal = atts.getQName(i); + } + String avalue = atts.getValue(i); TransducedAccessor xacc = attUnmarshallers.get(auri, alocal); try { if(xacc!=null) { xacc.parse(child,avalue); } else if (attCatchAll!=null) { String qname = atts.getQName(i); if(atts.getURI(i).equals(WellKnownNamespace.XML_SCHEMA_INSTANCE)) continue; // xsi:* attributes are meant to be processed by us, not by user apps. Object o = state.target; Map<QName,String> map = attCatchAll.get(o); if(map==null) { // TODO: use ClassFactory.inferImplClass(sig,knownImplClasses) // if null, create a new map. if(attCatchAll.valueType.isAssignableFrom(HashMap.class)) map = new HashMap<QName,String>(); else { // we don't know how to create a map for this. // report an error and back out context.handleError(Messages.UNABLE_TO_CREATE_MAP.format(attCatchAll.valueType)); return; } attCatchAll.set(o,map); } String prefix; int idx = qname.indexOf(':'); if(idx<0) prefix=""; else prefix=qname.substring(0,idx); map.put(new QName(auri,alocal,prefix),avalue); } } catch (AccessorException e) { handleGenericException(e,true); } } } } @Override public void childElement(UnmarshallingContext.State state, TagName arg) throws SAXException { ChildLoader child = childUnmarshallers.get(arg.uri,arg.local); if(child==null) { child = catchAll; if(child==null) { super.childElement(state,arg); return; } } state.loader = child.loader; state.receiver = child.receiver; } @Override public Collection<QName> getExpectedChildElements() { return childUnmarshallers.keySet(); } @Override public Collection<QName> getExpectedAttributes() { return attUnmarshallers.keySet(); } @Override public void text(UnmarshallingContext.State state, CharSequence text) throws SAXException { if(textHandler!=null) textHandler.loader.text(state,text); } @Override public void leaveElement(UnmarshallingContext.State state, TagName ea) throws SAXException { state.getContext().endScope(frameSize); fireAfterUnmarshal(beanInfo, state.target, state.prev); } private static final QNameMap<TransducedAccessor> EMPTY = new QNameMap<TransducedAccessor>(); public JaxBeanInfo getBeanInfo() { return beanInfo; } }
false
true
public void startElement(UnmarshallingContext.State state, TagName ea) throws SAXException { UnmarshallingContext context = state.getContext(); // create the object to unmarshal Object child; assert !beanInfo.isImmutable(); // let's see if we can reuse the existing peer object child = context.getInnerPeer(); if(child != null && beanInfo.jaxbType!=child.getClass()) child = null; // unexpected type. if(child != null) beanInfo.reset(child,context); if(child == null) child = context.createInstance(beanInfo); context.recordInnerPeer(child); state.target = child; fireBeforeUnmarshal(beanInfo, child, state); context.startScope(frameSize); if(attUnmarshallers!=null) { Attributes atts = ea.atts; for (int i = 0; i < atts.getLength(); i ++){ String auri = atts.getURI(i); String alocal = atts.getLocalName(i); String avalue = atts.getValue(i); TransducedAccessor xacc = attUnmarshallers.get(auri, alocal); try { if(xacc!=null) { xacc.parse(child,avalue); } else if (attCatchAll!=null) { String qname = atts.getQName(i); if(atts.getURI(i).equals(WellKnownNamespace.XML_SCHEMA_INSTANCE)) continue; // xsi:* attributes are meant to be processed by us, not by user apps. Object o = state.target; Map<QName,String> map = attCatchAll.get(o); if(map==null) { // TODO: use ClassFactory.inferImplClass(sig,knownImplClasses) // if null, create a new map. if(attCatchAll.valueType.isAssignableFrom(HashMap.class)) map = new HashMap<QName,String>(); else { // we don't know how to create a map for this. // report an error and back out context.handleError(Messages.UNABLE_TO_CREATE_MAP.format(attCatchAll.valueType)); return; } attCatchAll.set(o,map); } String prefix; int idx = qname.indexOf(':'); if(idx<0) prefix=""; else prefix=qname.substring(0,idx); map.put(new QName(auri,alocal,prefix),avalue); } } catch (AccessorException e) { handleGenericException(e,true); } } } }
public void startElement(UnmarshallingContext.State state, TagName ea) throws SAXException { UnmarshallingContext context = state.getContext(); // create the object to unmarshal Object child; assert !beanInfo.isImmutable(); // let's see if we can reuse the existing peer object child = context.getInnerPeer(); if(child != null && beanInfo.jaxbType!=child.getClass()) child = null; // unexpected type. if(child != null) beanInfo.reset(child,context); if(child == null) child = context.createInstance(beanInfo); context.recordInnerPeer(child); state.target = child; fireBeforeUnmarshal(beanInfo, child, state); context.startScope(frameSize); if(attUnmarshallers!=null) { Attributes atts = ea.atts; for (int i = 0; i < atts.getLength(); i ++){ String auri = atts.getURI(i); // may be empty string based on parser settings String alocal = atts.getLocalName(i); if ("".equals(alocal)) { alocal = atts.getQName(i); } String avalue = atts.getValue(i); TransducedAccessor xacc = attUnmarshallers.get(auri, alocal); try { if(xacc!=null) { xacc.parse(child,avalue); } else if (attCatchAll!=null) { String qname = atts.getQName(i); if(atts.getURI(i).equals(WellKnownNamespace.XML_SCHEMA_INSTANCE)) continue; // xsi:* attributes are meant to be processed by us, not by user apps. Object o = state.target; Map<QName,String> map = attCatchAll.get(o); if(map==null) { // TODO: use ClassFactory.inferImplClass(sig,knownImplClasses) // if null, create a new map. if(attCatchAll.valueType.isAssignableFrom(HashMap.class)) map = new HashMap<QName,String>(); else { // we don't know how to create a map for this. // report an error and back out context.handleError(Messages.UNABLE_TO_CREATE_MAP.format(attCatchAll.valueType)); return; } attCatchAll.set(o,map); } String prefix; int idx = qname.indexOf(':'); if(idx<0) prefix=""; else prefix=qname.substring(0,idx); map.put(new QName(auri,alocal,prefix),avalue); } } catch (AccessorException e) { handleGenericException(e,true); } } } }
diff --git a/src/com/jidesoft/converter/RgbColorConverter.java b/src/com/jidesoft/converter/RgbColorConverter.java index 3d771c40..b55497bb 100644 --- a/src/com/jidesoft/converter/RgbColorConverter.java +++ b/src/com/jidesoft/converter/RgbColorConverter.java @@ -1,132 +1,144 @@ /* * @(#) RgbColorConverter.java * * Copyright 2002 - 2003 JIDE Software. All rights reserved. */ package com.jidesoft.converter; import java.awt.*; import java.util.StringTokenizer; /** * If alpha value is not included, converts Color to/from "XXX, XXX, XXX" format. For example "0, 0, 0" is Color(0, 0, * 0) and "255, 0, 255" is Color(255, 0, 255). * <p/> * If alpha value is included, converts Color to/from "XXX, XXX, XXX, XXX" format. For example "0, 0, 0, 255" is * Color(0, 0, 0, 255) and "255, 0, 255, 100" is Color(255, 0, 255, 100). */ public class RgbColorConverter extends ColorConverter { private boolean _alphaIncluded = false; /** * Creates a RgbColorConverter. This is the default constructor and will not include alpha value. */ public RgbColorConverter() { } /** * Creates a RgbColorConverter. With this constructor, you can create a converter with alpha value included. * * @param alphaIncluded the flag if alpha value will be included in this converter */ public RgbColorConverter(boolean alphaIncluded) { _alphaIncluded = alphaIncluded; } /** * Get the flag if this converter should consider alpha value. * <p/> * If you use default constructor, the default value of this flag is false. * <p/> * * @return true if this converter should consider alpha value. * * @see RgbColorConverter */ public boolean isAlphaIncluded() { return _alphaIncluded; } /** * Set the flag if this converter should consider alpha value. * <p/> * * @param alphaIncluded the flag if this converter should consider alpha value. * @see #isAlphaIncluded() */ public void setAlphaIncluded(boolean alphaIncluded) { _alphaIncluded = alphaIncluded; } public String toString(Object object, ConverterContext context) { if (object instanceof Color) { Color color = (Color) object; StringBuffer colorText = new StringBuffer(); colorText.append(color.getRed()).append(", "); colorText.append(color.getGreen()).append(", "); colorText.append(color.getBlue()); if (isAlphaIncluded()) { colorText.append(", ").append(color.getAlpha()); } return new String(colorText); } else { return ""; } } public boolean supportToString(Object object, ConverterContext context) { return true; } public boolean supportFromString(String string, ConverterContext context) { return true; } public Object fromString(String string, ConverterContext context) { if (string == null || string.trim().length() == 0) { return null; } StringTokenizer token = new StringTokenizer(string, ",; "); int r = 0, g = 0, b = 0, a = 255; if (token.hasMoreTokens()) { String s = token.nextToken(); try { r = Integer.parseInt(s, 10) % 256; + if (r < 0) { + r += 256; + } } catch (NumberFormatException e) { return null; } } if (token.hasMoreTokens()) { String s = token.nextToken(); try { g = Integer.parseInt(s, 10) % 256; + if (g < 0) { + g += 256; + } } catch (NumberFormatException e) { return null; } } if (token.hasMoreTokens()) { String s = token.nextToken(); try { b = Integer.parseInt(s, 10) % 256; + if (b < 0) { + b += 256; + } } catch (NumberFormatException e) { return null; } } if (isAlphaIncluded() && token.hasMoreTokens()) { String s = token.nextToken(); try { a = Integer.parseInt(s, 10) % 256; + if (a < 0) { + a += 256; + } } catch (NumberFormatException e) { return null; } } return new Color(r, g, b, a); } }
false
true
public Object fromString(String string, ConverterContext context) { if (string == null || string.trim().length() == 0) { return null; } StringTokenizer token = new StringTokenizer(string, ",; "); int r = 0, g = 0, b = 0, a = 255; if (token.hasMoreTokens()) { String s = token.nextToken(); try { r = Integer.parseInt(s, 10) % 256; } catch (NumberFormatException e) { return null; } } if (token.hasMoreTokens()) { String s = token.nextToken(); try { g = Integer.parseInt(s, 10) % 256; } catch (NumberFormatException e) { return null; } } if (token.hasMoreTokens()) { String s = token.nextToken(); try { b = Integer.parseInt(s, 10) % 256; } catch (NumberFormatException e) { return null; } } if (isAlphaIncluded() && token.hasMoreTokens()) { String s = token.nextToken(); try { a = Integer.parseInt(s, 10) % 256; } catch (NumberFormatException e) { return null; } } return new Color(r, g, b, a); }
public Object fromString(String string, ConverterContext context) { if (string == null || string.trim().length() == 0) { return null; } StringTokenizer token = new StringTokenizer(string, ",; "); int r = 0, g = 0, b = 0, a = 255; if (token.hasMoreTokens()) { String s = token.nextToken(); try { r = Integer.parseInt(s, 10) % 256; if (r < 0) { r += 256; } } catch (NumberFormatException e) { return null; } } if (token.hasMoreTokens()) { String s = token.nextToken(); try { g = Integer.parseInt(s, 10) % 256; if (g < 0) { g += 256; } } catch (NumberFormatException e) { return null; } } if (token.hasMoreTokens()) { String s = token.nextToken(); try { b = Integer.parseInt(s, 10) % 256; if (b < 0) { b += 256; } } catch (NumberFormatException e) { return null; } } if (isAlphaIncluded() && token.hasMoreTokens()) { String s = token.nextToken(); try { a = Integer.parseInt(s, 10) % 256; if (a < 0) { a += 256; } } catch (NumberFormatException e) { return null; } } return new Color(r, g, b, a); }
diff --git a/src/Extra/org/objectweb/proactive/extra/infrastructuremanager/dataresource/database/IMDataResourceImpl.java b/src/Extra/org/objectweb/proactive/extra/infrastructuremanager/dataresource/database/IMDataResourceImpl.java index b714674c7..9d689359b 100644 --- a/src/Extra/org/objectweb/proactive/extra/infrastructuremanager/dataresource/database/IMDataResourceImpl.java +++ b/src/Extra/org/objectweb/proactive/extra/infrastructuremanager/dataresource/database/IMDataResourceImpl.java @@ -1,347 +1,347 @@ /* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library 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 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 * General Public License for more details. * * You should have received a copy of the GNU 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 * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.extra.infrastructuremanager.dataresource.database; import java.io.Serializable; import java.util.ArrayList; import java.util.ListIterator; import java.util.Vector; import org.apache.log4j.Logger; import org.objectweb.proactive.api.ProFuture; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.mop.MOP; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.wrapper.IntWrapper; import org.objectweb.proactive.extra.infrastructuremanager.dataresource.IMDataResource; import org.objectweb.proactive.extra.infrastructuremanager.frontend.NodeSet; import org.objectweb.proactive.extra.infrastructuremanager.imnode.IMNode; import org.objectweb.proactive.extra.infrastructuremanager.nodesource.IMNodeSource; import org.objectweb.proactive.extra.scheduler.common.scripting.ScriptResult; import org.objectweb.proactive.extra.scheduler.common.scripting.VerifyingScript; /** * Implementation of the {@link IMDataResource} interface, * using a {@link IMNodeSource} that provides the nodes to handle. * @author proactive team * */ public class IMDataResourceImpl implements IMDataResource, Serializable { /** */ private static final long serialVersionUID = -3170872605593251201L; private static final int MAX_VERIF_TIMEOUT = 120000; private static final Logger logger = ProActiveLogger.getLogger(Loggers.IM_DATARESOURCE); // Attributes private IMNodeSource nodeManager; //----------------------------------------------------------------------// // CONSTRUCTORS /** * The {@link IMNodeManager} given in parameter must be not null. */ public IMDataResourceImpl(IMNodeSource nodeSource) { this.nodeManager = nodeSource; } public void init() { } /** * find which {@link IMNode} correspond to the {@link Node} given in parameter * and change its state to 'free'. */ public void freeNode(Node node) { ListIterator<IMNode> iterator = nodeManager.getBusyNodes().listIterator(); String nodeURL = null; try { nodeURL = node.getNodeInformation().getURL(); } catch (RuntimeException e) { logger.debug("A Runtime exception occured " + "while obtaining information on the node," + "the node must be down (it will be detected later)", e); // node is down, // will be detected later return; } while (iterator.hasNext()) { IMNode imnode = iterator.next(); // Si le noeud correspond if (imnode.getNodeURL().equals(nodeURL)) { imnode.clean(); // Nettoyage du noeud nodeManager.setFree(imnode); break; } } } public void freeNodes(NodeSet nodes) { for (Node node : nodes) freeNode(node); } public void freeNodes(VirtualNode vnode) { ListIterator<IMNode> iterator = nodeManager.getBusyNodes().listIterator(); while (iterator.hasNext()) { IMNode imnode = iterator.next(); if (imnode.getVNodeName().equals(vnode.getName())) { imnode.clean(); // Cleaning the node nodeManager.setFree(imnode); } } } /** * The {@link #getAtMostNodes(IntWrapper, VerifyingScript)} method has three way to handle the request : * if there is no script, it returns at most the first nb free nodes. * If the script is a dynamic script, the method will test the resources, * until nb nodes verifies the script or if there is no node left. * In the case of a static script, * it will return in priority the nodes on which the given script * has already been verified. */ public NodeSet getAtMostNodes(IntWrapper nb, VerifyingScript verifyingScript) { logger.info("[RESOURCE] Searching for " + nb + " nodes on " + this.nodeManager.getNbFreeNodes() + " free nodes."); ArrayList<IMNode> nodes = nodeManager.getNodesByScript(verifyingScript, true); // log StringBuffer order = new StringBuffer(); for (IMNode n : nodes) order.append(n.getHostName() + " "); logger.info("[RESOURCE] Available nodes are : " + order); NodeSet result = new NodeSet(); int found = 0; // no verifying script if (verifyingScript == null) { while (!nodes.isEmpty() && (found < nb.intValue())) { IMNode node = nodes.remove(0); node.clean(); try { result.add(node.getNode()); nodeManager.setBusy(node); found++; } catch (NodeException e) { nodeManager.setDown(node); } } // static verif script } else if (!verifyingScript.isDynamic()) { logger.info("Static verif script"); while (!nodes.isEmpty() && (found < nb.intValue())) { IMNode node = nodes.remove(0); if (node.getScriptStatus().containsKey(verifyingScript) && node.getScriptStatus().get(verifyingScript) .equals(IMNode.VERIFIED_SCRIPT)) { node.clean(); try { result.add(node.getNode()); nodeManager.setBusy(node); found++; } catch (NodeException e) { nodeManager.setDown(node); } } else { break; } } Vector<ScriptResult<Boolean>> scriptResults = new Vector<ScriptResult<Boolean>>(); Vector<IMNode> nodeResults = new Vector<IMNode>(); int launched = found; while (!nodes.isEmpty() && (launched++ < nb.intValue())) { nodeResults.add(nodes.get(0)); ScriptResult<Boolean> sr = nodes.get(0) .executeScript(verifyingScript); // if r is not a future, the script has not been executed if (MOP.isReifiedObject(sr)) { scriptResults.add(sr); } else { // script has not been executed on remote host // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", sr.getException()); } nodes.remove(0); } // Recupere les resultats do { try { int idx = ProFuture.waitForAny(scriptResults, MAX_VERIF_TIMEOUT); IMNode imnode = nodeResults.remove(idx); ScriptResult<Boolean> res = scriptResults.remove(idx); if (res.errorOccured()) { // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", res.getException()); } else if (res.getResult()) { // Result OK nodeManager.setVerifyingScript(imnode, verifyingScript); imnode.clean(); try { result.add(imnode.getNode()); nodeManager.setBusy(imnode); found++; } catch (NodeException e) { nodeManager.setDown(imnode); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } else { // result is false nodeManager.setNotVerifyingScript(imnode, verifyingScript); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } catch (ProActiveException e) { // TODO Auto-generated catch block // Wait For Any Timeout... // traitement special e.printStackTrace(); } - } while (!scriptResults.isEmpty() && !nodes.isEmpty() && + } while ((!scriptResults.isEmpty() || !nodes.isEmpty()) && (found < nb.intValue())); } else { logger.info("[RESOURCE] Nodes with dynamic verif script"); Vector<ScriptResult<Boolean>> scriptResults = new Vector<ScriptResult<Boolean>>(); Vector<IMNode> nodeResults = new Vector<IMNode>(); // lance la verif sur les nb premier int launched = 0; while (!nodes.isEmpty() && (launched++ < nb.intValue())) { nodeResults.add(nodes.get(0)); ScriptResult<Boolean> r = nodes.get(0) .executeScript(verifyingScript); // if r is not a future, the script has not been executed if (MOP.isReifiedObject(r)) { scriptResults.add(r); } else { // script has not been executed on remote host // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", r.getException()); } nodes.remove(0); } // testing script results do { try { //int idx = ProActive.waitForAny(scriptResults, MAX_VERIF_TIMEOUT); int idx = ProFuture.waitForAny(scriptResults); // idx could be -1 if an error occured in wfa (or timeout expires) IMNode imnode = nodeResults.remove(idx); ScriptResult<Boolean> res = scriptResults.remove(idx); if (res.errorOccured()) { // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", res.getException()); } else if (res.getResult()) { // Result OK nodeManager.setVerifyingScript(imnode, verifyingScript); imnode.clean(); try { result.add(imnode.getNode()); nodeManager.setBusy(imnode); found++; } catch (NodeException e) { nodeManager.setDown(imnode); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } else { // result is false nodeManager.setNotVerifyingScript(imnode, verifyingScript); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } catch (Exception e) { // TODO Auto-generated catch block // Wait For Any Timeout... // traitement special e.printStackTrace(); } - } while (!scriptResults.isEmpty() && !nodes.isEmpty() && + } while ((!scriptResults.isEmpty() || !nodes.isEmpty()) && (found < nb.intValue())); } return result; } public NodeSet getExactlyNodes(IntWrapper nb, VerifyingScript verifyingScript) { // TODO Auto-generated method stub return null; } /** * Notifies the {@link IMNodeSource} that the given node is down. */ public void nodeIsDown(IMNode imNode) { nodeManager.setDown(imNode); } }
false
true
public NodeSet getAtMostNodes(IntWrapper nb, VerifyingScript verifyingScript) { logger.info("[RESOURCE] Searching for " + nb + " nodes on " + this.nodeManager.getNbFreeNodes() + " free nodes."); ArrayList<IMNode> nodes = nodeManager.getNodesByScript(verifyingScript, true); // log StringBuffer order = new StringBuffer(); for (IMNode n : nodes) order.append(n.getHostName() + " "); logger.info("[RESOURCE] Available nodes are : " + order); NodeSet result = new NodeSet(); int found = 0; // no verifying script if (verifyingScript == null) { while (!nodes.isEmpty() && (found < nb.intValue())) { IMNode node = nodes.remove(0); node.clean(); try { result.add(node.getNode()); nodeManager.setBusy(node); found++; } catch (NodeException e) { nodeManager.setDown(node); } } // static verif script } else if (!verifyingScript.isDynamic()) { logger.info("Static verif script"); while (!nodes.isEmpty() && (found < nb.intValue())) { IMNode node = nodes.remove(0); if (node.getScriptStatus().containsKey(verifyingScript) && node.getScriptStatus().get(verifyingScript) .equals(IMNode.VERIFIED_SCRIPT)) { node.clean(); try { result.add(node.getNode()); nodeManager.setBusy(node); found++; } catch (NodeException e) { nodeManager.setDown(node); } } else { break; } } Vector<ScriptResult<Boolean>> scriptResults = new Vector<ScriptResult<Boolean>>(); Vector<IMNode> nodeResults = new Vector<IMNode>(); int launched = found; while (!nodes.isEmpty() && (launched++ < nb.intValue())) { nodeResults.add(nodes.get(0)); ScriptResult<Boolean> sr = nodes.get(0) .executeScript(verifyingScript); // if r is not a future, the script has not been executed if (MOP.isReifiedObject(sr)) { scriptResults.add(sr); } else { // script has not been executed on remote host // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", sr.getException()); } nodes.remove(0); } // Recupere les resultats do { try { int idx = ProFuture.waitForAny(scriptResults, MAX_VERIF_TIMEOUT); IMNode imnode = nodeResults.remove(idx); ScriptResult<Boolean> res = scriptResults.remove(idx); if (res.errorOccured()) { // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", res.getException()); } else if (res.getResult()) { // Result OK nodeManager.setVerifyingScript(imnode, verifyingScript); imnode.clean(); try { result.add(imnode.getNode()); nodeManager.setBusy(imnode); found++; } catch (NodeException e) { nodeManager.setDown(imnode); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } else { // result is false nodeManager.setNotVerifyingScript(imnode, verifyingScript); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } catch (ProActiveException e) { // TODO Auto-generated catch block // Wait For Any Timeout... // traitement special e.printStackTrace(); } } while (!scriptResults.isEmpty() && !nodes.isEmpty() && (found < nb.intValue())); } else { logger.info("[RESOURCE] Nodes with dynamic verif script"); Vector<ScriptResult<Boolean>> scriptResults = new Vector<ScriptResult<Boolean>>(); Vector<IMNode> nodeResults = new Vector<IMNode>(); // lance la verif sur les nb premier int launched = 0; while (!nodes.isEmpty() && (launched++ < nb.intValue())) { nodeResults.add(nodes.get(0)); ScriptResult<Boolean> r = nodes.get(0) .executeScript(verifyingScript); // if r is not a future, the script has not been executed if (MOP.isReifiedObject(r)) { scriptResults.add(r); } else { // script has not been executed on remote host // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", r.getException()); } nodes.remove(0); } // testing script results do { try { //int idx = ProActive.waitForAny(scriptResults, MAX_VERIF_TIMEOUT); int idx = ProFuture.waitForAny(scriptResults); // idx could be -1 if an error occured in wfa (or timeout expires) IMNode imnode = nodeResults.remove(idx); ScriptResult<Boolean> res = scriptResults.remove(idx); if (res.errorOccured()) { // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", res.getException()); } else if (res.getResult()) { // Result OK nodeManager.setVerifyingScript(imnode, verifyingScript); imnode.clean(); try { result.add(imnode.getNode()); nodeManager.setBusy(imnode); found++; } catch (NodeException e) { nodeManager.setDown(imnode); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } else { // result is false nodeManager.setNotVerifyingScript(imnode, verifyingScript); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } catch (Exception e) { // TODO Auto-generated catch block // Wait For Any Timeout... // traitement special e.printStackTrace(); } } while (!scriptResults.isEmpty() && !nodes.isEmpty() && (found < nb.intValue())); } return result; }
public NodeSet getAtMostNodes(IntWrapper nb, VerifyingScript verifyingScript) { logger.info("[RESOURCE] Searching for " + nb + " nodes on " + this.nodeManager.getNbFreeNodes() + " free nodes."); ArrayList<IMNode> nodes = nodeManager.getNodesByScript(verifyingScript, true); // log StringBuffer order = new StringBuffer(); for (IMNode n : nodes) order.append(n.getHostName() + " "); logger.info("[RESOURCE] Available nodes are : " + order); NodeSet result = new NodeSet(); int found = 0; // no verifying script if (verifyingScript == null) { while (!nodes.isEmpty() && (found < nb.intValue())) { IMNode node = nodes.remove(0); node.clean(); try { result.add(node.getNode()); nodeManager.setBusy(node); found++; } catch (NodeException e) { nodeManager.setDown(node); } } // static verif script } else if (!verifyingScript.isDynamic()) { logger.info("Static verif script"); while (!nodes.isEmpty() && (found < nb.intValue())) { IMNode node = nodes.remove(0); if (node.getScriptStatus().containsKey(verifyingScript) && node.getScriptStatus().get(verifyingScript) .equals(IMNode.VERIFIED_SCRIPT)) { node.clean(); try { result.add(node.getNode()); nodeManager.setBusy(node); found++; } catch (NodeException e) { nodeManager.setDown(node); } } else { break; } } Vector<ScriptResult<Boolean>> scriptResults = new Vector<ScriptResult<Boolean>>(); Vector<IMNode> nodeResults = new Vector<IMNode>(); int launched = found; while (!nodes.isEmpty() && (launched++ < nb.intValue())) { nodeResults.add(nodes.get(0)); ScriptResult<Boolean> sr = nodes.get(0) .executeScript(verifyingScript); // if r is not a future, the script has not been executed if (MOP.isReifiedObject(sr)) { scriptResults.add(sr); } else { // script has not been executed on remote host // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", sr.getException()); } nodes.remove(0); } // Recupere les resultats do { try { int idx = ProFuture.waitForAny(scriptResults, MAX_VERIF_TIMEOUT); IMNode imnode = nodeResults.remove(idx); ScriptResult<Boolean> res = scriptResults.remove(idx); if (res.errorOccured()) { // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", res.getException()); } else if (res.getResult()) { // Result OK nodeManager.setVerifyingScript(imnode, verifyingScript); imnode.clean(); try { result.add(imnode.getNode()); nodeManager.setBusy(imnode); found++; } catch (NodeException e) { nodeManager.setDown(imnode); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } else { // result is false nodeManager.setNotVerifyingScript(imnode, verifyingScript); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } catch (ProActiveException e) { // TODO Auto-generated catch block // Wait For Any Timeout... // traitement special e.printStackTrace(); } } while ((!scriptResults.isEmpty() || !nodes.isEmpty()) && (found < nb.intValue())); } else { logger.info("[RESOURCE] Nodes with dynamic verif script"); Vector<ScriptResult<Boolean>> scriptResults = new Vector<ScriptResult<Boolean>>(); Vector<IMNode> nodeResults = new Vector<IMNode>(); // lance la verif sur les nb premier int launched = 0; while (!nodes.isEmpty() && (launched++ < nb.intValue())) { nodeResults.add(nodes.get(0)); ScriptResult<Boolean> r = nodes.get(0) .executeScript(verifyingScript); // if r is not a future, the script has not been executed if (MOP.isReifiedObject(r)) { scriptResults.add(r); } else { // script has not been executed on remote host // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", r.getException()); } nodes.remove(0); } // testing script results do { try { //int idx = ProActive.waitForAny(scriptResults, MAX_VERIF_TIMEOUT); int idx = ProFuture.waitForAny(scriptResults); // idx could be -1 if an error occured in wfa (or timeout expires) IMNode imnode = nodeResults.remove(idx); ScriptResult<Boolean> res = scriptResults.remove(idx); if (res.errorOccured()) { // nothing to do, just let the node in the free list logger.info("Error occured executing verifying script", res.getException()); } else if (res.getResult()) { // Result OK nodeManager.setVerifyingScript(imnode, verifyingScript); imnode.clean(); try { result.add(imnode.getNode()); nodeManager.setBusy(imnode); found++; } catch (NodeException e) { nodeManager.setDown(imnode); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } else { // result is false nodeManager.setNotVerifyingScript(imnode, verifyingScript); // try on a new node if any if (!nodes.isEmpty()) { nodeResults.add(nodes.get(0)); scriptResults.add(nodes.remove(0) .executeScript(verifyingScript)); } } } catch (Exception e) { // TODO Auto-generated catch block // Wait For Any Timeout... // traitement special e.printStackTrace(); } } while ((!scriptResults.isEmpty() || !nodes.isEmpty()) && (found < nb.intValue())); } return result; }
diff --git a/src/de/uni/leipzig/asv/zitationsgraph/preprocessing/Divider.java b/src/de/uni/leipzig/asv/zitationsgraph/preprocessing/Divider.java index e719f10..70d7e5c 100644 --- a/src/de/uni/leipzig/asv/zitationsgraph/preprocessing/Divider.java +++ b/src/de/uni/leipzig/asv/zitationsgraph/preprocessing/Divider.java @@ -1,235 +1,235 @@ package de.uni.leipzig.asv.zitationsgraph.preprocessing; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class to split scientific papers into the three parts. We assume that we have only the plain text with line * breaks. So we only can use this inherent informations. Any splitter taking into account additional meta data * such as layout command within a PDF file would by of a higher order. * As of now, we only support a splitting by a brute force algorithm looking for "Introduction" and "References" * or "Bibliography" as exact string matches in the full text. * Future work: Take into account, that these parts are captions and therefore occurring in a single line, possibly * with a heading numeration. * * @version 0.1 * @author Klaus Lyko * */ public class Divider { Logger logger = Logger.getLogger("ZitGraph"); public static final boolean debug = false; //public static String[] refBoundaries = {"Notes", "Note", "Appendix"}; /** * Holding full text of a scientific paper to be divided. */ private String fullText; String head, body, tail; String introName, extroName; public Divider(String fullText) { super(); this.fullText = fullText; } public void setFullText(String fullText) { this.fullText = fullText; } public String getFullText() { return fullText; } /** * Determines quality of brute force method. * @return */ public int determineBruteForceMethod() { int quality = 0; int headCount = countOccurrenceOfHeading(fullText, "Introduction"); int referenceCount = countOccurrenceOfHeading(fullText, "References"); int bibliographyCount = countOccurrenceOfHeading(fullText, "Bibliography"); introName = "Introduction"; if(referenceCount == 0 && bibliographyCount == 0) { if(debug) logger.warning("Wasn't able to find either 'References' or 'Bibliography' to mark tail."); } if(referenceCount >= 1 && bibliographyCount == 0) { if(debug) logger.info("Using 'Introduction' and 'References'"); extroName = "References"; } if(referenceCount == 0 && bibliographyCount >= 1) { if(debug) logger.info("Using 'Introduction' and 'Bibliography'"); extroName = "Bibliography"; } if(referenceCount > 0 && bibliographyCount > 0) { if(debug) logger.info("Both appearing 'References' and 'Bibliography' atleast once."); if(referenceCount <= bibliographyCount) { if(debug) logger.info("Using 'Introduction' and 'References'"); extroName = "References"; } else { if(debug) logger.info("Using 'Introduction' and 'Bibliography'"); extroName = "Bibliography"; } } quality += headCount + referenceCount + bibliographyCount; return quality; } /** * Splits by brute force method. */ public void splitByBruteForce() { if(introName==null && extroName==null) determineBruteForceMethod(); splitBy(introName, extroName); } /** * Splits fullText into head, body and tail using exact string with the specified words. * @param intro String dividing head and body, taking first occurrence. * @param extro String dividing body and tail, taking last occurrence. */ public void splitBy(String intro, String extro) { //defaults body = fullText; head = fullText; tail = fullText; //split references splitTail(extro); //try to get head splitHead(intro); } private void splitHead(String intro) { Pattern pattern = Pattern.compile("\\s[0-9]*"+intro+"\\n"); Matcher matcher = pattern.matcher(fullText); if(matcher.find()) { if(debug) logger.info("Found "+intro+" at "+matcher.end()); head = fullText.substring(0, matcher.start()); }else { // try "...." after Abstract if(debug) logger.info("Trying to find abstract"); Pattern abstractPattern = Pattern.compile("\\s[0-9]*Abstract\\s"); Matcher abstractMatcher = abstractPattern.matcher(fullText); int abstractOffSet = 0; if(abstractMatcher.find()) { if(debug) logger.info("Found Abstract"); abstractOffSet = abstractMatcher.end(); Pattern pointPattern = Pattern.compile("\\.{4,}"); Matcher pointMatcher = pointPattern.matcher(fullText); while(pointMatcher.find()) { if(pointMatcher.end()>abstractOffSet){ head=fullText.substring(0, pointMatcher.end()); body=fullText.substring(pointMatcher.end()); return; } } head = fullText.substring(0, abstractMatcher.start()); body = fullText.substring(abstractMatcher.start()); } // Apparently abstract wasn't divided by points splitByHeading(); } } private void splitTail(String extro) { //first try to find references - Pattern pattern = Pattern.compile("^(References|Bibliography ).{0,5}$", Pattern.MULTILINE); + Pattern pattern = Pattern.compile("^(References|Bibliography).{0,5}$", Pattern.MULTILINE); Matcher matcher = pattern.matcher(fullText); if(matcher.find()) { matcher.reset(); while(matcher.find()){ tail = fullText.substring(matcher.end()); body = fullText.substring(0, matcher.start()); } //limit int limitOffSet = -1; // for each possible heading of the limit //create patter, get first occurrence in tail Pattern limitPattern = Pattern.compile("^(Note|Notes|Appendix ).{0,5}$", Pattern.MULTILINE); Matcher limitMatcher = limitPattern.matcher(tail); while(limitMatcher.find()) { if(limitOffSet == -1) limitOffSet = limitMatcher.start(); if(limitOffSet > limitMatcher.start()) limitOffSet = limitMatcher.start(); } if(limitOffSet > -1) { if(debug) logger.info("Limiting Reference part until "+limitOffSet+" that is "+tail.substring(limitOffSet, limitOffSet+12)); tail = tail.substring(0, limitOffSet); } }else { if(debug) logger.info("Wasn't able to find '"+extro+"' to split tail and body. So we set reference to null."); tail=null; /* Pattern headingPattern = Pattern.compile("^[0-9]*[A-Z][a-zA-Z].{0,5}$", Pattern.MULTILINE); Matcher headingMatcher = headingPattern.matcher(fullText); while(headingMatcher.find()) { if(debug) logger.info("Heading found to split tail: "+headingMatcher.group()); tail = fullText.substring(headingMatcher.end()+1); body = fullText.substring(0, headingMatcher.start()); } */ } } /** * Method to split a text by headings. * As of now we assume a Heading has a leading number followed by a whitespace character * and some text beginning with upper case letters, such as "3 Related Work" */ private void splitByHeading() { Pattern pattern = Pattern.compile("^[0-9]+\\s[A-Z].*", Pattern.MULTILINE); Matcher matcher; int add = 0; // try to find headings after abstract Pattern abstractPattern = Pattern.compile("^(Abstract).{0,5}$", Pattern.MULTILINE); Matcher abstractMatcher = abstractPattern.matcher(body); if(abstractMatcher.find()) { add = abstractMatcher.end(); matcher = pattern.matcher(body.substring(abstractMatcher.end())); } else { matcher = pattern.matcher(body); } if(matcher.find()) { // found at least once if(debug) logger.info("Splitting by heading at "+add+matcher.start()+ " which is the heading: "+matcher.group()); head = body.substring(0, add+matcher.start()); body = body.substring(add+matcher.start()); } } private int countOccurrenceOfHeading(String text, String heading) { int count = 0; Pattern pattern = Pattern.compile("\\s[0-9]*"+heading+"\\s"); Matcher matcher = pattern.matcher(text); while(matcher.find()) count++; return count; } }
true
true
private void splitTail(String extro) { //first try to find references Pattern pattern = Pattern.compile("^(References|Bibliography ).{0,5}$", Pattern.MULTILINE); Matcher matcher = pattern.matcher(fullText); if(matcher.find()) { matcher.reset(); while(matcher.find()){ tail = fullText.substring(matcher.end()); body = fullText.substring(0, matcher.start()); } //limit int limitOffSet = -1; // for each possible heading of the limit //create patter, get first occurrence in tail Pattern limitPattern = Pattern.compile("^(Note|Notes|Appendix ).{0,5}$", Pattern.MULTILINE); Matcher limitMatcher = limitPattern.matcher(tail); while(limitMatcher.find()) { if(limitOffSet == -1) limitOffSet = limitMatcher.start(); if(limitOffSet > limitMatcher.start()) limitOffSet = limitMatcher.start(); } if(limitOffSet > -1) { if(debug) logger.info("Limiting Reference part until "+limitOffSet+" that is "+tail.substring(limitOffSet, limitOffSet+12)); tail = tail.substring(0, limitOffSet); } }else { if(debug) logger.info("Wasn't able to find '"+extro+"' to split tail and body. So we set reference to null."); tail=null; /* Pattern headingPattern = Pattern.compile("^[0-9]*[A-Z][a-zA-Z].{0,5}$", Pattern.MULTILINE); Matcher headingMatcher = headingPattern.matcher(fullText); while(headingMatcher.find()) { if(debug) logger.info("Heading found to split tail: "+headingMatcher.group()); tail = fullText.substring(headingMatcher.end()+1); body = fullText.substring(0, headingMatcher.start()); } */ } }
private void splitTail(String extro) { //first try to find references Pattern pattern = Pattern.compile("^(References|Bibliography).{0,5}$", Pattern.MULTILINE); Matcher matcher = pattern.matcher(fullText); if(matcher.find()) { matcher.reset(); while(matcher.find()){ tail = fullText.substring(matcher.end()); body = fullText.substring(0, matcher.start()); } //limit int limitOffSet = -1; // for each possible heading of the limit //create patter, get first occurrence in tail Pattern limitPattern = Pattern.compile("^(Note|Notes|Appendix ).{0,5}$", Pattern.MULTILINE); Matcher limitMatcher = limitPattern.matcher(tail); while(limitMatcher.find()) { if(limitOffSet == -1) limitOffSet = limitMatcher.start(); if(limitOffSet > limitMatcher.start()) limitOffSet = limitMatcher.start(); } if(limitOffSet > -1) { if(debug) logger.info("Limiting Reference part until "+limitOffSet+" that is "+tail.substring(limitOffSet, limitOffSet+12)); tail = tail.substring(0, limitOffSet); } }else { if(debug) logger.info("Wasn't able to find '"+extro+"' to split tail and body. So we set reference to null."); tail=null; /* Pattern headingPattern = Pattern.compile("^[0-9]*[A-Z][a-zA-Z].{0,5}$", Pattern.MULTILINE); Matcher headingMatcher = headingPattern.matcher(fullText); while(headingMatcher.find()) { if(debug) logger.info("Heading found to split tail: "+headingMatcher.group()); tail = fullText.substring(headingMatcher.end()+1); body = fullText.substring(0, headingMatcher.start()); } */ } }
diff --git a/src/main/java/org/agilewiki/jid/collection/vlenc/map/BMapJid.java b/src/main/java/org/agilewiki/jid/collection/vlenc/map/BMapJid.java index b595a47..26e5c64 100644 --- a/src/main/java/org/agilewiki/jid/collection/vlenc/map/BMapJid.java +++ b/src/main/java/org/agilewiki/jid/collection/vlenc/map/BMapJid.java @@ -1,574 +1,574 @@ /* * Copyright 2012 Bill La Forge * * This file is part of AgileWiki and is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License (LGPL) as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This code 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * or navigate to the following url http://www.gnu.org/licenses/lgpl-2.1.txt * * Note however that only Scala, Java and JavaScript files are being covered by LGPL. * All other files are covered by the Common Public License (CPL). * A copy of this license is also included and can be * found as well at http://www.opensource.org/licenses/cpl1.0.txt */ package org.agilewiki.jid.collection.vlenc.map; import org.agilewiki.jactor.factory.ActorFactory; import org.agilewiki.jid.Jid; import org.agilewiki.jid._Jid; import org.agilewiki.jid.collection.Collection; import org.agilewiki.jid.collection.flenc.AppJid; import org.agilewiki.jid.collection.vlenc.JAList; import org.agilewiki.jid.scalar.flens.integer.IntegerJid; import org.agilewiki.jid.scalar.flens.integer.IntegerJidFactory; import org.agilewiki.jid.scalar.vlens.actor.UnionJid; /** * A balanced tree that holds a map. */ abstract public class BMapJid<KEY_TYPE extends Comparable<KEY_TYPE>, VALUE_TYPE extends Jid> extends AppJid implements Collection<MapEntry<KEY_TYPE, VALUE_TYPE>>, JAList, JAMap<KEY_TYPE, VALUE_TYPE> { protected final int TUPLE_SIZE = 0; protected final int TUPLE_UNION = 1; protected int nodeCapacity = 28; protected boolean isRoot; public ActorFactory valueFactory; abstract protected ActorFactory getUnionJidFactory() throws Exception; /** * Converts a string to a key. * * @param skey The string to be converted. * @return The key. */ abstract protected KEY_TYPE stringToKey(String skey); protected ActorFactory getValueFactory() throws Exception { if (valueFactory == null) throw new IllegalStateException("valueFactory uninitialized"); return valueFactory; } protected void init() throws Exception { tupleFactories = new ActorFactory[2]; tupleFactories[TUPLE_SIZE] = IntegerJidFactory.fac; tupleFactories[TUPLE_UNION] = getUnionJidFactory(); } protected void setNodeType(String nodeType) throws Exception { getUnionJid().setValue(nodeType); } protected IntegerJid getSizeJid() throws Exception { return (IntegerJid) _iGet(TUPLE_SIZE); } /** * Returns the size of the collection. * * @return The size of the collection. */ @Override public int size() throws Exception { return getSizeJid().getValue(); } protected void incSize(int inc) throws Exception { IntegerJid sj = getSizeJid(); sj.setValue(sj.getValue() + inc); } protected UnionJid getUnionJid() throws Exception { return (UnionJid) _iGet(TUPLE_UNION); } protected MapJid<KEY_TYPE, Jid> getNode() throws Exception { return (MapJid) getUnionJid().getValue(); } public String getNodeType() throws Exception { return getNode().getActorType(); } public boolean isLeaf() throws Exception { return getNodeType().equals("leaf"); } public int nodeSize() throws Exception { return getNode().size(); } public boolean isFat() throws Exception { return nodeSize() >= nodeCapacity; } /** * Returns the selected element. * * @param ndx Selects the element. * @return The ith JID component, or null if the index is out of range. */ @Override public MapEntry<KEY_TYPE, VALUE_TYPE> iGet(int ndx) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); if (isLeaf()) { return (MapEntry<KEY_TYPE, VALUE_TYPE>) node.iGet(ndx); } if (ndx < 0) ndx += size(); if (ndx < 0 || ndx >= size()) return null; int i = 0; while (i < node.size()) { BMapJid<KEY_TYPE, VALUE_TYPE> bnode = (BMapJid) node.iGet(i).getValue(); int bns = bnode.size(); if (ndx < bns) { return bnode.iGet(ndx); } ndx -= bns; i += 1; } return null; } /** * Creates a JID actor and loads its serialized data. * * @param ndx The index of the desired element. * @param bytes Holds the serialized data. * @throws Exception Any exceptions thrown while processing the request. */ @Override public void iSetBytes(int ndx, byte[] bytes) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); if (isLeaf()) { node.iSetBytes(ndx, bytes); return; } if (ndx < 0) ndx += size(); if (ndx < 0 || ndx >= size()) throw new IllegalArgumentException(); int i = 0; while (i < node.size()) { BMapJid<KEY_TYPE, VALUE_TYPE> bnode = (BMapJid) node.iGet(i).getValue(); int bns = bnode.size(); if (ndx < bns) { bnode.iSetBytes(ndx, bytes); return; } ndx -= bns; i += 1; } throw new IllegalArgumentException(); } @Override public void iAdd(int i) throws Exception { throw new UnsupportedOperationException(); } @Override public void iAddBytes(int ndx, byte[] bytes) throws Exception { throw new UnsupportedOperationException(); } /** * Add an entry to the map unless there is an entry with a matching first element. * * @param key Used to match the first element of the entries. * @return True if a new entry was created. */ @Override final public Boolean kMake(KEY_TYPE key) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); if (isLeaf()) { int i = node.search(key); if (i > -1) return false; i = -i - 1; node.iAdd(i); MapEntry<KEY_TYPE, Jid> me = node.iGet(i); me.setKey(key); incSize(1); return true; } int i = node.match(key); MapEntry<KEY_TYPE, Jid> entry = null; if (node.size() == i) { i -= 1; entry = node.iGet(i); entry.setKey(key); } else { entry = node.iGet(i); } BMapJid<KEY_TYPE, VALUE_TYPE> bnode = (BMapJid) entry.getValue(); if (!bnode.kMake(key)) return false; incSize(1); if (bnode.isFat()) { node.iAdd(i - 1); MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> leftEntry = (MapEntry) node.iGet(i - 1); bnode.inodeSplit(leftEntry); if (node.size() < nodeCapacity) return true; if (isRoot) { rootSplit(); } } return true; } protected void rootSplit() throws Exception { MapJid<KEY_TYPE, Jid> oldRootNode = getNode(); String oldType = oldRootNode.getActorType(); getUnionJid().setValue("inode"); MapJid<KEY_TYPE, Jid> newRootNode = getNode(); newRootNode.iAdd(0); newRootNode.iAdd(1); MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> leftEntry = (MapEntry) newRootNode.iGet(0); MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> rightEntry = (MapEntry) newRootNode.iGet(1); BMapJid<KEY_TYPE, Jid> leftBNode = leftEntry.getValue(); BMapJid<KEY_TYPE, Jid> rightBNode = rightEntry.getValue(); leftBNode.setNodeType(oldType); rightBNode.setNodeType(oldType); int h = nodeCapacity / 2; int i = 0; if (oldType.equals("leaf")) { while (i < h) { Jid e = (Jid) oldRootNode.iGet(i); byte[] bytes = e.getSerializedBytes(); leftBNode.iAddBytes(-1, bytes); i += 1; } while (i < nodeCapacity) { Jid e = (Jid) oldRootNode.iGet(i); byte[] bytes = e.getSerializedBytes(); rightBNode.iAddBytes(-1, bytes); i += 1; } } else { while (i < h) { BMapJid<KEY_TYPE, Jid> e = (BMapJid) oldRootNode.iGet(i).getValue(); int eSize = e.size(); byte[] bytes = e.getSerializedBytes(); leftBNode.append(bytes, eSize); i += 1; } while (i < nodeCapacity) { BMapJid<KEY_TYPE, Jid> e = (BMapJid) oldRootNode.iGet(i).getValue(); int eSize = e.size(); byte[] bytes = e.getSerializedBytes(); rightBNode.append(bytes, eSize); i += 1; } } leftEntry.setKey(leftBNode.getLastKey()); rightEntry.setKey(rightBNode.getLastKey()); } protected void inodeSplit(MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> leftEntry) throws Exception { BMapJid<KEY_TYPE, Jid> leftBNode = leftEntry.getValue(); leftBNode.setNodeType(getNodeType()); MapJid<KEY_TYPE, Jid> node = getNode(); int h = nodeCapacity / 2; int i = 0; if (isLeaf()) { while (i < h) { Jid e = (Jid) node.iGet(0); node.iRemove(0); byte[] bytes = e.getSerializedBytes(); leftBNode.iAddBytes(-1, bytes); i += 1; } incSize(-h); } else { while (i < h) { BMapJid<KEY_TYPE, VALUE_TYPE> e = (BMapJid) node.iGet(0).getValue(); node.iRemove(0); int eSize = e.size(); incSize(-eSize); byte[] bytes = e.getSerializedBytes(); leftBNode.append(bytes, eSize); i += 1; } } KEY_TYPE leftKey = leftBNode.getLastKey(); leftEntry.setKey(leftKey); } @Override public void empty() throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); node.empty(); IntegerJid sj = getSizeJid(); sj.setValue(0); } @Override public void iRemove(int ndx) throws Exception { int s = size(); if (ndx < 0) ndx += s; if (ndx < 0 || ndx >= s) throw new IllegalArgumentException(); MapJid<KEY_TYPE, Jid> node = getNode(); if (isLeaf()) { node.iRemove(ndx); incSize(-1); return; } int i = 0; while (i < node.size()) { MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> entry = (MapEntry) node.iGet(ndx); BMapJid<KEY_TYPE, VALUE_TYPE> bnode = (BMapJid) entry.getValue(); int bns = bnode.size(); if (ndx < bns) { bnode.iRemove(ndx); entry.setKey(bnode.getLastKey()); incSize(-1); int bnodeSize = bnode.size(); if (bnodeSize > nodeCapacity / 3) return; if (bnodeSize == 0) { node.iRemove(ndx); } else { if (i > 0) { MapEntry leftEntry = node.iGet(i - 1); BMapJid<KEY_TYPE, VALUE_TYPE> leftBNode = (BMapJid) leftEntry.getValue(); if (leftBNode.nodeSize() + bnodeSize < nodeCapacity) { bnode.append(leftBNode); node.iRemove(i); leftEntry.setKey(leftBNode.getLastKey()); } } if (i + 1 < node.size()) { - MapEntry rightEntry = node.iGet(i - 1); + MapEntry rightEntry = node.iGet(i + 1); BMapJid<KEY_TYPE, VALUE_TYPE> rightBNode = (BMapJid) rightEntry.getValue(); if (bnodeSize + rightBNode.nodeSize() < nodeCapacity) { rightBNode.append(bnode); node.iRemove(i + 1); rightEntry.setKey(rightBNode.getLastKey()); } } } if (node.size() == 1 && isRoot && !isLeaf()) { bnode = (BMapJid) node.iGet(0).getValue(); setNodeType(bnode.getNodeType()); IntegerJid sj = getSizeJid(); sj.setValue(0); bnode.append(this); } return; } ndx -= bns; i += 1; } throw new IllegalArgumentException(); } /** * Removes the item identified by the key. * * @param key The key. * @return True when the item was present and removed. */ @Override final public boolean kRemove(KEY_TYPE key) throws Exception { if (isLeaf()) { MapJid<KEY_TYPE, Jid> node = getNode(); return node.kRemove(key); } MapJid<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> node = (MapJid) getNode(); int ndx = node.match(key); if (ndx == size()) return false; MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> entry = node.iGet(ndx); BMapJid<KEY_TYPE, Jid> bnode = entry.getValue(); if (!bnode.kRemove(key)) return false; entry.setKey(bnode.getLastKey()); incSize(-1); int bnodeSize = bnode.size(); if (bnodeSize > nodeCapacity / 3) return true; if (bnodeSize == 0) { node.iRemove(ndx); } else { if (ndx > 0) { BMapJid<KEY_TYPE, VALUE_TYPE> leftBNode = (BMapJid) node.iGet(ndx - 1).getValue(); if (leftBNode.nodeSize() + bnodeSize < nodeCapacity) { bnode.append((BMapJid<KEY_TYPE,Jid>) leftBNode); node.iRemove(ndx); } } if (ndx + 1 < node.size()) { BMapJid<KEY_TYPE, VALUE_TYPE> rightBNode = (BMapJid) node.iGet(ndx + 1).getValue(); if (bnodeSize + rightBNode.nodeSize() < nodeCapacity) { rightBNode.append((BMapJid<KEY_TYPE,VALUE_TYPE>) bnode); node.iRemove(ndx + 1); } } } if (node.size() == 1 && isRoot && !isLeaf()) { bnode = (BMapJid) node.iGet(0).getValue(); setNodeType(bnode.getNodeType()); IntegerJid sj = getSizeJid(); sj.setValue(0); bnode.append((BMapJid<KEY_TYPE,Jid>) this); } return true; } void append(BMapJid<KEY_TYPE, VALUE_TYPE> leftNode) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); int i = 0; if (isLeaf()) { while (i < node.size()) { Jid e = (Jid) node.iGet(i); leftNode.append(e.getSerializedBytes(), 1); i += 1; } } else { while (i < node.size()) { BMapJid<KEY_TYPE, VALUE_TYPE> e = (BMapJid) node.iGet(i).getValue(); leftNode.append(e.getSerializedBytes(), e.size()); i += 1; } } } void append(byte[] bytes, int eSize) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); node.iAddBytes(-1, bytes); incSize(eSize); } /** * Returns the JID value associated with the key. * * @param key The key. * @return The jid assigned to the key, or null. */ @Override final public VALUE_TYPE kGet(KEY_TYPE key) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); int i = node.search(key); if (i < 0) return null; MapEntry<KEY_TYPE, VALUE_TYPE> t = iGet(i); return t.getValue(); } /** * Returns the JID value with a greater key. * * @param key The key. * @return The matching jid, or null. */ @Override final public MapEntry<KEY_TYPE, VALUE_TYPE> getHigher(KEY_TYPE key) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); int i = node.higher(key); if (i < 0) return null; return (MapEntry<KEY_TYPE, VALUE_TYPE>) iGet(i); } /** * Returns the JID value with the smallest key >= the given key. * * @param key The key. * @return The matching jid, or null. */ @Override final public MapEntry<KEY_TYPE, VALUE_TYPE> getCeiling(KEY_TYPE key) throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); int i = node.ceiling(key); if (i < 0) return null; return (MapEntry<KEY_TYPE, VALUE_TYPE>) iGet(i); } /** * Resolves a JID pathname, returning a JID actor or null. * * @param pathname A JID pathname. * @return A JID actor or null. * @throws Exception Any uncaught exception which occurred while processing the request. */ @Override final public _Jid resolvePathname(String pathname) throws Exception { if (pathname.length() == 0) { return this; } int s = pathname.indexOf("/"); if (s == -1) s = pathname.length(); if (s == 0) throw new IllegalArgumentException("pathname " + pathname); String ns = pathname.substring(0, s); _Jid jid = kGet(stringToKey(ns)); if (jid == null) return null; if (s == pathname.length()) return jid; return jid.resolvePathname(pathname.substring(s + 1)); } public MapEntry<KEY_TYPE, VALUE_TYPE> getFirst() throws Exception { return (MapEntry<KEY_TYPE, VALUE_TYPE>) iGet(0); } public MapEntry<KEY_TYPE, VALUE_TYPE> getLast() throws Exception { return (MapEntry<KEY_TYPE, VALUE_TYPE>) iGet(-1); } public KEY_TYPE getLastKey() throws Exception { MapJid<KEY_TYPE, Jid> node = getNode(); return node.getLastKey(); } }
true
true
public void iRemove(int ndx) throws Exception { int s = size(); if (ndx < 0) ndx += s; if (ndx < 0 || ndx >= s) throw new IllegalArgumentException(); MapJid<KEY_TYPE, Jid> node = getNode(); if (isLeaf()) { node.iRemove(ndx); incSize(-1); return; } int i = 0; while (i < node.size()) { MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> entry = (MapEntry) node.iGet(ndx); BMapJid<KEY_TYPE, VALUE_TYPE> bnode = (BMapJid) entry.getValue(); int bns = bnode.size(); if (ndx < bns) { bnode.iRemove(ndx); entry.setKey(bnode.getLastKey()); incSize(-1); int bnodeSize = bnode.size(); if (bnodeSize > nodeCapacity / 3) return; if (bnodeSize == 0) { node.iRemove(ndx); } else { if (i > 0) { MapEntry leftEntry = node.iGet(i - 1); BMapJid<KEY_TYPE, VALUE_TYPE> leftBNode = (BMapJid) leftEntry.getValue(); if (leftBNode.nodeSize() + bnodeSize < nodeCapacity) { bnode.append(leftBNode); node.iRemove(i); leftEntry.setKey(leftBNode.getLastKey()); } } if (i + 1 < node.size()) { MapEntry rightEntry = node.iGet(i - 1); BMapJid<KEY_TYPE, VALUE_TYPE> rightBNode = (BMapJid) rightEntry.getValue(); if (bnodeSize + rightBNode.nodeSize() < nodeCapacity) { rightBNode.append(bnode); node.iRemove(i + 1); rightEntry.setKey(rightBNode.getLastKey()); } } } if (node.size() == 1 && isRoot && !isLeaf()) { bnode = (BMapJid) node.iGet(0).getValue(); setNodeType(bnode.getNodeType()); IntegerJid sj = getSizeJid(); sj.setValue(0); bnode.append(this); } return; } ndx -= bns; i += 1; } throw new IllegalArgumentException(); }
public void iRemove(int ndx) throws Exception { int s = size(); if (ndx < 0) ndx += s; if (ndx < 0 || ndx >= s) throw new IllegalArgumentException(); MapJid<KEY_TYPE, Jid> node = getNode(); if (isLeaf()) { node.iRemove(ndx); incSize(-1); return; } int i = 0; while (i < node.size()) { MapEntry<KEY_TYPE, BMapJid<KEY_TYPE, Jid>> entry = (MapEntry) node.iGet(ndx); BMapJid<KEY_TYPE, VALUE_TYPE> bnode = (BMapJid) entry.getValue(); int bns = bnode.size(); if (ndx < bns) { bnode.iRemove(ndx); entry.setKey(bnode.getLastKey()); incSize(-1); int bnodeSize = bnode.size(); if (bnodeSize > nodeCapacity / 3) return; if (bnodeSize == 0) { node.iRemove(ndx); } else { if (i > 0) { MapEntry leftEntry = node.iGet(i - 1); BMapJid<KEY_TYPE, VALUE_TYPE> leftBNode = (BMapJid) leftEntry.getValue(); if (leftBNode.nodeSize() + bnodeSize < nodeCapacity) { bnode.append(leftBNode); node.iRemove(i); leftEntry.setKey(leftBNode.getLastKey()); } } if (i + 1 < node.size()) { MapEntry rightEntry = node.iGet(i + 1); BMapJid<KEY_TYPE, VALUE_TYPE> rightBNode = (BMapJid) rightEntry.getValue(); if (bnodeSize + rightBNode.nodeSize() < nodeCapacity) { rightBNode.append(bnode); node.iRemove(i + 1); rightEntry.setKey(rightBNode.getLastKey()); } } } if (node.size() == 1 && isRoot && !isLeaf()) { bnode = (BMapJid) node.iGet(0).getValue(); setNodeType(bnode.getNodeType()); IntegerJid sj = getSizeJid(); sj.setValue(0); bnode.append(this); } return; } ndx -= bns; i += 1; } throw new IllegalArgumentException(); }
diff --git a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java index a09486b1..2143bfc5 100644 --- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java +++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java @@ -1,1101 +1,1109 @@ /******************************************************************************* * Copyright (c) 2010 xored software, 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 * * Contributors: * xored software, Inc. - initial API and Implementation (Alex Panchenko) *******************************************************************************/ package org.eclipse.dltk.internal.javascript.ti; import static org.eclipse.dltk.javascript.typeinfo.ITypeNames.NUMBER; import static org.eclipse.dltk.javascript.typeinfo.ITypeNames.OBJECT; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Stack; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.core.runtime.Assert; import org.eclipse.dltk.ast.ASTNode; import org.eclipse.dltk.internal.javascript.validation.JavaScriptValidations; import org.eclipse.dltk.javascript.ast.ArrayInitializer; import org.eclipse.dltk.javascript.ast.AsteriskExpression; import org.eclipse.dltk.javascript.ast.BinaryOperation; import org.eclipse.dltk.javascript.ast.BooleanLiteral; import org.eclipse.dltk.javascript.ast.BreakStatement; import org.eclipse.dltk.javascript.ast.CallExpression; import org.eclipse.dltk.javascript.ast.CaseClause; import org.eclipse.dltk.javascript.ast.CatchClause; import org.eclipse.dltk.javascript.ast.CommaExpression; import org.eclipse.dltk.javascript.ast.ConditionalOperator; import org.eclipse.dltk.javascript.ast.ConstStatement; import org.eclipse.dltk.javascript.ast.ContinueStatement; import org.eclipse.dltk.javascript.ast.DecimalLiteral; import org.eclipse.dltk.javascript.ast.DefaultXmlNamespaceStatement; import org.eclipse.dltk.javascript.ast.DeleteStatement; import org.eclipse.dltk.javascript.ast.DoWhileStatement; import org.eclipse.dltk.javascript.ast.EmptyExpression; import org.eclipse.dltk.javascript.ast.EmptyStatement; import org.eclipse.dltk.javascript.ast.Expression; import org.eclipse.dltk.javascript.ast.ForEachInStatement; import org.eclipse.dltk.javascript.ast.ForInStatement; import org.eclipse.dltk.javascript.ast.ForStatement; import org.eclipse.dltk.javascript.ast.FunctionStatement; import org.eclipse.dltk.javascript.ast.GetAllChildrenExpression; import org.eclipse.dltk.javascript.ast.GetArrayItemExpression; import org.eclipse.dltk.javascript.ast.GetLocalNameExpression; import org.eclipse.dltk.javascript.ast.Identifier; import org.eclipse.dltk.javascript.ast.IfStatement; import org.eclipse.dltk.javascript.ast.LabelledStatement; import org.eclipse.dltk.javascript.ast.NewExpression; import org.eclipse.dltk.javascript.ast.NullExpression; import org.eclipse.dltk.javascript.ast.ObjectInitializer; import org.eclipse.dltk.javascript.ast.ObjectInitializerPart; import org.eclipse.dltk.javascript.ast.ParenthesizedExpression; import org.eclipse.dltk.javascript.ast.PropertyExpression; import org.eclipse.dltk.javascript.ast.PropertyInitializer; import org.eclipse.dltk.javascript.ast.RegExpLiteral; import org.eclipse.dltk.javascript.ast.ReturnStatement; import org.eclipse.dltk.javascript.ast.Script; import org.eclipse.dltk.javascript.ast.SimpleType; import org.eclipse.dltk.javascript.ast.Statement; import org.eclipse.dltk.javascript.ast.StatementBlock; import org.eclipse.dltk.javascript.ast.StringLiteral; import org.eclipse.dltk.javascript.ast.SwitchComponent; import org.eclipse.dltk.javascript.ast.SwitchStatement; import org.eclipse.dltk.javascript.ast.ThisExpression; import org.eclipse.dltk.javascript.ast.ThrowStatement; import org.eclipse.dltk.javascript.ast.TryStatement; import org.eclipse.dltk.javascript.ast.TypeOfExpression; import org.eclipse.dltk.javascript.ast.UnaryOperation; import org.eclipse.dltk.javascript.ast.VariableDeclaration; import org.eclipse.dltk.javascript.ast.VariableStatement; import org.eclipse.dltk.javascript.ast.VoidExpression; import org.eclipse.dltk.javascript.ast.VoidOperator; import org.eclipse.dltk.javascript.ast.WhileStatement; import org.eclipse.dltk.javascript.ast.WithStatement; import org.eclipse.dltk.javascript.ast.XmlAttributeIdentifier; import org.eclipse.dltk.javascript.ast.XmlExpressionFragment; import org.eclipse.dltk.javascript.ast.XmlFragment; import org.eclipse.dltk.javascript.ast.XmlLiteral; import org.eclipse.dltk.javascript.ast.XmlTextFragment; import org.eclipse.dltk.javascript.ast.YieldOperator; import org.eclipse.dltk.javascript.parser.JSParser; import org.eclipse.dltk.javascript.parser.PropertyExpressionUtils; import org.eclipse.dltk.javascript.typeinference.IValueCollection; import org.eclipse.dltk.javascript.typeinference.IValueReference; import org.eclipse.dltk.javascript.typeinference.ReferenceKind; import org.eclipse.dltk.javascript.typeinference.ReferenceLocation; import org.eclipse.dltk.javascript.typeinfo.IModelBuilder; import org.eclipse.dltk.javascript.typeinfo.IModelBuilder.IParameter; import org.eclipse.dltk.javascript.typeinfo.IModelBuilder.IVariable; import org.eclipse.dltk.javascript.typeinfo.ITypeNames; import org.eclipse.dltk.javascript.typeinfo.JSTypeSet; import org.eclipse.dltk.javascript.typeinfo.ReferenceSource; import org.eclipse.dltk.javascript.typeinfo.TypeUtil; import org.eclipse.dltk.javascript.typeinfo.model.ArrayType; import org.eclipse.dltk.javascript.typeinfo.model.JSType; import org.eclipse.dltk.javascript.typeinfo.model.Type; import org.eclipse.dltk.javascript.typeinfo.model.TypeInfoModelFactory; import org.eclipse.dltk.javascript.typeinfo.model.TypeKind; import org.eclipse.dltk.javascript.typeinfo.model.TypeRef; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class TypeInferencerVisitor extends TypeInferencerVisitorBase { public TypeInferencerVisitor(ITypeInferenceContext context) { super(context); } private final Stack<Branching> branchings = new Stack<Branching>(); private class Branching { public void end() { branchings.remove(this); } } protected Branching branching() { final Branching branching = new Branching(); branchings.add(branching); return branching; } public ReferenceSource getSource() { final ReferenceSource source = context.getSource(); return source != null ? source : ReferenceSource.UNKNOWN; } protected void assign(IValueReference dest, IValueReference src) { if (branchings.isEmpty()) { dest.setValue(src); } else { dest.addValue(src, false); } } private static final int K_NUMBER = 1; private static final int K_STRING = 2; private static final int K_OTHER = 4; @Override public IValueReference visitArrayInitializer(ArrayInitializer node) { int kind = 0; for (ASTNode astNode : node.getItems()) { if (astNode instanceof StringLiteral) { kind |= K_STRING; } else if (astNode instanceof DecimalLiteral) { kind |= K_NUMBER; } else if (astNode instanceof NullExpression) { // ignore } else { kind |= K_OTHER; visit(astNode); } } if (kind == K_STRING) { return context.getFactory().create(peekContext(), TypeUtil.arrayOf(context.getTypeRef(ITypeNames.STRING))); } else if (kind == K_NUMBER) { return context.getFactory().create(peekContext(), TypeUtil.arrayOf(context.getTypeRef(ITypeNames.NUMBER))); } else { return context.getFactory().createArray(peekContext()); } } @Override public IValueReference visitAsteriskExpression(AsteriskExpression node) { return context.getFactory().createXML(peekContext()); } @Override public IValueReference visitBinaryOperation(BinaryOperation node) { final IValueReference left = visit(node.getLeftExpression()); final IValueReference right = visit(node.getRightExpression()); final int op = node.getOperation(); if (JSParser.ASSIGN == op) { return visitAssign(left, right, node); } else if (left == null && right instanceof ConstantValue) { return right; } else if (op == JSParser.LAND) { return coalesce(right, left); } else if (op == JSParser.GT || op == JSParser.GTE || op == JSParser.LT || op == JSParser.LTE || op == JSParser.NSAME || op == JSParser.SAME || op == JSParser.NEQ || op == JSParser.EQ) { return context.getFactory().createBoolean(peekContext()); } else if (isNumber(left) && isNumber(right)) { return context.getFactory().createNumber(peekContext()); } else if (op == JSParser.ADD) { return left; } else if (JSParser.INSTANCEOF == op) { return context.getFactory().createBoolean(peekContext()); } else if (JSParser.LOR == op) { final JSTypeSet typeSet = JSTypeSet.create(); if (left != null) { typeSet.addAll(left.getDeclaredTypes()); typeSet.addAll(left.getTypes()); } if (right != null) { typeSet.addAll(right.getDeclaredTypes()); typeSet.addAll(right.getTypes()); } return new ConstantValue(typeSet); } else { // TODO handle other operations return null; } } private static IValueReference coalesce(IValueReference v1, IValueReference v2) { return v1 != null ? v1 : v2; } private boolean isNumber(IValueReference ref) { if (ref != null) { if (ref.getTypes().contains(context.getType(NUMBER))) return true; if (context.getType(NUMBER).equals(ref.getDeclaredType())) return true; } return false; } protected IValueReference visitAssign(IValueReference left, IValueReference right, BinaryOperation node) { if (left != null) { if (IValueReference.ARRAY_OP.equals(left.getName()) && node.getLeftExpression() instanceof GetArrayItemExpression) { GetArrayItemExpression arrayItemExpression = (GetArrayItemExpression) node .getLeftExpression(); IValueReference namedChild = extractNamedChild( left.getParent(), arrayItemExpression.getIndex()); if (namedChild != null) { assign(namedChild, right); } else { assign(left, right); } } else { assign(left, right); } } return right; } @Override public IValueReference visitBooleanLiteral(BooleanLiteral node) { return context.getFactory().createBoolean(peekContext()); } @Override public IValueReference visitBreakStatement(BreakStatement node) { return null; } @Override public IValueReference visitCallExpression(CallExpression node) { final IValueReference reference = visit(node.getExpression()); for (ASTNode argument : node.getArguments()) { visit(argument); } if (reference != null) { return reference.getChild(IValueReference.FUNCTION_OP); } else { return null; } } @Override public IValueReference visitCommaExpression(CommaExpression node) { return visit(node.getItems()); } @Override public IValueReference visitConditionalOperator(ConditionalOperator node) { visit(node.getCondition()); return merge(visit(node.getTrueValue()), visit(node.getFalseValue())); } @Override public IValueReference visitConstDeclaration(ConstStatement node) { final IValueCollection context = peekContext(); for (VariableDeclaration declaration : node.getVariables()) { IValueReference constant = createVariable(context, declaration); if (constant != null) constant.setAttribute(IReferenceAttributes.CONSTANT, Boolean.TRUE); } return null; } protected IValueReference createVariable(IValueCollection context, VariableDeclaration declaration) { final Identifier identifier = declaration.getIdentifier(); final String varName = identifier.getName(); final IValueReference reference = context.createChild(varName); final JSVariable variable = new JSVariable(); variable.setName(declaration.getVariableName()); final org.eclipse.dltk.javascript.ast.Type varType = declaration .getType(); if (varType != null) { variable.setType(resolveType(varType)); } if (declaration.getParent() instanceof VariableStatement) { final VariableStatement statement = (VariableStatement) declaration .getParent(); for (IModelBuilder extension : this.context.getModelBuilders()) { extension.processVariable(statement, variable, reporter, getJSDocTypeChecker()); } } if (varType == null) setTypeImpl(reference, variable.getType()); else setType(identifier, reference, variable.getType(), true); reference.setAttribute(IReferenceAttributes.VARIABLE, variable); reference.setKind(inFunction() ? ReferenceKind.LOCAL : ReferenceKind.GLOBAL); reference.setLocation(ReferenceLocation.create(getSource(), declaration.sourceStart(), declaration.sourceEnd(), identifier.sourceStart(), identifier.sourceEnd())); initializeVariable(reference, declaration, variable); return reference; } protected void initializeVariable(final IValueReference reference, VariableDeclaration declaration, IVariable variable) { if (declaration.getInitializer() != null) { IValueReference assignment = visit(declaration.getInitializer()); if (assignment != null) { assign(reference, assignment); if (assignment.getKind() == ReferenceKind.FUNCTION && reference .getAttribute(IReferenceAttributes.PARAMETERS) != null) reference.setKind(ReferenceKind.FUNCTION); } } } @Override public IValueReference visitContinueStatement(ContinueStatement node) { return null; } @Override public IValueReference visitDecimalLiteral(DecimalLiteral node) { return context.getFactory().createNumber(peekContext()); } @Override public IValueReference visitDefaultXmlNamespace( DefaultXmlNamespaceStatement node) { visit(node.getValue()); return null; } @Override public IValueReference visitDeleteStatement(DeleteStatement node) { IValueReference value = visit(node.getExpression()); if (value != null) { value.delete(); } return context.getFactory().createBoolean(peekContext()); } @Override public IValueReference visitDoWhileStatement(DoWhileStatement node) { visit(node.getCondition()); visit(node.getBody()); return null; } @Override public IValueReference visitEmptyExpression(EmptyExpression node) { return null; } @Override public IValueReference visitEmptyStatement(EmptyStatement node) { return null; } @Override public IValueReference visitForEachInStatement(ForEachInStatement node) { IValueReference itemReference = visit(node.getItem()); IValueReference iteratorReference = visit(node.getIterator()); JSType type = JavaScriptValidations.typeOf(iteratorReference); if (type != null && type instanceof ArrayType && JavaScriptValidations.typeOf(itemReference) == null) { final JSType itemType = ((ArrayType) type).getItemType(); itemReference.setDeclaredType(itemType); } visit(node.getBody()); return null; } @Override public IValueReference visitForInStatement(ForInStatement node) { final IValueReference item = visit(node.getItem()); if (item != null) { assign(item, context.getFactory().createString(peekContext())); } visit(node.getIterator()); visit(node.getBody()); return null; } @Override public IValueReference visitForStatement(ForStatement node) { if (node.getInitial() != null) visit(node.getInitial()); if (node.getCondition() != null) visit(node.getCondition()); if (node.getStep() != null) visit(node.getStep()); if (node.getBody() != null) visit(node.getBody()); return null; } @Override public IValueReference visitFunctionStatement(FunctionStatement node) { final JSMethod method = generateJSMethod(node); final IValueCollection function = new FunctionValueCollection( peekContext(), method.getName()); for (IParameter parameter : method.getParameters()) { final IValueReference refArg = function.createChild(parameter .getName()); refArg.setKind(ReferenceKind.ARGUMENT); if (parameter.getPropertiesType() != null) { refArg.setDeclaredType(TypeUtil.ref(parameter .getPropertiesType())); } else { // call directly the impl else unknown type is reported twice if // used in jsdoc, // but when it is declared in code itself it will now fail.. setTypeImpl(refArg, parameter.getType()); } refArg.setLocation(parameter.getLocation()); } final Identifier methodName = node.getName(); final IValueReference result; if (isChildFunction(node)) { result = peekContext().createChild(method.getName()); } else { result = new AnonymousValue(); } result.setLocation(method.getLocation()); result.setKind(ReferenceKind.FUNCTION); result.setDeclaredType(context.getTypeRef(ITypeNames.FUNCTION)); result.setAttribute(IReferenceAttributes.PARAMETERS, method); result.setAttribute(IReferenceAttributes.FUNCTION_SCOPE, function); enterContext(function); try { visitFunctionBody(node); } finally { leaveContext(); } final IValueReference returnValue = result .getChild(IValueReference.FUNCTION_OP); returnValue.addValue(function.getReturnValue(), true); if (node.getReturnType() == null) setTypeImpl(returnValue, method.getType()); else setType(methodName != null ? methodName : node.getFunctionKeyword(), returnValue, method.getType(), true); return result; } /** * @param node * @param methodName * @return */ protected static boolean isChildFunction(FunctionStatement node) { return node.getName() != null && !(node.getParent() instanceof BinaryOperation) && !(node.getParent() instanceof VariableDeclaration) && !(node.getParent() instanceof PropertyInitializer) && !(node.getParent() instanceof NewExpression); } /** * @param node * @return */ protected JSMethod generateJSMethod(FunctionStatement node) { final JSMethod method = new JSMethod(node, getSource()); for (IModelBuilder extension : context.getModelBuilders()) { extension.processMethod(node, method, reporter, getJSDocTypeChecker()); } return method; } public void visitFunctionBody(FunctionStatement node) { visit(node.getBody()); } protected JSType resolveType(org.eclipse.dltk.javascript.ast.Type type) { return context.getTypeRef(type.getName()); } public void setType(ASTNode node, IValueReference value, JSType type, boolean lazy) { setTypeImpl(value, type); } private void setTypeImpl(IValueReference value, JSType type) { if (type != null) { type = context.resolveTypeRef(type); Assert.isTrue(type.getKind() != TypeKind.UNRESOLVED); if (type.getKind() != TypeKind.UNKNOWN) { value.setDeclaredType(type); } else if (type instanceof TypeRef) { value.addValue(new LazyTypeReference(context, type.getName(), peekContext()), false); } } } @Override public IValueReference visitGetAllChildrenExpression( GetAllChildrenExpression node) { return context.getFactory().createXML(peekContext()); } @Override public IValueReference visitGetArrayItemExpression( GetArrayItemExpression node) { final IValueReference array = visit(node.getArray()); visit(node.getIndex()); if (array != null) { // always just create the ARRAY_OP child (for code completion) IValueReference child = array.getChild(IValueReference.ARRAY_OP); JSType arrayType = null; if (array.getDeclaredType() != null) { arrayType = TypeUtil.extractArrayItemType(array .getDeclaredType()); } else { JSTypeSet types = array.getTypes(); if (types.size() > 0) arrayType = TypeUtil.extractArrayItemType(types.getFirst()); } if (arrayType != null && child.getDeclaredType() == null) { child.setDeclaredType(arrayType); } if (node.getIndex() instanceof StringLiteral) { IValueReference namedChild = extractNamedChild(array, node.getIndex()); if (namedChild.exists()) { child = namedChild; if (arrayType != null && namedChild.getDeclaredType() == null) { namedChild.setDeclaredType(arrayType); } } } return child; } return null; } @Override public IValueReference visitGetLocalNameExpression( GetLocalNameExpression node) { return null; } @Override public IValueReference visitIdentifier(Identifier node) { return peekContext().getChild(node.getName()); } private Boolean evaluateCondition(Expression condition) { if (condition instanceof BooleanLiteral) { return Boolean.valueOf(((BooleanLiteral) condition).getText()); } else { return null; } } @Override public IValueReference visitIfStatement(IfStatement node) { visit(node.getCondition()); final List<Statement> statements = new ArrayList<Statement>(2); Statement onlyBranch = null; final Boolean condition = evaluateCondition(node.getCondition()); if ((condition == null || condition.booleanValue()) && node.getThenStatement() != null) { statements.add(node.getThenStatement()); if (condition != null && condition.booleanValue()) { onlyBranch = node.getThenStatement(); } } if ((condition == null || !condition.booleanValue()) && node.getElseStatement() != null) { statements.add(node.getElseStatement()); if (condition != null && !condition.booleanValue()) { onlyBranch = node.getElseStatement(); } } if (!statements.isEmpty()) { if (statements.size() == 1) { if (statements.get(0) == onlyBranch) { visit(statements.get(0)); } else { final Branching branching = branching(); visit(statements.get(0)); branching.end(); } } else { final Branching branching = branching(); final List<NestedValueCollection> collections = new ArrayList<NestedValueCollection>( statements.size()); for (Statement statement : statements) { final NestedValueCollection nestedCollection = new NestedValueCollection( peekContext()); enterContext(nestedCollection); visit(statement); leaveContext(); collections.add(nestedCollection); } NestedValueCollection.mergeTo(peekContext(), collections); branching.end(); } } return null; } @Override public IValueReference visitLabelledStatement(LabelledStatement node) { if (node.getStatement() != null) visit(node.getStatement()); return null; } protected static class AnonymousNewValue extends AnonymousValue { @Override public IValueReference getChild(String name) { if (name.equals(IValueReference.FUNCTION_OP)) return this; return super.getChild(name); } } @Override public IValueReference visitNewExpression(NewExpression node) { Expression objectClass = node.getObjectClass(); if (objectClass instanceof CallExpression) { final CallExpression call = (CallExpression) objectClass; for (ASTNode argument : call.getArguments()) { visit(argument); } objectClass = call.getExpression(); } IValueReference visit = visit(objectClass); IValueReference result = null; if (visit != null) { if (visit.getKind() == ReferenceKind.FUNCTION) { Object fs = visit .getAttribute(IReferenceAttributes.FUNCTION_SCOPE); if (fs instanceof IValueCollection && ((IValueCollection) fs).getThis() != null) { result = new AnonymousNewValue(); result.setValue(((IValueCollection) fs).getThis()); result.setKind(ReferenceKind.TYPE); String className = PropertyExpressionUtils .getPath(objectClass); if (className != null) { Type type = TypeInfoModelFactory.eINSTANCE.createType(); type.setSuperType(context.getKnownType(OBJECT)); type.setKind(TypeKind.JAVASCRIPT); type.setName(className); result.setDeclaredType(TypeUtil.ref(type)); } else { result.setDeclaredType(context.getTypeRef(OBJECT)); } } } else if (visit.exists()) { - final JSTypeSet types = visit.getTypes(); - for (JSType type : types) { + for (JSType type : visit.getDeclaredTypes()) { if (type instanceof TypeRef && ((TypeRef) type).isStatic()) { result = new AnonymousNewValue(); result.setKind(ReferenceKind.TYPE); result.setDeclaredType(TypeUtil.ref(((TypeRef) type) .getTarget())); - break; + return result; + } + } + for (JSType type : visit.getTypes()) { + if (type instanceof TypeRef && ((TypeRef) type).isStatic()) { + result = new AnonymousNewValue(); + result.setKind(ReferenceKind.TYPE); + result.setDeclaredType(TypeUtil.ref(((TypeRef) type) + .getTarget())); + return result; } } } } if (result == null) { final String className = PropertyExpressionUtils .getPath(objectClass); IValueCollection contextValueCollection = peekContext(); if (className != null) { Type knownType = context.getKnownType(className); if (knownType != null) { result = new AnonymousNewValue(); result.setValue(context.getFactory().create( contextValueCollection, TypeUtil.ref(knownType))); result.setKind(ReferenceKind.TYPE); } else { result = new LazyTypeReference(context, className, contextValueCollection); } } else { result = new AnonymousNewValue(); result.setValue(context.getFactory().createObject( contextValueCollection)); } } return result; } @Override public IValueReference visitNullExpression(NullExpression node) { return null; } @Override public IValueReference visitObjectInitializer(ObjectInitializer node) { final IValueReference result = new AnonymousValue(); result.setDeclaredType(TypeUtil.ref(context.getKnownType(OBJECT))); for (ObjectInitializerPart part : node.getInitializers()) { if (part instanceof PropertyInitializer) { final PropertyInitializer pi = (PropertyInitializer) part; final IValueReference child = extractNamedChild(result, pi.getName()); final IValueReference value = visit(pi.getValue()); if (child != null) { child.setValue(value); child.setLocation(ReferenceLocation.create(getSource(), pi .getName().sourceStart(), pi.getName().sourceEnd())); if (child.getKind() == ReferenceKind.UNKNOWN) { child.setKind(ReferenceKind.FIELD); } } } else { // TODO handle get/set methods } } return result; } @Override public IValueReference visitParenthesizedExpression( ParenthesizedExpression node) { return visit(node.getExpression()); } @Override public IValueReference visitPropertyExpression(PropertyExpression node) { final IValueReference object = visit(node.getObject()); Expression property = node.getProperty(); IValueReference child = extractNamedChild(object, property); if (child != null && node.getObject() instanceof ThisExpression && !child.exists()) { if (isFunctionDeclaration(node)) child.setKind(ReferenceKind.FUNCTION); else child.setKind(ReferenceKind.FIELD); child.setLocation(ReferenceLocation.create(getSource(), node.sourceStart(), node.sourceEnd(), property.sourceStart(), property.sourceEnd())); } return child; } protected IValueReference extractNamedChild(IValueReference parent, Expression name) { if (parent != null) { final String nameStr; if (name instanceof Identifier) { nameStr = ((Identifier) name).getName(); } else if (name instanceof StringLiteral) { nameStr = ((StringLiteral) name).getValue(); } else if (name instanceof XmlAttributeIdentifier) { nameStr = ((XmlAttributeIdentifier) name).getAttributeName(); } else { return null; } return parent.getChild(nameStr); } return null; } @Override public IValueReference visitRegExpLiteral(RegExpLiteral node) { return context.getFactory().createRegExp(peekContext()); } @Override public IValueReference visitReturnStatement(ReturnStatement node) { if (node.getValue() != null) { final IValueReference value = visit(node.getValue()); if (value != null) { final IValueReference returnValue = peekContext() .getReturnValue(); if (returnValue != null) { returnValue.addValue(value, !(value instanceof LazyTypeReference)); } } return value; } return null; } @Override public IValueReference visitScript(Script node) { return visit(node.getStatements()); } @Override public IValueReference visitSimpleType(SimpleType node) { // TODO Auto-generated method stub return null; } @Override public IValueReference visitStatementBlock(StatementBlock node) { for (Statement statement : node.getStatements()) { visit(statement); } return null; } @Override public IValueReference visitStringLiteral(StringLiteral node) { return context.getFactory().createString(peekContext()); } @Override public IValueReference visitSwitchStatement(SwitchStatement node) { if (node.getCondition() != null) visit(node.getCondition()); for (SwitchComponent component : node.getCaseClauses()) { if (component instanceof CaseClause) { visit(((CaseClause) component).getCondition()); } visit(component.getStatements()); } return null; } @Override public IValueReference visitThisExpression(ThisExpression node) { return peekContext().getThis(); } @Override public IValueReference visitThrowStatement(ThrowStatement node) { if (node.getException() != null) visit(node.getException()); return null; } @Override public IValueReference visitTryStatement(TryStatement node) { visit(node.getBody()); for (CatchClause catchClause : node.getCatches()) { final NestedValueCollection collection = new NestedValueCollection( peekContext()); collection.createChild(catchClause.getException().getName()); enterContext(collection); if (catchClause.getStatement() != null) { visit(catchClause.getStatement()); } leaveContext(); } if (node.getFinally() != null) { visit(node.getFinally().getStatement()); } return null; } @Override public IValueReference visitTypeOfExpression(TypeOfExpression node) { visit(node.getExpression()); return context.getFactory().createString(peekContext()); } @Override public IValueReference visitUnaryOperation(UnaryOperation node) { return visit(node.getExpression()); } @Override public IValueReference visitVariableStatement(VariableStatement node) { final IValueCollection collection = peekContext(); IValueReference result = null; for (VariableDeclaration declaration : node.getVariables()) { result = createVariable(collection, declaration); final JSVariable variable = new JSVariable(); variable.setName(declaration.getVariableName()); if (result.getDeclaredType() != null) variable.setType(result.getDeclaredType()); for (IModelBuilder extension : context.getModelBuilders()) { extension.processVariable(node, variable, reporter, getJSDocTypeChecker()); } if (result.getDeclaredType() == null && variable.getType() != null) { result.setDeclaredType(variable.getType()); } result.setAttribute(IReferenceAttributes.VARIABLE, variable); } return result; } @Override public IValueReference visitVoidExpression(VoidExpression node) { visit(node.getExpression()); return null; } @Override public IValueReference visitVoidOperator(VoidOperator node) { visit(node.getExpression()); return null; } @Override public IValueReference visitWhileStatement(WhileStatement node) { if (node.getCondition() != null) visit(node.getCondition()); if (node.getBody() != null) visit(node.getBody()); return null; } @Override public IValueReference visitWithStatement(WithStatement node) { final IValueReference with = visit(node.getExpression()); if (with != null) { final WithValueCollection withCollection = new WithValueCollection( peekContext(), with); enterContext(withCollection); visit(node.getStatement()); leaveContext(); } else { visit(node.getStatement()); } return null; } private static final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); private DocumentBuilder docBuilder; /** * @return * @throws ParserConfigurationException */ private DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { if (docBuilder == null) docBuilder = docBuilderFactory.newDocumentBuilder(); return docBuilder; } @Override public IValueReference visitXmlLiteral(XmlLiteral node) { IValueReference xmlValueReference = context.getFactory().createXML( peekContext()); if (xmlValueReference instanceof IValueProvider) { JSType xmlType = TypeUtil.ref(context.getKnownType(ITypeNames.XML)); IValue xmlValue = ((IValueProvider) xmlValueReference).getValue(); List<XmlFragment> fragments = node.getFragments(); StringBuilder xml = new StringBuilder(); for (XmlFragment xmlFragment : fragments) { if (xmlFragment instanceof XmlTextFragment) { String xmlText = ((XmlTextFragment) xmlFragment).getXml(); if (xmlText.equals("<></>")) continue; if (xmlText.startsWith("<>") && xmlText.endsWith("</>")) { xmlText = "<xml>" + xmlText.substring(2, xmlText.length() - 3) + "</xml>"; } xml.append(xmlText); } else if (xmlFragment instanceof XmlExpressionFragment) { Expression expression = ((XmlExpressionFragment) xmlFragment) .getExpression(); visit(expression); if (xml.charAt(xml.length() - 1) == '<' || xml.subSequence(xml.length() - 2, xml.length()) .equals("</")) { if (expression instanceof Identifier) { xml.append(((Identifier) expression).getName()); } else { xml.setLength(0); break; } } else xml.append("\"\""); } } if (xml.length() > 0) { try { DocumentBuilder docBuilder = getDocumentBuilder(); Document doc = docBuilder.parse(new InputSource( new StringReader(xml.toString()))); NodeList nl = doc.getChildNodes(); if (nl.getLength() == 1) { Node item = nl.item(0); NamedNodeMap attributes = item.getAttributes(); for (int a = 0; a < attributes.getLength(); a++) { Node attribute = attributes.item(a); xmlValue.createChild("@" + attribute.getNodeName()); } createXmlChilds(xmlType, xmlValue, item.getChildNodes()); } else { System.err.println("root should be 1 child?? " + xml); } } catch (Exception e) { } } } return xmlValueReference; } /** * @param xmlType * @param xmlValue * @param nl */ private void createXmlChilds(JSType xmlType, IValue xmlValue, NodeList nl) { for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); if (item.getNodeType() == Node.TEXT_NODE) { String value = item.getNodeValue(); if (value == null || "".equals(value.trim())) { continue; } } IValue nodeValue = xmlValue.createChild(item.getNodeName()); nodeValue.setDeclaredType(xmlType); NamedNodeMap attributes = item.getAttributes(); if (attributes != null) { for (int a = 0; a < attributes.getLength(); a++) { Node attribute = attributes.item(a); nodeValue.createChild("@" + attribute.getNodeName()); } } createXmlChilds(xmlType, nodeValue, item.getChildNodes()); } } @Override public IValueReference visitXmlPropertyIdentifier( XmlAttributeIdentifier node) { return context.getFactory().createXML(peekContext()); } @Override public IValueReference visitYieldOperator(YieldOperator node) { final IValueReference value = visit(node.getExpression()); if (value != null) { final IValueReference reference = peekContext().getReturnValue(); if (reference != null) { reference.addValue(value, true); } } return null; } public static boolean isFunctionDeclaration(Expression expression) { PropertyExpression pe = null; if (expression instanceof PropertyExpression) pe = (PropertyExpression) expression; else if (expression.getParent() instanceof PropertyExpression) pe = (PropertyExpression) expression.getParent(); if (pe != null && pe.getObject() instanceof ThisExpression && pe.getParent() instanceof BinaryOperation) { return ((BinaryOperation) pe.getParent()).getRightExpression() instanceof FunctionStatement; } return false; } }
false
true
public IValueReference visitNewExpression(NewExpression node) { Expression objectClass = node.getObjectClass(); if (objectClass instanceof CallExpression) { final CallExpression call = (CallExpression) objectClass; for (ASTNode argument : call.getArguments()) { visit(argument); } objectClass = call.getExpression(); } IValueReference visit = visit(objectClass); IValueReference result = null; if (visit != null) { if (visit.getKind() == ReferenceKind.FUNCTION) { Object fs = visit .getAttribute(IReferenceAttributes.FUNCTION_SCOPE); if (fs instanceof IValueCollection && ((IValueCollection) fs).getThis() != null) { result = new AnonymousNewValue(); result.setValue(((IValueCollection) fs).getThis()); result.setKind(ReferenceKind.TYPE); String className = PropertyExpressionUtils .getPath(objectClass); if (className != null) { Type type = TypeInfoModelFactory.eINSTANCE.createType(); type.setSuperType(context.getKnownType(OBJECT)); type.setKind(TypeKind.JAVASCRIPT); type.setName(className); result.setDeclaredType(TypeUtil.ref(type)); } else { result.setDeclaredType(context.getTypeRef(OBJECT)); } } } else if (visit.exists()) { final JSTypeSet types = visit.getTypes(); for (JSType type : types) { if (type instanceof TypeRef && ((TypeRef) type).isStatic()) { result = new AnonymousNewValue(); result.setKind(ReferenceKind.TYPE); result.setDeclaredType(TypeUtil.ref(((TypeRef) type) .getTarget())); break; } } } } if (result == null) { final String className = PropertyExpressionUtils .getPath(objectClass); IValueCollection contextValueCollection = peekContext(); if (className != null) { Type knownType = context.getKnownType(className); if (knownType != null) { result = new AnonymousNewValue(); result.setValue(context.getFactory().create( contextValueCollection, TypeUtil.ref(knownType))); result.setKind(ReferenceKind.TYPE); } else { result = new LazyTypeReference(context, className, contextValueCollection); } } else { result = new AnonymousNewValue(); result.setValue(context.getFactory().createObject( contextValueCollection)); } } return result; }
public IValueReference visitNewExpression(NewExpression node) { Expression objectClass = node.getObjectClass(); if (objectClass instanceof CallExpression) { final CallExpression call = (CallExpression) objectClass; for (ASTNode argument : call.getArguments()) { visit(argument); } objectClass = call.getExpression(); } IValueReference visit = visit(objectClass); IValueReference result = null; if (visit != null) { if (visit.getKind() == ReferenceKind.FUNCTION) { Object fs = visit .getAttribute(IReferenceAttributes.FUNCTION_SCOPE); if (fs instanceof IValueCollection && ((IValueCollection) fs).getThis() != null) { result = new AnonymousNewValue(); result.setValue(((IValueCollection) fs).getThis()); result.setKind(ReferenceKind.TYPE); String className = PropertyExpressionUtils .getPath(objectClass); if (className != null) { Type type = TypeInfoModelFactory.eINSTANCE.createType(); type.setSuperType(context.getKnownType(OBJECT)); type.setKind(TypeKind.JAVASCRIPT); type.setName(className); result.setDeclaredType(TypeUtil.ref(type)); } else { result.setDeclaredType(context.getTypeRef(OBJECT)); } } } else if (visit.exists()) { for (JSType type : visit.getDeclaredTypes()) { if (type instanceof TypeRef && ((TypeRef) type).isStatic()) { result = new AnonymousNewValue(); result.setKind(ReferenceKind.TYPE); result.setDeclaredType(TypeUtil.ref(((TypeRef) type) .getTarget())); return result; } } for (JSType type : visit.getTypes()) { if (type instanceof TypeRef && ((TypeRef) type).isStatic()) { result = new AnonymousNewValue(); result.setKind(ReferenceKind.TYPE); result.setDeclaredType(TypeUtil.ref(((TypeRef) type) .getTarget())); return result; } } } } if (result == null) { final String className = PropertyExpressionUtils .getPath(objectClass); IValueCollection contextValueCollection = peekContext(); if (className != null) { Type knownType = context.getKnownType(className); if (knownType != null) { result = new AnonymousNewValue(); result.setValue(context.getFactory().create( contextValueCollection, TypeUtil.ref(knownType))); result.setKind(ReferenceKind.TYPE); } else { result = new LazyTypeReference(context, className, contextValueCollection); } } else { result = new AnonymousNewValue(); result.setValue(context.getFactory().createObject( contextValueCollection)); } } return result; }
diff --git a/src/foobar/FoobarSuggestions.java b/src/foobar/FoobarSuggestions.java index cab873f..e5f6685 100644 --- a/src/foobar/FoobarSuggestions.java +++ b/src/foobar/FoobarSuggestions.java @@ -1,110 +1,110 @@ package foobar; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.ListSelectionModel; /** * The FoobarSuggestions are displayed to the user from a Popup window, which is * triggered on an individual key press in FoobarField as dictated by * FoobarKeyListener. FoobarSuggestions are immutable JLists of Fooables. * * @author Frank Goodman * */ public final class FoobarSuggestions extends JList<Fooable> { private static final long serialVersionUID = 1L; private final DefaultListModel<Fooable> model; /** * The Fooables contained in this JList */ private final List<Fooable> suggestions; /** * Create a JList containing a list of suggestions provided as 'results', * generated from the parent Foobar 'parent'. * * @param parent * The parent Foobar * @param results * The list of results displayed */ protected FoobarSuggestions(final Foobar parent, List<Fooable> results) { super(); // Store the list of suggestions this.suggestions = results; // Use the DefaultListModel this.model = new DefaultListModel<>(); this.setModel(this.model); // Allow a maximum of one option to be selected this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Execute any Fooable that is double-clicked this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) parent.executeFooable(); } }); // Populate the result list with up to 5 Fooables for (Fooable result : results.subList(0, results.size() > 5 ? 5 : results.size())) { this.model.addElement(result); } // Select the first option this.setSelectedIndex(0); // Adjust the size of the result list to fit all the Fooables this.setPreferredSize(new Dimension(parent.getParent().getWidth(), - results.size() * 17)); + (results.size() > 5 ? 5 : results.size()) * 17)); this.setVisible(true); } /** * Get a list of the Fooables contained in this object. * * @return The list of the Fooables contained in this object */ protected List<Fooable> getFooables() { return this.suggestions; } /** * Select the previous indexed item in the list, If there are no more items * in the list, make a beep sound. */ protected void setSelectedIndexPrevious() { if (this.getSelectedIndex() > 0) { this.setSelectedIndex(this.getSelectedIndex() - 1); } else { Toolkit.getDefaultToolkit().beep(); } } /** * Select the next indexed item in the list. If there are no more items in * the list, make a beep sound. */ protected void setSelectedIndexNext() { if (this.getSelectedIndex() < this.getLastVisibleIndex()) { this.setSelectedIndex(this.getSelectedIndex() + 1); } else { Toolkit.getDefaultToolkit().beep(); } } }
true
true
protected FoobarSuggestions(final Foobar parent, List<Fooable> results) { super(); // Store the list of suggestions this.suggestions = results; // Use the DefaultListModel this.model = new DefaultListModel<>(); this.setModel(this.model); // Allow a maximum of one option to be selected this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Execute any Fooable that is double-clicked this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) parent.executeFooable(); } }); // Populate the result list with up to 5 Fooables for (Fooable result : results.subList(0, results.size() > 5 ? 5 : results.size())) { this.model.addElement(result); } // Select the first option this.setSelectedIndex(0); // Adjust the size of the result list to fit all the Fooables this.setPreferredSize(new Dimension(parent.getParent().getWidth(), results.size() * 17)); this.setVisible(true); }
protected FoobarSuggestions(final Foobar parent, List<Fooable> results) { super(); // Store the list of suggestions this.suggestions = results; // Use the DefaultListModel this.model = new DefaultListModel<>(); this.setModel(this.model); // Allow a maximum of one option to be selected this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Execute any Fooable that is double-clicked this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) parent.executeFooable(); } }); // Populate the result list with up to 5 Fooables for (Fooable result : results.subList(0, results.size() > 5 ? 5 : results.size())) { this.model.addElement(result); } // Select the first option this.setSelectedIndex(0); // Adjust the size of the result list to fit all the Fooables this.setPreferredSize(new Dimension(parent.getParent().getWidth(), (results.size() > 5 ? 5 : results.size()) * 17)); this.setVisible(true); }
diff --git a/opentaps/financials/src/com/opensourcestrategies/financials/financials/FinancialServices.java b/opentaps/financials/src/com/opensourcestrategies/financials/financials/FinancialServices.java index 6565574b1..05549e286 100644 --- a/opentaps/financials/src/com/opensourcestrategies/financials/financials/FinancialServices.java +++ b/opentaps/financials/src/com/opensourcestrategies/financials/financials/FinancialServices.java @@ -1,1817 +1,1817 @@ /* * Copyright (c) 2006 - 2009 Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package com.opensourcestrategies.financials.financials; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import com.opensourcestrategies.financials.util.UtilFinancial; import javolution.util.FastList; import javolution.util.FastMap; import org.ofbiz.accounting.AccountingException; import org.ofbiz.accounting.util.UtilAccounting; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilDateTime; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilNumber; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceUtil; import org.opentaps.base.constants.GlAccountTypeConstants; import org.opentaps.base.services.FindLastClosedDateService; import org.opentaps.base.services.GetBalanceSheetForDateService; import org.opentaps.base.services.GetIncomeStatementByDatesService; import org.opentaps.common.util.UtilAccountingTags; import org.opentaps.common.util.UtilCommon; import org.opentaps.common.util.UtilMessage; import org.opentaps.domain.DomainsDirectory; import org.opentaps.domain.DomainsLoader; import org.opentaps.domain.ledger.GeneralLedgerAccount; import org.opentaps.domain.ledger.LedgerRepositoryInterface; import org.opentaps.domain.organization.Organization; import org.opentaps.domain.organization.OrganizationDomainInterface; import org.opentaps.domain.organization.OrganizationRepositoryInterface; import org.opentaps.financials.domain.ledger.LedgerRepository; import org.opentaps.foundation.entity.EntityNotFoundException; import org.opentaps.foundation.infrastructure.Infrastructure; import org.opentaps.foundation.infrastructure.User; import org.opentaps.foundation.repository.RepositoryException; /** * FinancialServices - Services for generating financial reports and statements. * * @author <a href="mailto:[email protected]">Si Chen</a> * @version $Rev$ * @since 2.2 */ public final class FinancialServices { private FinancialServices() { } private static String MODULE = FinancialServices.class.getName(); public static int decimals = UtilNumber.getBigDecimalScale("fin_arithmetic.properties", "financial.statements.decimals"); public static int rounding = UtilNumber.getBigDecimalRoundingMode("fin_arithmetic.properties", "financial.statements.rounding"); public static final BigDecimal ZERO = BigDecimal.ZERO.setScale(decimals, rounding); /** Default toplevel income statement glAccountTypeIds to group by. */ public static final List<String> INCOME_STATEMENT_TYPES = Arrays.asList("REVENUE", "COGS", "OPERATING_EXPENSE", "OTHER_EXPENSE", "OTHER_INCOME", "TAX_EXPENSE"); /** The types that are expenses. */ public static final List<String> EXPENSES_TYPES = Arrays.asList("COGS", "OPERATING_EXPENSE", "OTHER_EXPENSE", "TAX_EXPENSE"); /** Account classes to search when generating the income statement. */ public static final List<String> INCOME_STATEMENT_CLASSES = Arrays.asList("REVENUE", "EXPENSE", "INCOME"); /** A type to group all accounts without glAccountTypeId for income statement. */ public static final String UNCLASSIFIED_TYPE = "UNCLASSIFIED"; /** * Generates an income statement over two CustomTimePeriod entries, returning a Map of GlAccount and amounts and a double. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getIncomeStatementByTimePeriods(DispatchContext dctx, Map context) { return reportServiceTimePeriodHelper(dctx, context, "getIncomeStatementByDates"); } /** * Generates an income statement over a range of dates, returning a Map of GlAccount and amounts and a netIncome. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getIncomeStatementByDates(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Timestamp fromDate = (Timestamp) context.get("fromDate"); Timestamp thruDate = (Timestamp) context.get("thruDate"); String organizationPartyId = (String) context.get("organizationPartyId"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); // glFiscalTypeId defaults to ACTUAL if (UtilValidate.isEmpty(glFiscalTypeId)) { glFiscalTypeId = "ACTUAL"; context.put("glFiscalTypeId", glFiscalTypeId); } try { // get a Map of glAccount -> sums for all income statement accounts for this time period Map input = dctx.getModelService("getIncomeStatementAccountSumsByDate").makeValid(context, ModelService.IN_PARAM); Map tmpResult = dispatcher.runSync("getIncomeStatementAccountSumsByDate", input); if (tmpResult.get("glAccountSums") == null) { return ServiceUtil.returnError("Cannot sum up account balances properly for income statement"); } Map<GenericValue, BigDecimal> glAccountSums = (HashMap) tmpResult.get("glAccountSums"); Map<String, String> glAccountTypeTree = FastMap.newInstance(); Map<String, List<Map>> glAccountSumsGrouped = FastMap.newInstance(); Map<String, BigDecimal> glAccountGroupSums = FastMap.newInstance(); Map<String, BigDecimal> sums = FastMap.newInstance(); prepareIncomeStatementMaps(glAccountTypeTree, glAccountSumsGrouped, glAccountGroupSums, sums, delegator); // sort them into the correct map while also keeping a running total of the aggregations we're interested in (net income, gross profit, etc.) for (GenericValue account : glAccountSums.keySet()) { calculateIncomeStatementMaps(glAccountTypeTree, glAccountSumsGrouped, glAccountGroupSums, sums, account, glAccountSums.get(account), delegator); } return makeIncomeStatementResults(glAccountSums, glAccountSumsGrouped, glAccountGroupSums, sums, organizationPartyId, fromDate, thruDate, delegator); } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Calculates net income (of ACTUAL gl fiscal type) since last closed accounting period or, if none exists, since earliest accounting period. * Optionally use periodTypeId to get figure since last closed date of a period type. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getActualNetIncomeSinceLastClosing(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); String organizationPartyId = (String) context.get("organizationPartyId"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String periodTypeId = (String) context.get("periodTypeId"); Timestamp fromDate = null; try { // try to get the ending date of the most recent accounting time period which has been closed Map tmpResult = dispatcher.runSync("findLastClosedDate", UtilMisc.toMap("organizationPartyId", organizationPartyId, "periodTypeId", periodTypeId, "userLogin", userLogin)); if ((tmpResult != null) && (tmpResult.get("lastClosedDate") != null)) { fromDate = (Timestamp) tmpResult.get("lastClosedDate"); } else { return ServiceUtil.returnError("Cannot get a starting date for net income"); } // add calculated parameters Map input = new HashMap(context); input.putAll(UtilMisc.toMap("glFiscalTypeId", "ACTUAL", "fromDate", fromDate)); input = dctx.getModelService("getIncomeStatementByDates").makeValid(input, ModelService.IN_PARAM); tmpResult = dispatcher.runSync("getIncomeStatementByDates", input); if (!UtilCommon.isSuccess(tmpResult)) { return tmpResult; // probably an error message - pass it back up } else if (tmpResult.get("netIncome") == null) { return ServiceUtil.returnError("Cannot calculate a net income"); // no error message, no net income either? } else { // return net income and profit&loss gl account Map result = ServiceUtil.returnSuccess(); result.put("netIncome", tmpResult.get("netIncome")); result.put("retainedEarningsGlAccount", tmpResult.get("retainedEarningsGlAccount")); result.put("glAccountSumsFlat", tmpResult.get("glAccountSumsFlat")); return result; } } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Generates balance sheet for a time period and returns separate maps for balances of asset, liability, and equity accounts. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getBalanceSheetForTimePeriod(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); String organizationPartyId = (String) context.get("organizationPartyId"); String customTimePeriodId = (String) context.get("customTimePeriodId"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); // default to generating "ACTUAL" balance sheets if (UtilValidate.isEmpty(glFiscalTypeId)) { glFiscalTypeId = "ACTUAL"; context.put("glFiscalTypeId", glFiscalTypeId); } try { // get the current time period and first use it to assume whether this period has been closed or not GenericValue currentTimePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", customTimePeriodId)); boolean isClosed = false; boolean accountingTagsUsed = UtilAccountingTags.areTagsSet(context); if (currentTimePeriod.getString("isClosed").equals("Y")) { isClosed = true; if (accountingTagsUsed) { Debug.logWarning("getBalanceSheetForTimePeriod found a closed time period but we have accounting tag, considering the time period as NOT closed", MODULE); isClosed = false; } } if (("ACTUAL".equals(glFiscalTypeId)) && (isClosed)) { // if the time period is closed and we're doing ACTUAL balance sheet, then we can use the posted GlAccountHistory // first, find all the gl accounts' GlAccountHistory record for this time period EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("organizationPartyId", EntityOperator.EQUALS, organizationPartyId), EntityCondition.makeCondition("customTimePeriodId", EntityOperator.EQUALS, customTimePeriodId), EntityCondition.makeCondition(EntityOperator.OR, UtilFinancial.getAssetExpr(delegator), UtilFinancial.getLiabilityExpr(delegator), UtilFinancial.getEquityExpr(delegator))); List selectedFields = UtilMisc.toList("glAccountId", "glAccountTypeId", "glAccountClassId", "accountName", "postedDebits", "postedCredits"); selectedFields.add("endingBalance"); List<GenericValue> accounts = delegator.findByCondition("GlAccountAndHistory", conditions, selectedFields, UtilMisc.toList("glAccountId")); // now, create the separate account balance Maps and see if this period has been closed. // if the period has been closed, then just get the accounts' balances from the endingBalance // otherwise, get it by calculating the net of posted debits and credits Map<GenericValue, BigDecimal> assetAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountBalances = new HashMap<GenericValue, BigDecimal>(); for (Iterator<GenericValue> ai = accounts.iterator(); ai.hasNext();) { GenericValue account = ai.next(); BigDecimal balance = BigDecimal.ZERO; if (account.get("endingBalance") != null) { balance = account.getBigDecimal("endingBalance"); } // classify and put into the appropriate Map if (UtilAccounting.isAssetAccount(account)) { assetAccountBalances.put(account.getRelatedOne("GlAccount"), balance); } else if (UtilAccounting.isLiabilityAccount(account)) { liabilityAccountBalances.put(account.getRelatedOne("GlAccount"), balance); } else if (UtilAccounting.isEquityAccount(account)) { equityAccountBalances.put(account.getRelatedOne("GlAccount"), balance); } } Map result = ServiceUtil.returnSuccess(); result.put("assetAccountBalances", assetAccountBalances); result.put("liabilityAccountBalances", liabilityAccountBalances); result.put("equityAccountBalances", equityAccountBalances); result.put("isClosed", new Boolean(isClosed)); return result; } else { Map params = dctx.getModelService("getBalanceSheetForDate").makeValid(context, ModelService.IN_PARAM); params.put("asOfDate", UtilDateTime.toTimestamp(currentTimePeriod.getDate("thruDate"))); return dispatcher.runSync("getBalanceSheetForDate", params); } } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Generates the trial balance for a time period and returns separate maps for balances of asset, liability, equity, revenue, expense, income and other accounts. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getTrialBalanceForDate(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); String organizationPartyId = (String) context.get("organizationPartyId"); Timestamp asOfDate = (Timestamp) context.get("asOfDate"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); Map tags = UtilAccountingTags.getTagParameters(context); // default to generating "ACTUAL" balance sheets if (UtilValidate.isEmpty(glFiscalTypeId)) { glFiscalTypeId = "ACTUAL"; context.put("glFiscalTypeId", glFiscalTypeId); } User user = new User(userLogin); Infrastructure infrastructure = new Infrastructure(dispatcher); DomainsLoader dl = new DomainsLoader(infrastructure, user); try { LedgerRepositoryInterface ledgerRepository = dl.loadDomainsDirectory().getLedgerDomain().getLedgerRepository(); // for totals of balances, debits and credits Map<GenericValue, BigDecimal> accountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> accountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> accountCredits = new HashMap<GenericValue, BigDecimal>(); // per account type Map<GenericValue, BigDecimal> assetAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> assetAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> assetAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountCredits = new HashMap<GenericValue, BigDecimal>(); // try to get the ending date of the most recent accounting time period which has been closed Timestamp lastClosedDate = UtilDateTime.toTimestamp(1, 1, 1970, 0, 0, 0); // default if there never has been a period closing FindLastClosedDateService findLastClosedDate = new FindLastClosedDateService(); findLastClosedDate.setInOrganizationPartyId(organizationPartyId); // this is in case the current time period is already closed, and you try to run a report at the end of the time period // adjust as of date forward 1 second, so if report date is 12/31/XX at 23:59:59.999, but CustomTimePeriod ends at 1/1/XX+1 00:00:00 and the CustomTimePeriod has been // closed, it will get the CustomTimePeriod as the last closed period. Otherwise, it will get the previous time period and add everything again. // but don't change the actual as of date because it may cause inconsistencies with other reports // does not appear to be an issue for balance sheet, income statement, because if it is missed you just re-calculate that time period again // but this report actually adds both, so if you miss a closed time period, it could cause double-counting - findLastClosedDate.setInFindDate(UtilDateTime.adjustTimestamp(asOfDate, java.util.Calendar.SECOND, new Integer(1))); + findLastClosedDate.setInFindDate(new java.sql.Date(UtilDateTime.adjustTimestamp(asOfDate, java.util.Calendar.SECOND, new Integer(1)).getTime())); findLastClosedDate.setUser(user); findLastClosedDate.runSyncNoNewTransaction(infrastructure); // these are null unless there has been a closed time period before this BigDecimal netIncomeSinceLastClosing = null; GeneralLedgerAccount retainedEarningsGlAccount = ledgerRepository.getDefaultLedgerAccount(GlAccountTypeConstants.RETAINED_EARNINGS, organizationPartyId);; GeneralLedgerAccount profitLossGlAccount = ledgerRepository.getDefaultLedgerAccount(GlAccountTypeConstants.PROFIT_LOSS_ACCOUNT, organizationPartyId); // balance sheet account balances as of the previous closed time period, null if there has been no previous closed time periods Map balanceSheetAccountBalances = null; // if there has been a previous period closing, then we need both the income statement and balance sheet since the last closing if (findLastClosedDate.getOutLastClosedDate() != null) { lastClosedDate = findLastClosedDate.getOutLastClosedDate(); GetIncomeStatementByDatesService getIncomeStatement = new GetIncomeStatementByDatesService(); getIncomeStatement.setInFromDate(lastClosedDate); getIncomeStatement.setInThruDate(asOfDate); getIncomeStatement.setInOrganizationPartyId(organizationPartyId); getIncomeStatement.setInGlFiscalTypeId(glFiscalTypeId); getIncomeStatement.setInTag1((String) tags.get("tag1")); getIncomeStatement.setInTag2((String) tags.get("tag2")); getIncomeStatement.setInTag3((String) tags.get("tag3")); getIncomeStatement.setInTag4((String) tags.get("tag4")); getIncomeStatement.setInTag5((String) tags.get("tag5")); getIncomeStatement.setInTag6((String) tags.get("tag6")); getIncomeStatement.setInTag7((String) tags.get("tag7")); getIncomeStatement.setInTag8((String) tags.get("tag8")); getIncomeStatement.setInTag9((String) tags.get("tag9")); getIncomeStatement.setInTag10((String) tags.get("tag10")); getIncomeStatement.setUser(user); getIncomeStatement.runSyncNoNewTransaction(infrastructure); netIncomeSinceLastClosing = getIncomeStatement.getOutNetIncome(); GetBalanceSheetForDateService getBalanceSheet = new GetBalanceSheetForDateService(); getBalanceSheet.setInAsOfDate(lastClosedDate); getBalanceSheet.setInGlFiscalTypeId(glFiscalTypeId); getBalanceSheet.setInOrganizationPartyId(organizationPartyId); getBalanceSheet.setInTag1((String) tags.get("tag1")); getBalanceSheet.setInTag2((String) tags.get("tag2")); getBalanceSheet.setInTag3((String) tags.get("tag3")); getBalanceSheet.setInTag4((String) tags.get("tag4")); getBalanceSheet.setInTag5((String) tags.get("tag5")); getBalanceSheet.setInTag6((String) tags.get("tag6")); getBalanceSheet.setInTag7((String) tags.get("tag7")); getBalanceSheet.setInTag8((String) tags.get("tag8")); getBalanceSheet.setInTag9((String) tags.get("tag9")); getBalanceSheet.setInTag10((String) tags.get("tag10")); getBalanceSheet.setUser(user); getBalanceSheet.runSyncNoNewTransaction(infrastructure); balanceSheetAccountBalances = getBalanceSheet.getOutAssetAccountBalances(); balanceSheetAccountBalances.putAll(getBalanceSheet.getOutLiabilityAccountBalances()); balanceSheetAccountBalances.putAll(getBalanceSheet.getOutEquityAccountBalances()); } Debug.logInfo("Last closed date is [" + lastClosedDate + "] net income [" + netIncomeSinceLastClosing + "] profit loss account is [" + profitLossGlAccount.getGlAccountId() + "] and retained earnings account [" + retainedEarningsGlAccount.getGlAccountId() + "]", MODULE); // a little bit of a hack, using this method with a "null" for GL account class causes it to return the sum of the transaction entries for all the GL accounts accountBalances = getAcctgTransAndEntriesForClassWithDetails(accountBalances, accountDebits, accountCredits, organizationPartyId, lastClosedDate, asOfDate, glFiscalTypeId, null, tags, userLogin, dispatcher); // if there are balance sheet balances from the last closed time period, then add them to the account balances we just got, thus merging the last closed balance sheet with the trial balance since then if (balanceSheetAccountBalances != null) { Set<GenericValue> balanceSheetGlAccounts = balanceSheetAccountBalances.keySet(); for (GenericValue glAccount: balanceSheetGlAccounts) { UtilCommon.addInMapOfBigDecimal(accountBalances, glAccount, (BigDecimal) balanceSheetAccountBalances.get(glAccount)); } } // now we sort them out into separate sections for assets, liabilities, equities, revenue, expense, income // this is also where we add the net income since last time period closing to the retained earnings and profit loss accounts Set<GenericValue> glAccounts = accountBalances.keySet(); BigDecimal netBalance = BigDecimal.ZERO; // net of debit minus credit BigDecimal totalDebits = BigDecimal.ZERO; BigDecimal totalCredits = BigDecimal.ZERO; // we need to track if this has been done, and if not do it later manually boolean addedNetIncomeSinceLastClosingToRetainedEarnings = false; boolean addedNetIncomeSinceLastCLosingToProfitLoss = false; for (GenericValue glAccount : glAccounts) { BigDecimal balance = accountBalances.get(glAccount); String glAccountId = glAccount.getString("glAccountId"); // add net income since last closing to the retained earnings and profit loss accounts if (netIncomeSinceLastClosing != null) { if (glAccountId.equals(retainedEarningsGlAccount.getGlAccountId())) { balance = balance.add(netIncomeSinceLastClosing).setScale(decimals, rounding); addedNetIncomeSinceLastClosingToRetainedEarnings = true; Debug.logInfo("Adding retained earnings of [" + netIncomeSinceLastClosing + "] to GL account ["+ glAccountId + "] balance is now [" + balance + "]", MODULE); } if (glAccountId.equals(profitLossGlAccount.getGlAccountId())) { balance = balance.add(netIncomeSinceLastClosing).setScale(decimals, rounding); addedNetIncomeSinceLastCLosingToProfitLoss = true; Debug.logInfo("Adding retained earnings of [" + netIncomeSinceLastClosing + "] to GL account ["+ glAccountId + "] balance is now [" + balance + "]", MODULE); } } // add to net balance and total debits and total credits if (balance != null) { if (UtilAccounting.isDebitAccount(glAccount)) { totalDebits = totalDebits.add(balance); netBalance = netBalance.add(balance); } else { totalCredits = totalCredits.add(balance); netBalance = netBalance.subtract(balance); } } if (UtilAccounting.isAssetAccount(glAccount)) { assetAccountBalances.put(glAccount, balance); assetAccountDebits.put(glAccount, balance); } else if (UtilAccounting.isLiabilityAccount(glAccount)) { liabilityAccountBalances.put(glAccount, balance); liabilityAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isEquityAccount(glAccount)) { equityAccountBalances.put(glAccount, balance); equityAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isRevenueAccount(glAccount)) { revenueAccountBalances.put(glAccount, balance); revenueAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isExpenseAccount(glAccount)) { expenseAccountBalances.put(glAccount, balance); expenseAccountDebits.put(glAccount, balance); } else if (UtilAccounting.isIncomeAccount(glAccount)) { incomeAccountBalances.put(glAccount, balance); incomeAccountCredits.put(glAccount, balance); } else { Debug.logWarning("Classification of GL account [" + glAccount.getString("glAccountId") + "] is unknown, putting balance [" + balance + "] under debit", MODULE); otherAccountBalances.put(glAccount, balance); otherAccountDebits.put(glAccount, balance); } } // now manually put in the retained earnings if that was not done already // this assume that since there was no retained earnings from before, it should be zero if ((lastClosedDate != null) && !addedNetIncomeSinceLastClosingToRetainedEarnings) { equityAccountBalances.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); equityAccountDebits.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); equityAccountCredits.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); totalCredits = totalCredits.add(netIncomeSinceLastClosing); netBalance = netBalance.subtract(netIncomeSinceLastClosing); Debug.logInfo("Did not find retained earnings account, so put [" + netIncomeSinceLastClosing + "] for [" + retainedEarningsGlAccount.getGlAccountId() + "]", MODULE); } // do the same for profit loss. this should be OK -- an offsetting amount should've been added to retained earnings or put there right above if ((lastClosedDate != null) && !addedNetIncomeSinceLastCLosingToProfitLoss) { incomeAccountBalances.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); incomeAccountDebits.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); incomeAccountCredits.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); totalDebits = totalDebits.add(netIncomeSinceLastClosing); netBalance = netBalance.add(netIncomeSinceLastClosing); Debug.logInfo("Did not find profit loss account, so put [" + netIncomeSinceLastClosing + "] for [" + profitLossGlAccount.getGlAccountId() + "]", MODULE); } // calculate net income from the last closed date // add it to the retained earnings account and profit and loss account Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("assetAccountBalances", assetAccountBalances); results.put("liabilityAccountBalances", liabilityAccountBalances); results.put("equityAccountBalances", equityAccountBalances); results.put("revenueAccountBalances", revenueAccountBalances); results.put("expenseAccountBalances", expenseAccountBalances); results.put("incomeAccountBalances", incomeAccountBalances); results.put("otherAccountBalances", otherAccountBalances); results.put("assetAccountCredits", assetAccountCredits); results.put("liabilityAccountCredits", liabilityAccountCredits); results.put("equityAccountCredits", equityAccountCredits); results.put("revenueAccountCredits", revenueAccountCredits); results.put("expenseAccountCredits", expenseAccountCredits); results.put("incomeAccountCredits", incomeAccountCredits); results.put("otherAccountCredits", otherAccountCredits); results.put("assetAccountDebits", assetAccountDebits); results.put("liabilityAccountDebits", liabilityAccountDebits); results.put("equityAccountDebits", equityAccountDebits); results.put("revenueAccountDebits", revenueAccountDebits); results.put("expenseAccountDebits", expenseAccountDebits); results.put("incomeAccountDebits", incomeAccountDebits); results.put("otherAccountDebits", otherAccountDebits); results.put("totalBalances", netBalance); results.put("totalDebits", totalDebits); results.put("totalCredits", totalCredits); Debug.logInfo("getTrialBalanceForDate totals => balance = " + netBalance + ", credits = " + totalCredits + ", debits = " + totalDebits + ", calculated balance = " + totalCredits.subtract(totalDebits), MODULE); return results; } catch (GeneralException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Generates balance sheet as of a particular date, by working forward from the last closed time period, * or, if none, from the beginning of the earliest time period. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getBalanceSheetForDate(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); String organizationPartyId = (String) context.get("organizationPartyId"); Timestamp asOfDate = (Timestamp) context.get("asOfDate"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); // default to generating "ACTUAL" balance sheets if (UtilValidate.isEmpty(glFiscalTypeId)) { glFiscalTypeId = "ACTUAL"; context.put("glFiscalTypeId", glFiscalTypeId); } // balances of the asset, liability, and equity GL accounts, initially empty Map<GenericValue, BigDecimal> assetAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountBalances = new HashMap<GenericValue, BigDecimal>(); try { // figure the date and the last closed time period Timestamp lastClosedDate = null; GenericValue lastClosedTimePeriod = null; Map tmpResult; boolean accountingTagsUsed = UtilAccountingTags.areTagsSet(context); if (accountingTagsUsed) { Debug.logWarning("getBalanceSheetForDate is using accounting tags, not looking for closed time periods", MODULE); lastClosedTimePeriod = null; List<GenericValue> timePeriods = delegator.findByAnd("CustomTimePeriod", UtilMisc.toMap("organizationPartyId", organizationPartyId), UtilMisc.toList("fromDate ASC")); if ((timePeriods != null) && (timePeriods.size() > 0) && ((timePeriods.get(0)).get("fromDate") != null)) { lastClosedDate = UtilDateTime.toTimestamp((timePeriods.get(0)).getDate("fromDate")); } else { return ServiceUtil.returnError("Cannot get a starting date for net income"); } } else { // find the last closed time period tmpResult = dispatcher.runSync("findLastClosedDate", UtilMisc.toMap("organizationPartyId", organizationPartyId, "findDate", asOfDate, "userLogin", userLogin)); if ((tmpResult == null) || (tmpResult.get("lastClosedDate") == null)) { return ServiceUtil.returnError("Cannot get a closed time period before " + asOfDate); } else { lastClosedDate = (Timestamp) tmpResult.get("lastClosedDate"); } if (tmpResult.get("lastClosedTimePeriod") != null) { lastClosedTimePeriod = (GenericValue) tmpResult.get("lastClosedTimePeriod"); } } Debug.logVerbose("Last closed time period [" + lastClosedTimePeriod + "] and last closed date [" + lastClosedDate + "]", MODULE); // if there was a previously closed time period, then get a balance sheet as of the end of that time period. This balance sheet is our starting point // but this only works for ACTUAL fiscal types. For Budgets, Forecasts, etc., we should just aggregating transaction entries. if ("ACTUAL".equals(glFiscalTypeId) && lastClosedTimePeriod != null) { Map input = new HashMap(context); input.put("customTimePeriodId", lastClosedTimePeriod.getString("customTimePeriodId")); input = dctx.getModelService("getBalanceSheetForTimePeriod").makeValid(input, ModelService.IN_PARAM); tmpResult = dispatcher.runSync("getBalanceSheetForTimePeriod", input); if (tmpResult != null) { assetAccountBalances = (Map<GenericValue, BigDecimal>) tmpResult.get("assetAccountBalances"); liabilityAccountBalances = (Map<GenericValue, BigDecimal>) tmpResult.get("liabilityAccountBalances"); equityAccountBalances = (Map<GenericValue, BigDecimal>) tmpResult.get("equityAccountBalances"); } } // now add the new asset, liability, and equity transactions Map tags = UtilAccountingTags.getTagParameters(context); assetAccountBalances = getAcctgTransAndEntriesForClass(assetAccountBalances, organizationPartyId, lastClosedDate, asOfDate, glFiscalTypeId, "ASSET", tags, true, userLogin, dispatcher); liabilityAccountBalances = getAcctgTransAndEntriesForClass(liabilityAccountBalances, organizationPartyId, lastClosedDate, asOfDate, glFiscalTypeId, "LIABILITY", tags, true, userLogin, dispatcher); equityAccountBalances = getAcctgTransAndEntriesForClass(equityAccountBalances, organizationPartyId, lastClosedDate, asOfDate, glFiscalTypeId, "EQUITY", tags, true, userLogin, dispatcher); // calculate a net income since the last closed date and add it to our equity account balances Map input = new HashMap(context); input.put("fromDate", lastClosedDate); input.put("thruDate", asOfDate); input = dctx.getModelService("getIncomeStatementByDates").makeValid(input, ModelService.IN_PARAM); tmpResult = dispatcher.runSync("getIncomeStatementByDates", input); GenericValue retainedEarningsGlAccount = (GenericValue) tmpResult.get("retainedEarningsGlAccount"); BigDecimal interimNetIncome = (BigDecimal) tmpResult.get("netIncome"); // if any time periods had been closed, the retained earnings account may have a posted balance but for all accounting tags, which is // not appropriate from the accounting tags, so if accountings tags are used, then ignore any existing posted retained earnings balance // and just put the interim net income as retained earnings if (accountingTagsUsed) { equityAccountBalances.put(retainedEarningsGlAccount, interimNetIncome); } else { UtilCommon.addInMapOfBigDecimal(equityAccountBalances, retainedEarningsGlAccount, interimNetIncome); } // TODO: This is just copied over from getIncomeStatementByDates for now. We should implement a good version at some point. boolean isClosed = true; EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("organizationPartyId", EntityOperator.EQUALS, organizationPartyId), EntityCondition.makeCondition("isClosed", EntityOperator.NOT_EQUAL, "Y"), EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("fromDate", EntityOperator.GREATER_THAN_EQUAL_TO, lastClosedDate), EntityCondition.makeCondition("thruDate", EntityOperator.LESS_THAN_EQUAL_TO, asOfDate))); List timePeriods = delegator.findByCondition("CustomTimePeriod", conditions, UtilMisc.toList("customTimePeriodId"), UtilMisc.toList("customTimePeriodId")); if (timePeriods.size() > 0) { isClosed = false; } // all done Map result = ServiceUtil.returnSuccess(); result.put("assetAccountBalances", assetAccountBalances); result.put("liabilityAccountBalances", liabilityAccountBalances); result.put("equityAccountBalances", equityAccountBalances); result.put("isClosed", new Boolean(isClosed)); result.put("retainedEarningsGlAccount", retainedEarningsGlAccount); result.put("interimNetIncomeAmount", interimNetIncome); return result; } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Finds and returns a List of AcctgTransAndEntries based on organizationPartyId, fromDate, thruDate, fiscalTypeId, * subject to the glAccountClassIds in the glAccountClasses List. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getAcctgTransAndEntriesByType(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); Timestamp fromDate = (Timestamp) context.get("fromDate"); Timestamp thruDate = (Timestamp) context.get("thruDate"); String organizationPartyId = (String) context.get("organizationPartyId"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); List<String> glAccountClasses = (List) context.get("glAccountClasses"); // search for those in a set of glAccountClassId List<String> glAccountTypes = (List) context.get("glAccountTypes"); // search for those in a set of glAccountTypeId String productId = (String) context.get("productId"); String partyId = (String) context.get("partyId"); // this defaults to FINANCIALS_REPORTS_TAG (see the service definition) String accountingTagUsage = (String) context.get("accountingTagUsage"); List<String> ignoreAcctgTransTypeIds = (List<String>) context.get("ignoreAcctgTransTypeIds"); if (UtilValidate.isEmpty(glAccountClasses) && UtilValidate.isEmpty(glAccountTypes)) { return ServiceUtil.returnError("Please supply either a list of glAccountClassId or glAccountTypeId"); } try { // build a condition list of all the GlAccountClasses considered (this entity has parent/child tree structure) List<EntityCondition> glAccountClassesConsidered = new ArrayList(); if (glAccountClasses != null) { for (String glAccountClassId : glAccountClasses) { glAccountClassesConsidered.add(UtilFinancial.getGlAccountClassExpr(glAccountClassId, delegator)); } } // find all accounting transaction entries for this organizationPartyId and falling into this time period which are // of the specified types. Note we are only getting posted transactions here. This might change at some point. List searchConditions = UtilMisc.toList( EntityCondition.makeCondition("organizationPartyId", EntityOperator.EQUALS, organizationPartyId), EntityCondition.makeCondition("isPosted", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition("glFiscalTypeId", EntityOperator.EQUALS, glFiscalTypeId), EntityCondition.makeCondition("transactionDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate), EntityCondition.makeCondition("transactionDate", EntityOperator.LESS_THAN_EQUAL_TO, thruDate)); if (UtilValidate.isNotEmpty(glAccountClassesConsidered)) { searchConditions.add(EntityCondition.makeCondition(glAccountClassesConsidered, EntityOperator.OR)); } if (UtilValidate.isNotEmpty(glAccountTypes)) { searchConditions.add(EntityCondition.makeCondition("glAccountTypeId", EntityOperator.IN, glAccountTypes)); } if (UtilValidate.isNotEmpty(ignoreAcctgTransTypeIds)) { searchConditions.add(EntityCondition.makeCondition("acctgTransTypeId", EntityOperator.NOT_IN, ignoreAcctgTransTypeIds)); } if (UtilValidate.isNotEmpty(productId)) { searchConditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); } if (UtilValidate.isNotEmpty(partyId)) { searchConditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId)); } List<EntityCondition> tagConditions = UtilAccountingTags.buildTagConditions(organizationPartyId, accountingTagUsage, delegator, context); if (UtilValidate.isNotEmpty(tagConditions)) { searchConditions.addAll(tagConditions); } EntityCondition conditions = EntityCondition.makeCondition(searchConditions, EntityOperator.AND); List fieldsToGet = UtilMisc.toList("acctgTransId", "acctgTransTypeId", "acctgTransEntrySeqId", "glAccountId", "glAccountClassId", "amount"); fieldsToGet.add("glAccountTypeId"); fieldsToGet.add("debitCreditFlag"); fieldsToGet.add("productId"); fieldsToGet.add("partyId"); for (int i = 1; i <= UtilAccountingTags.TAG_COUNT; i++) { fieldsToGet.add(UtilAccountingTags.ENTITY_TAG_PREFIX + i); } List transactionEntries = delegator.findByCondition("AcctgTransAndEntries", conditions, fieldsToGet, // get these fields UtilMisc.toList("acctgTransId", "acctgTransEntrySeqId")); // order by these fields Map result = ServiceUtil.returnSuccess(); result.put("transactionEntries", transactionEntries); return result; } catch (GeneralException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Gets a Map of glAccount -> sum of transactions for all income statement accounts (REVENUE, EXPENSE, INCOME) over a period of dates for an organization. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getIncomeStatementAccountSumsByDate(DispatchContext dctx, Map context) { return getIncomeStatementAccountSumsCommon(dctx, context); } /** * Takes an initial <code>Map</code> of <code>GlAccount</code>, sums and a <code>List</code> of <code>AcctgTransAndEntries</code> and adds them to the Map, * based on debit/credit flag of transaction transactionEntry and whether the account is a debit or credit account. * Useful for doing income statement and intra-time-period updating of balance sheets, etc. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map addToAccountBalances(DispatchContext dctx, Map context) { Map<GenericValue, BigDecimal> glAccountSums = (Map<GenericValue, BigDecimal>) context.get("glAccountSums"); List<GenericValue> transactionEntries = (List<GenericValue>) context.get("transactionEntries"); try { UtilFinancial.sumBalancesByAccount(glAccountSums, transactionEntries); Map result = ServiceUtil.returnSuccess(); result.put("glAccountSums", glAccountSums); return result; } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Takes an <code>initial</code> Map of <code>GlAccount</code>, sums and a <code>List</code> of <code>AcctgTransAndEntries</code> and adds them to the Map, * based on debit/credit flag of transaction transactionEntry and whether the account is a debit or credit account. * Useful for doing income statement and intra-time-period updating of balance sheets, etc. * This is like {@link #addToAccountBalances} but returns three <code>Map</code> : <code>glAccountBalancesSums</code>, <code>glAccountDebitsSums</code> and <code>glAccountCreditsSums</code>. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map addToAccountBalancesWithDetails(DispatchContext dctx, Map context) { Map<GenericValue, BigDecimal> glAccountBalancesSums = (Map<GenericValue, BigDecimal>) context.get("glAccountBalancesSums"); Map<GenericValue, BigDecimal> glAccountDebitsSums = (Map<GenericValue, BigDecimal>) context.get("glAccountDebitsSums"); Map<GenericValue, BigDecimal> glAccountCreditsSums = (Map<GenericValue, BigDecimal>) context.get("glAccountCreditsSums"); List<GenericValue> transactionEntries = (List<GenericValue>) context.get("transactionEntries"); try { UtilFinancial.sumBalancesByAccountWithDetail(glAccountBalancesSums, glAccountDebitsSums, glAccountCreditsSums, transactionEntries); Map result = ServiceUtil.returnSuccess(); result.put("glAccountBalancesSums", glAccountBalancesSums); result.put("glAccountDebitsSums", glAccountDebitsSums); result.put("glAccountCreditsSums", glAccountCreditsSums); return result; } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Little method to help out getBalanceSheetForDate. Gets all AcctgTransAndEntries of a glAccountClassId and add them to the * original accountBalances Map, which is returned. * @param accountBalances * @param organizationPartyId * @param fromDate * @param thruDate * @param glFiscalTypeId * @param glAccountClassId * @param tags the <code>Map</code> of accounting tags * @param userLogin the user login <code>GenericValue</code> * @param dispatcher a <code>LocalDispatcher</code> value * @return */ @SuppressWarnings("unchecked") private static Map<GenericValue, BigDecimal> getAcctgTransAndEntriesForClass(Map<GenericValue, BigDecimal> accountBalances, String organizationPartyId, Timestamp fromDate, Timestamp thruDate, String glFiscalTypeId, String glAccountClassId, Map tags, GenericValue userLogin, LocalDispatcher dispatcher) { return getAcctgTransAndEntriesForClass(accountBalances, organizationPartyId, fromDate, thruDate, glFiscalTypeId, glAccountClassId, tags, false, userLogin, dispatcher); } /** * Little method to help out getBalanceSheetForDate. Gets all AcctgTransAndEntries of a glAccountClassId and add them to the * original accountBalances Map, which is returned. * @param accountBalances * @param organizationPartyId * @param fromDate * @param thruDate * @param glFiscalTypeId * @param glAccountClassId * @param tags the <code>Map</code> of accounting tags * @param ignoreClosingPeriodTransactions used for getBalanceSheetForDate so as the closing transaction is already accounted for * @param userLogin the user login <code>GenericValue</code> * @param dispatcher a <code>LocalDispatcher</code> value * @return */ @SuppressWarnings("unchecked") private static Map<GenericValue, BigDecimal> getAcctgTransAndEntriesForClass(Map<GenericValue, BigDecimal> accountBalances, String organizationPartyId, Timestamp fromDate, Timestamp thruDate, String glFiscalTypeId, String glAccountClassId, Map tags, boolean ignoreClosingPeriodTransactions, GenericValue userLogin, LocalDispatcher dispatcher) { try { // first get all the AcctgTransAndEntries of this glAccountClassId Map input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "fromDate", fromDate, "thruDate", thruDate, "glFiscalTypeId", glFiscalTypeId, "glAccountClasses", UtilMisc.toList(glAccountClassId), "userLogin", userLogin); if (ignoreClosingPeriodTransactions) { input.put("ignoreAcctgTransTypeIds", UtilMisc.toList("PERIOD_CLOSING")); } if (tags != null) { input.putAll(tags); } Map tmpResult = dispatcher.runSync("getAcctgTransAndEntriesByType", input); List<GenericValue> transactionEntries = (List<GenericValue>) tmpResult.get("transactionEntries"); // now add it to accountBalances tmpResult = dispatcher.runSync("addToAccountBalances", UtilMisc.toMap("glAccountSums", accountBalances, "transactionEntries", transactionEntries, "userLogin", userLogin)); accountBalances = (Map<GenericValue, BigDecimal>) tmpResult.get("glAccountSums"); return accountBalances; } catch (GenericServiceException ex) { Debug.logError(ex.getMessage(), MODULE); return null; } } /** * Little method to help out getBalanceSheetForDate. Gets all AcctgTransAndEntries of a glAccountClassId and add them to the * original accountBalances Map, which is returned. * @param accountBalances output Map of GLAccount to BigDecimal * @param accountDebits output Map of GLAccount to BigDecimal * @param accountCredits output Map of GLAccount to BigDecimal * @param organizationPartyId * @param fromDate * @param thruDate * @param glFiscalTypeId * @param glAccountClassId * @param tags the <code>Map</code> of accounting tags * @param userLogin the user login <code>GenericValue</code> * @param dispatcher a <code>LocalDispatcher</code> value * @return */ @SuppressWarnings("unchecked") private static Map<GenericValue, BigDecimal> getAcctgTransAndEntriesForClassWithDetails(Map<GenericValue, BigDecimal> accountBalances, Map<GenericValue, BigDecimal> accountDebits, Map<GenericValue, BigDecimal> accountCredits, String organizationPartyId, Timestamp fromDate, Timestamp thruDate, String glFiscalTypeId, String glAccountClassId, Map tags, GenericValue userLogin, LocalDispatcher dispatcher) { try { // first get all the AcctgTransAndEntries of this glAccountClassId Map input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "fromDate", fromDate, "thruDate", thruDate, "glFiscalTypeId", glFiscalTypeId, "glAccountClasses", UtilMisc.toList(glAccountClassId), "userLogin", userLogin); if (tags != null) { input.putAll(tags); } Map tmpResult = dispatcher.runSync("getAcctgTransAndEntriesByType", input); List<GenericValue> transactionEntries = (List<GenericValue>) tmpResult.get("transactionEntries"); // now add it to accountBalances tmpResult = dispatcher.runSync("addToAccountBalancesWithDetails", UtilMisc.toMap("glAccountBalancesSums", accountBalances, "glAccountDebitsSums", accountDebits, "glAccountCreditsSums", accountCredits, "transactionEntries", transactionEntries, "userLogin", userLogin)); accountBalances = (Map<GenericValue, BigDecimal>) tmpResult.get("glAccountBalancesSums"); accountDebits = (Map<GenericValue, BigDecimal>) tmpResult.get("glAccountDebitsSums"); accountCredits = (Map<GenericValue, BigDecimal>) tmpResult.get("glAccountCreditsSums"); return accountBalances; } catch (GenericServiceException ex) { Debug.logError(ex.getMessage(), MODULE); return null; } } /** * Generates balance sheet for two dates and determines the balance difference between the two. The balances are in BigDecimal. * The output includes the result of getBalanceSheetForDate for the fromDate and thruDate and glFiscalTypeId1 and glFiscalTypeId2. * * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getComparativeBalanceSheet(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = UtilCommon.getLocale(context); // input parameters String organizationPartyId = (String) context.get("organizationPartyId"); String glFiscalTypeId1 = (String) context.get("glFiscalTypeId1"); String glFiscalTypeId2 = (String) context.get("glFiscalTypeId2"); Timestamp fromDate = (Timestamp) context.get("fromDate"); Timestamp thruDate = (Timestamp) context.get("thruDate"); GenericValue userLogin = (GenericValue) context.get("userLogin"); try { // create the balance sheet for the fromDate Map input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "glFiscalTypeId", glFiscalTypeId1, "asOfDate", fromDate, "userLogin", userLogin); UtilAccountingTags.addTagParameters(context, input); Map fromDateResults = dispatcher.runSync("getBalanceSheetForDate", input); if (ServiceUtil.isError(fromDateResults)) { return UtilMessage.createAndLogServiceError(fromDateResults, "FinancialsError_CannotCreateComparativeBalanceSheet", locale, MODULE); } // create the balance sheet for the thruDate input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "glFiscalTypeId", glFiscalTypeId2, "asOfDate", thruDate, "userLogin", userLogin); UtilAccountingTags.addTagParameters(context, input); Map thruDateResults = dispatcher.runSync("getBalanceSheetForDate", input); if (ServiceUtil.isError(thruDateResults)) { return UtilMessage.createAndLogServiceError(thruDateResults, "FinancialsError_CannotCreateComparativeBalanceSheet", locale, MODULE); } Map results = ServiceUtil.returnSuccess(); // include the two balance sheets in the results results.put("fromDateAccountBalances", fromDateResults); results.put("thruDateAccountBalances", thruDateResults); // compute the balance difference for each type of account results.put("liabilityAccountBalances", calculateDifferenceBalance((Map) fromDateResults.get("liabilityAccountBalances"), (Map) thruDateResults.get("liabilityAccountBalances"))); results.put("assetAccountBalances", calculateDifferenceBalance((Map) fromDateResults.get("assetAccountBalances"), (Map) thruDateResults.get("assetAccountBalances"))); results.put("equityAccountBalances", calculateDifferenceBalance((Map) fromDateResults.get("equityAccountBalances"), (Map) thruDateResults.get("equityAccountBalances"))); return results; } catch (GenericServiceException e) { return UtilMessage.createAndLogServiceError(e, "FinancialsError_CannotCreateComparativeBalanceSheet", locale, MODULE); } } /** * Generates income statement for two sets of dates and glFiscalTypeIds and determines the difference between the two. The balances are in BigDecimal. * The output includes the result of getIncomeStatementByDates for the two sets of fromDates and thruDates. * * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getComparativeIncomeStatement(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = UtilCommon.getLocale(context); // input parameters String organizationPartyId = (String) context.get("organizationPartyId"); String glFiscalTypeId1 = (String) context.get("glFiscalTypeId1"); String glFiscalTypeId2 = (String) context.get("glFiscalTypeId2"); Timestamp fromDate1 = (Timestamp) context.get("fromDate1"); Timestamp thruDate1 = (Timestamp) context.get("thruDate1"); Timestamp fromDate2 = (Timestamp) context.get("fromDate2"); Timestamp thruDate2 = (Timestamp) context.get("thruDate2"); GenericValue userLogin = (GenericValue) context.get("userLogin"); // validate the from/thru dates if (fromDate1.after(thruDate1) || fromDate2.after(thruDate2)) { return UtilMessage.createAndLogServiceError("FinancialsError_CannotCreateComparativeIncomeStatementFromDateAfterThruDate", locale, MODULE); } try { // create the income statement for the fromDate Map input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "glFiscalTypeId", glFiscalTypeId1, "fromDate", fromDate1, "thruDate", thruDate1, "userLogin", userLogin); UtilAccountingTags.addTagParameters(context, input); Map set1Results = dispatcher.runSync("getIncomeStatementByDates", input); if (ServiceUtil.isError(set1Results)) { return UtilMessage.createAndLogServiceError(set1Results, "FinancialsError_CannotCreateComparativeIncomeStatement", locale, MODULE); } // create the balance sheet for the thruDate input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "glFiscalTypeId", glFiscalTypeId2, "fromDate", fromDate2, "thruDate", thruDate2, "userLogin", userLogin); UtilAccountingTags.addTagParameters(context, input); Map set2Results = dispatcher.runSync("getIncomeStatementByDates", input); if (ServiceUtil.isError(set2Results)) { return UtilMessage.createAndLogServiceError(set2Results, "FinancialsError_CannotCreateComparativeIncomeStatement", locale, MODULE); } Map results = ServiceUtil.returnSuccess(); // include the two income statements in the results results.put("set1IncomeStatement", set1Results); results.put("set2IncomeStatement", set2Results); // compute the balance difference results.put("accountBalances", calculateDifferenceBalance((Map) set1Results.get("glAccountSumsFlat"), (Map) set2Results.get("glAccountSumsFlat"))); return results; } catch (GenericServiceException e) { return UtilMessage.createAndLogServiceError(e, "FinancialsError_CannotCreateComparativeIncomeStatement", locale, MODULE); } } /** * Generates cash flow statement for two sets of dates and glFiscalTypeIds and determines the difference between the two. The balances are in BigDecimal. * The output includes the result of getCashFlowStatementForDates for the two sets of fromDates and thruDates. * * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getComparativeCashFlowStatement(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = UtilCommon.getLocale(context); // input parameters String organizationPartyId = (String) context.get("organizationPartyId"); String glFiscalTypeId1 = (String) context.get("glFiscalTypeId1"); String glFiscalTypeId2 = (String) context.get("glFiscalTypeId2"); Timestamp fromDate1 = (Timestamp) context.get("fromDate1"); Timestamp thruDate1 = (Timestamp) context.get("thruDate1"); Timestamp fromDate2 = (Timestamp) context.get("fromDate2"); Timestamp thruDate2 = (Timestamp) context.get("thruDate2"); GenericValue userLogin = (GenericValue) context.get("userLogin"); // validate the from/thru dates if (fromDate1.after(thruDate1) || fromDate2.after(thruDate2)) { return UtilMessage.createAndLogServiceError("FinancialsError_CannotCreateComparativeCashFlowStatementFromDateAfterThruDate", locale, MODULE); } try { // create the cash flow statement for the fromDate Map input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "glFiscalTypeId", glFiscalTypeId1, "fromDate", fromDate1, "thruDate", thruDate1, "userLogin", userLogin); UtilAccountingTags.addTagParameters(context, input); Map set1Results = dispatcher.runSync("getCashFlowStatementForDates", input); if (ServiceUtil.isError(set1Results)) { return UtilMessage.createAndLogServiceError(set1Results, "FinancialsError_CannotCreateComparativeCashFlowStatement", locale, MODULE); } // create the balance sheet for the thruDate input = UtilMisc.toMap("organizationPartyId", organizationPartyId, "glFiscalTypeId", glFiscalTypeId2, "fromDate", fromDate2, "thruDate", thruDate2, "userLogin", userLogin); UtilAccountingTags.addTagParameters(context, input); Map set2Results = dispatcher.runSync("getCashFlowStatementForDates", input); if (ServiceUtil.isError(set2Results)) { return UtilMessage.createAndLogServiceError(set2Results, "FinancialsError_CannotCreateComparativeCashFlowStatement", locale, MODULE); } Map results = ServiceUtil.returnSuccess(); // include the two income statements in the results results.put("set1CashFlowStatement", set1Results); results.put("set2CashFlowStatement", set2Results); // compute the balance difference results.put("beginningCashAccountBalances", calculateDifferenceBalance((Map) set1Results.get("beginningCashAccountBalances"), (Map) set2Results.get("beginningCashAccountBalances"))); results.put("endingCashAccountBalances", calculateDifferenceBalance((Map) set1Results.get("endingCashAccountBalances"), (Map) set2Results.get("endingCashAccountBalances"))); results.put("operatingCashFlowAccountBalances", calculateDifferenceBalance((Map) set1Results.get("operatingCashFlowAccountBalances"), (Map) set2Results.get("operatingCashFlowAccountBalances"))); results.put("investingCashFlowAccountBalances", calculateDifferenceBalance((Map) set1Results.get("investingCashFlowAccountBalances"), (Map) set2Results.get("investingCashFlowAccountBalances"))); results.put("financingCashFlowAccountBalances", calculateDifferenceBalance((Map) set1Results.get("financingCashFlowAccountBalances"), (Map) set2Results.get("financingCashFlowAccountBalances"))); return results; } catch (GenericServiceException e) { return UtilMessage.createAndLogServiceError(e, "FinancialsError_CannotCreateComparativeCashFlowStatement", locale, MODULE); } } /** * Calculates the difference between the two balances for the input maps of {account, fromDateBalance} and {account, thruDateBalance}. * @param fromDateMap a <code>Map</code> value * @param thruDateMap a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") private static Map<GenericValue, BigDecimal> calculateDifferenceBalance(Map fromDateMap, Map thruDateMap) { Map<GenericValue, BigDecimal> resultMap = FastMap.newInstance(); // first iterate through the thru date accounts for (Iterator iter = thruDateMap.keySet().iterator(); iter.hasNext();) { GenericValue account = (GenericValue) iter.next(); BigDecimal thruDateBalance; if (thruDateMap.get(account) != null && thruDateMap.get(account) instanceof Double) { thruDateBalance = BigDecimal.valueOf((Double) thruDateMap.get(account)); } else if (thruDateMap.get(account) != null && thruDateMap.get(account) instanceof BigDecimal) { thruDateBalance = (BigDecimal) thruDateMap.get(account); } else { thruDateBalance = BigDecimal.ZERO; } BigDecimal fromDateBalance; if (fromDateMap.get(account) != null && fromDateMap.get(account) instanceof Double) { fromDateBalance = BigDecimal.valueOf((Double) fromDateMap.get(account)); } else if (fromDateMap.get(account) != null && fromDateMap.get(account) instanceof BigDecimal) { fromDateBalance = (BigDecimal) fromDateMap.get(account); } else { fromDateBalance = BigDecimal.ZERO; } BigDecimal difference = thruDateBalance.subtract(fromDateBalance); resultMap.put(account, difference.setScale(decimals, rounding)); } // iterate through the from date accounts that were missed because no thru date account exists for (Iterator iter = fromDateMap.keySet().iterator(); iter.hasNext();) { GenericValue account = (GenericValue) iter.next(); if (resultMap.get(account) != null) { continue; // already have a balance } BigDecimal fromDateBalance; if (fromDateMap.get(account) != null && fromDateMap.get(account) instanceof Double) { fromDateBalance = BigDecimal.valueOf((Double) fromDateMap.get(account)); } else if (fromDateMap.get(account) != null && fromDateMap.get(account) instanceof BigDecimal) { fromDateBalance = (BigDecimal) fromDateMap.get(account); } else { fromDateBalance = BigDecimal.ZERO; } if (fromDateBalance == null) { fromDateBalance = BigDecimal.ZERO; } BigDecimal difference = fromDateBalance.negate(); resultMap.put(account, difference.setScale(decimals, rounding)); } return resultMap; } /** * Helper method to transform input from and thru time periods to fromDate and thruDates. It will then call * the given service with the given input map and handle service/entity exceptions. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @param serviceName a <code>String</code> value * @param input a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") private static Map reportServiceTimePeriodHelper(DispatchContext dctx, Map context, String serviceName) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); String fromTimePeriodId = (String) context.get("fromTimePeriodId"); String thruTimePeriodId = (String) context.get("thruTimePeriodId"); String organizationPartyId = (String) context.get("organizationPartyId"); try { // get the right start and ending custom time periods GenericValue fromTimePeriod = delegator.findByPrimaryKey("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", fromTimePeriodId)); GenericValue thruTimePeriod = delegator.findByPrimaryKey("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", thruTimePeriodId)); // make sure these time periods belong to the organization and the from and thru dates are there if (fromTimePeriod == null) { return ServiceUtil.returnError("Custom time period " + fromTimePeriodId + " does not exist"); } if (thruTimePeriod == null) { return ServiceUtil.returnError("Custom time period " + thruTimePeriodId + " does not exist"); } if (!(fromTimePeriod.getString("organizationPartyId").equals(organizationPartyId))) { return ServiceUtil.returnError("Custom time period " + fromTimePeriodId + " does not belong to " + organizationPartyId); } if (!(thruTimePeriod.getString("organizationPartyId").equals(organizationPartyId))) { return ServiceUtil.returnError("Custom time period " + thruTimePeriodId + " does not belong to " + organizationPartyId); } if (fromTimePeriod.get("fromDate") == null) { return ServiceUtil.returnError("Cannot get a starting date from custom time period = " + fromTimePeriodId); } else if (thruTimePeriod.get("thruDate") == null) { return ServiceUtil.returnError("Cannot get a starting date from custom time period = " + thruTimePeriodId); } // call the service and pass back the results. Map input = new HashMap(context); input.put("fromDate", UtilDateTime.toTimestamp(fromTimePeriod.getDate("fromDate"))); input.put("thruDate", UtilDateTime.toTimestamp(thruTimePeriod.getDate("thruDate"))); input = dctx.getModelService(serviceName).makeValid(input, ModelService.IN_PARAM); Map result = dispatcher.runSync(serviceName, input); return result; } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Generates a cash flow statement. * * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getCashFlowStatementForTimePeriods(DispatchContext dctx, Map context) { return reportServiceTimePeriodHelper(dctx, context, "getCashFlowStatementForDates"); } /** * Generates a cash flow statement. * * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getCashFlowStatementForDates(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Timestamp fromDate = (Timestamp) context.get("fromDate"); Timestamp thruDate = (Timestamp) context.get("thruDate"); String organizationPartyId = (String) context.get("organizationPartyId"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); try { Map input = dctx.getModelService("getComparativeBalanceSheet").makeValid(context, ModelService.IN_PARAM); Map comparativeResults = dispatcher.runSync("getComparativeBalanceSheet", input); if (ServiceUtil.isError(comparativeResults)) { return ServiceUtil.returnError("Failed to compute cash flow statement. ", null, null, comparativeResults); } // extract the from date balance sheet and thru date balance sheet for convenience Map fromDateAccountBalances = (Map) comparativeResults.get("fromDateAccountBalances"); Map thruDateAccountBalances = (Map) comparativeResults.get("thruDateAccountBalances"); // run income statement for same date range input = dctx.getModelService("getIncomeStatementByDates").makeValid(context, ModelService.IN_PARAM); Map incomeResults = dispatcher.runSync("getIncomeStatementByDates", input); if (ServiceUtil.isError(incomeResults)) { return ServiceUtil.returnError("Failed to compute cash flow statement. ", null, null, incomeResults); } // extract the netIncome for convenience BigDecimal netIncome = (BigDecimal) incomeResults.get("netIncome"); // compute the beginning cash amount from accounts with glAccountClassId = CASH_EQUIVALENT and make a map of these accounts for return BigDecimal beginningCashAmount = ZERO; Map<GenericValue, BigDecimal> beginningCashAccountBalances = FastMap.newInstance(); Map<GenericValue, BigDecimal> beginningSheet = (Map<GenericValue, BigDecimal>) fromDateAccountBalances.get("assetAccountBalances"); // beginning cash equivalents are in from date balance sheet assets for (Iterator<GenericValue> iter = beginningSheet.keySet().iterator(); iter.hasNext();) { GenericValue account = iter.next(); if (!UtilAccounting.isAccountClass(account, "CASH_EQUIVALENT")) { continue; // skip non cash equivalent accounts } BigDecimal amount = beginningSheet.get(account); beginningCashAccountBalances.put(account, amount); beginningCashAmount = beginningCashAmount.add(amount).setScale(decimals, rounding); } // compute the ending cash amount from accounts with glAccountClassId = CASH_EQUIVALENT and make a map of these accounts for return BigDecimal endingCashAmount = ZERO; Map<GenericValue, BigDecimal> endingCashAccountBalances = FastMap.newInstance(); Map<GenericValue, BigDecimal> endingSheet = (Map<GenericValue, BigDecimal>) thruDateAccountBalances.get("assetAccountBalances"); // ending cash equivalents are in thru date balance sheet assets for (Iterator<GenericValue> iter = endingSheet.keySet().iterator(); iter.hasNext();) { GenericValue account = iter.next(); if (!UtilAccounting.isAccountClass(account, "CASH_EQUIVALENT")) { continue; // use our handy recursive method to test the class } BigDecimal amount = endingSheet.get(account); endingCashAccountBalances.put(account, amount); endingCashAmount = endingCashAmount.add(amount).setScale(decimals, rounding); } // cash flow amounts BigDecimal operatingCashFlow = ZERO; BigDecimal investingCashFlow = ZERO; BigDecimal financingCashFlow = ZERO; // cash flow maps of accounts to amounts Map operatingCashFlowAccountBalances = FastMap.newInstance(); Map investingCashFlowAccountBalances = FastMap.newInstance(); Map financingCashFlowAccountBalances = FastMap.newInstance(); // add net income to operating cash flow operatingCashFlow = netIncome; // add non cash expense accounts to the operating cash flow Map<GenericValue, BigDecimal> glAccountSums = (Map<GenericValue, BigDecimal>) incomeResults.get("glAccountSumsFlat"); if ((glAccountSums != null) && (glAccountSums.keySet() != null)) { for (Iterator<GenericValue> iter = glAccountSums.keySet().iterator(); iter.hasNext();) { GenericValue account = iter.next(); if (UtilAccounting.isAccountClass(account, "NON_CASH_EXPENSE") && !UtilAccounting.isAccountClass(account, "INVENTORY_ADJUST")) { BigDecimal amount = glAccountSums.get(account); // we can just add the amount, because expenses are Debits and all expense accounts are debit accounts // so the amount should already be positive operatingCashFlowAccountBalances.put(account, amount); operatingCashFlow = operatingCashFlow.add(amount).setScale(decimals, rounding); } } } // compute the cash flows from assets Map<GenericValue, BigDecimal> statement = (Map<GenericValue, BigDecimal>) comparativeResults.get("assetAccountBalances"); if ((statement != null) && (statement.keySet() != null)) { for (Iterator<GenericValue> iter = statement.keySet().iterator(); iter.hasNext();) { GenericValue account = iter.next(); if (UtilAccounting.isAccountClass(account, "CURRENT_ASSET") && !UtilAccounting.isAccountClass(account, "CASH_EQUIVALENT")) { // get current assets that are not cash equivalent accounts and flip the sign of the amounts, then add to operating cash flow BigDecimal amount = statement.get(account); amount = ZERO.subtract(amount).setScale(decimals, rounding); // flip the sign and use this value operatingCashFlowAccountBalances.put(account, amount); operatingCashFlow = operatingCashFlow.add(amount).setScale(decimals, rounding); } else if (UtilAccounting.isAccountClass(account, "LONGTERM_ASSET") && !UtilAccounting.isAccountClass(account, "ACCUM_DEPRECIATION") && !UtilAccounting.isAccountClass(account, "ACCUM_AMORTIZATION")) { // add to investing cash flow any long term assets BigDecimal amount = statement.get(account); investingCashFlowAccountBalances.put(account, amount.negate()); investingCashFlow = investingCashFlow.subtract(statement.get(account)).setScale(decimals, rounding); } } } // compute the cash flows from liabilities statement = (Map<GenericValue, BigDecimal>) comparativeResults.get("liabilityAccountBalances"); if ((statement != null) && (statement.keySet() != null)) { for (Iterator<GenericValue> iter = statement.keySet().iterator(); iter.hasNext();) { GenericValue account = iter.next(); if (UtilAccounting.isAccountClass(account, "CURRENT_LIABILITY")) { // add to operating cash flow any current liabilities operatingCashFlowAccountBalances.put(account, statement.get(account)); operatingCashFlow = operatingCashFlow.add(statement.get(account)).setScale(decimals, rounding); } else if (UtilAccounting.isAccountClass(account, "LONGTERM_LIABILITY")) { // add to financing cash flow any long term liabilities financingCashFlowAccountBalances.put(account, statement.get(account)); financingCashFlow = financingCashFlow.add(statement.get(account)).setScale(decimals, rounding); } } } // compute the cash flows from equity (sans the retained earnings accounts) statement = (Map<GenericValue, BigDecimal>) comparativeResults.get("equityAccountBalances"); if ((statement != null) && (statement.keySet() != null)) { for (Iterator<GenericValue> iter = statement.keySet().iterator(); iter.hasNext();) { GenericValue account = iter.next(); // add all equity to financing cash flow if (UtilAccounting.isAccountClass(account, "OWNERS_EQUITY")) { financingCashFlowAccountBalances.put(account, statement.get(account)); financingCashFlow = financingCashFlow.add(statement.get(account)).setScale(decimals, rounding); } } } // handle DISTRIBUTION account transactions statement = new HashMap<GenericValue, BigDecimal>(); // need to clear it now because this method adds the new DISTRIBUTION accounts and sums to the Map statement = getAcctgTransAndEntriesForClass(statement, organizationPartyId, fromDate, thruDate, glFiscalTypeId, "DISTRIBUTION", UtilAccountingTags.getTagParameters(context), userLogin, dispatcher); if ((statement != null) && (statement.keySet() != null)) { for (Iterator<GenericValue> iter = statement.keySet().iterator(); iter.hasNext();) { GenericValue account = iter.next(); if (statement.get(account) != null) { BigDecimal amount = statement.get(account); // here: a DISTRIBUTION should be a Debit transaction on a Credit (Equity) account, so it should already be negative // and can be added directly to the net financing cash flows financingCashFlowAccountBalances.put(account, amount); financingCashFlow = financingCashFlow.add(amount).setScale(decimals, rounding); } } } // complementary validation that the net cash flow is equal for the two methods to compute it BigDecimal netCashFlowOne = endingCashAmount.subtract(beginningCashAmount); BigDecimal netCashFlowTwo = operatingCashFlow.add(investingCashFlow).add(financingCashFlow); if (netCashFlowOne.compareTo(netCashFlowTwo) != 0) { Debug.logWarning("Net cash flow computation yielded different values! (ending cash amount - beginning cash amount) = [" + netCashFlowOne.toString() + "]; (operating + investing + financing) = [" + netCashFlowTwo.toString() + "]", MODULE); } else { Debug.logInfo("Net cash flow computation yielded same values: (ending cash amount - beginning cash amount) = [" + netCashFlowOne.toString() + "]; (operating + investing + financing) = [" + netCashFlowTwo.toString() + "]", MODULE); } Map results = ServiceUtil.returnSuccess(); results.put("beginningCashAmount", beginningCashAmount); results.put("beginningCashAccountBalances", beginningCashAccountBalances); results.put("endingCashAmount", endingCashAmount); results.put("endingCashAccountBalances", endingCashAccountBalances); results.put("operatingCashFlowAccountBalances", operatingCashFlowAccountBalances); results.put("investingCashFlowAccountBalances", investingCashFlowAccountBalances); results.put("financingCashFlowAccountBalances", financingCashFlowAccountBalances); results.put("operatingCashFlow", operatingCashFlow); results.put("investingCashFlow", investingCashFlow); results.put("financingCashFlow", financingCashFlow); results.put("netIncome", netIncome); results.put("netCashFlow", netCashFlowTwo); // return (operating + investing + financing) as the net cash flow return results; } catch (GenericServiceException e) { Debug.logError(e, "Failed to compute cash flow statement: " + e.getMessage(), MODULE); return ServiceUtil.returnError("Failed to compute cash flow statement: " + e.getMessage()); } catch (GenericEntityException e) { Debug.logError(e, "Failed to compute cash flow statement: " + e.getMessage(), MODULE); return ServiceUtil.returnError("Failed to compute cash flow statement: " + e.getMessage()); } } /** * Gets a Map of glAccountId,tag1,tag2,... -> sum of transactions for all income statement accounts (REVENUE, EXPENSE, INCOME) * over a period of dates in sepcific tags for an organization. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getIncomeStatementAccountSumsByTagByDate(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); String organizationPartyId = (String) context.get("organizationPartyId"); // this defaults to FINANCIALS_REPORTS_TAG (see the service definition) String accountingTagUsage = (String) context.get("accountingTagUsage"); try { DomainsLoader domainsLoader = new DomainsLoader(new Infrastructure(dispatcher), new User(userLogin)); DomainsDirectory domainsDirectory = domainsLoader.loadDomainsDirectory(); OrganizationDomainInterface organizationDomain = domainsDirectory.getOrganizationDomain(); OrganizationRepositoryInterface organizationRepository = organizationDomain.getOrganizationRepository(); Organization organization = organizationRepository.getOrganizationById(organizationPartyId); Map accountingTags = organization.getAccountingTagTypes(accountingTagUsage); return getIncomeStatementAccountSumsCommon(dctx, context, accountingTags); } catch (EntityNotFoundException ex) { return ServiceUtil.returnError(ex.getMessage()); } catch (RepositoryException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Takes an initial Map of GlAccount, sums and a List of AcctgTransAndEntries and adds them to the Map, * based on debit/credit flag of transaction transactionEntry and whether the account is a debit or credit account. * Useful for doing income statement and intra-time-period updating of balance sheets, etc. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map addToAccountBalancesByTag(DispatchContext dctx, Map context) { Map glAccountSums = (Map) context.get("glAccountSums"); Map accountingTags = (Map) context.get("accountingTags"); List transactionEntries = (List) context.get("transactionEntries"); try { UtilFinancial.sumBalancesByTag(glAccountSums, transactionEntries, accountingTags); Map result = ServiceUtil.returnSuccess(); result.put("glAccountSums", glAccountSums); return result; } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Generates an income statement over a range of dates, returning a Map of GlAccount and amounts and a netIncome. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") public static Map getIncomeStatementByTagByDates(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); Timestamp fromDate = (Timestamp) context.get("fromDate"); Timestamp thruDate = (Timestamp) context.get("thruDate"); String organizationPartyId = (String) context.get("organizationPartyId"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); // glFiscalTypeId defaults to ACTUAL if (UtilValidate.isEmpty(glFiscalTypeId)) { glFiscalTypeId = "ACTUAL"; context.put("glFiscalTypeId", glFiscalTypeId); } try { // get a Map of glAccount -> sums for all income statement accounts for this time period Map input = dctx.getModelService("getIncomeStatementAccountSumsByTagByDate").makeValid(context, ModelService.IN_PARAM); Map tmpResult = dispatcher.runSync("getIncomeStatementAccountSumsByTagByDate", input); if (tmpResult.get("glAccountSums") == null) { return ServiceUtil.returnError("Cannot sum up account balances properly for income statement"); } // note the key of this map is in the format: glAccountId,tag1,tag2,... Map<String, BigDecimal> glAccountSums = (HashMap<String, BigDecimal>) tmpResult.get("glAccountSums"); Map<String, String> glAccountTypeTree = FastMap.newInstance(); Map<String, List<Map>> glAccountSumsGrouped = FastMap.newInstance(); Map<String, BigDecimal> glAccountGroupSums = FastMap.newInstance(); Map<String, BigDecimal> sums = FastMap.newInstance(); prepareIncomeStatementMaps(glAccountTypeTree, glAccountSumsGrouped, glAccountGroupSums, sums, delegator); // sort them into the correct map while also keeping a running total of the aggregations we're interested in (net income, gross profit, etc.) for (String key : glAccountSums.keySet()) { // note the key of this map is in the format: glAccountId,tag1,tag2,... String[] keyArray = key.split(","); String glAccountId = keyArray[0]; GenericValue account = delegator.findByPrimaryKeyCache("GlAccount", UtilMisc.toMap("glAccountId", glAccountId)); Map<String, String> tagMap = FastMap.newInstance(); // put tags info into map (starting at index 1 since index 0 is the glAccountId) for (int i = 1; i < keyArray.length; i++) { tagMap.put(UtilAccountingTags.ENTITY_TAG_PREFIX + i, keyArray[i]); } calculateIncomeStatementMaps(glAccountTypeTree, glAccountSumsGrouped, glAccountGroupSums, sums, account, glAccountSums.get(key), tagMap, delegator); } return makeIncomeStatementResults(glAccountSums, glAccountSumsGrouped, glAccountGroupSums, sums, organizationPartyId, fromDate, thruDate, delegator); } catch (GenericEntityException ex) { return ServiceUtil.returnError(ex.getMessage()); } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } } /** * Common method for the <code>getIncomeStatementByTagByDates</code> and <code>getIncomeStatementByDates</code> services. * Initializes the Maps used for the calculation. * @param glAccountTypeTree an empty <code>Map</code> instance to initialize * @param glAccountSumsGrouped an empty <code>Map</code> instance to initialize * @param glAccountGroupSums an empty <code>Map</code> instance to initialize * @param sums an empty <code>Map</code> instance to initialize * @param delegator a <code>Delegator</code> value * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") private static void prepareIncomeStatementMaps(Map<String, String> glAccountTypeTree, Map<String, List<Map>> glAccountSumsGrouped, Map<String, BigDecimal> glAccountGroupSums, Map<String, BigDecimal> sums, Delegator delegator) throws GenericEntityException { // Get a flattened glAccountTypeId -> glAccountTypeId tree where the children of the master INCOME_STATEMENT_TYPEs are related directly. // The keys are the children glAccountTypeId and the value is the root glAccountTypeId in INCOME_STATEMENT_TYPE for (String glAccountTypeId : INCOME_STATEMENT_TYPES) { List<GenericValue> childrenValues = UtilCommon.getEntityChildren(delegator, delegator.findByPrimaryKeyCache("GlAccountType", UtilMisc.toMap("glAccountTypeId", glAccountTypeId))); for (GenericValue child : childrenValues) { glAccountTypeTree.put(child.getString("glAccountTypeId"), glAccountTypeId); } // identity element glAccountTypeTree.put(glAccountTypeId, glAccountTypeId); } // Accounts without a type are put in a special unclassified group. This is the identity element for those accounts. glAccountTypeTree.put(UNCLASSIFIED_TYPE, UNCLASSIFIED_TYPE); // We will group accounts into a Map with key in INCOME_STATEMENT_TYPES and values lists of accounts that are children of these types. // Instead of being a GenericValue, the account is a Map containing an additional field accountSum with the // correct sign for display of an income statement. // and a map to store the sums for each group // initialize the maps first for (String glAccountTypeId : INCOME_STATEMENT_TYPES) { List<Map> emptyList = FastList.newInstance(); glAccountSumsGrouped.put(glAccountTypeId, emptyList); glAccountGroupSums.put(glAccountTypeId, BigDecimal.ZERO); } // add an unclassified group for those accounts that don't show up anywhere List<Map> emptyList = FastList.newInstance(); glAccountSumsGrouped.put(UNCLASSIFIED_TYPE, emptyList); glAccountGroupSums.put(UNCLASSIFIED_TYPE, BigDecimal.ZERO); // initialize the sums Map sums.put("grossProfit", BigDecimal.ZERO); // gross profit = sum(REVENUE) - sum(COGS) sums.put("operatingIncome", BigDecimal.ZERO); // operating income = gross profit - sum(OPERATING_EXPENSE) sums.put("pretaxIncome", BigDecimal.ZERO); // pretax income = operating income + sum(OTHER_INCOME) - sum(OTHER_EXPENSE) sums.put("netIncome", BigDecimal.ZERO); // net income = pretax income - sum(TAX_EXPENSE) } /** * Common method for the <code>getIncomeStatementByDates</code> services. * Perform the calculation, using the given <code>account</code> and <code>sum</code> which are results from the <code>getIncomeStatementAccountSumsByDate</code> service. They should be returned in the <code>glAccountSums</code> result Map. * @param glAccountTypeTree a previously initialized <code>Map</code> instance of {glAccountTypeId: parent glAccountTypeId} * @param glAccountSumsGrouped a previously initialized <code>Map</code> instance of {glAccountTypeId: List of GL Account info map}, where the info map contains all the fields from the GL account, plus the total amount for this GL account * @param glAccountGroupSums a previously initialized <code>Map</code> instance of {glAccountTypeId: total amount} * @param sums a previously initialized <code>Map</code> instance containing grossProfit, operatingIncome, pretaxIncome and netIncome values * @param account the <code>GenericValue</code> that is iterated upon * @param sum the sum corresponding to the given GL account as given by the <code>getIncomeStatementAccountSumsByDate</code> services * @param delegator a <code>Delegator</code> value * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") private static void calculateIncomeStatementMaps(Map<String, String> glAccountTypeTree, Map<String, List<Map>> glAccountSumsGrouped, Map<String, BigDecimal> glAccountGroupSums, Map<String, BigDecimal> sums, GenericValue account, BigDecimal sum, Delegator delegator) throws GenericEntityException { calculateIncomeStatementMaps(glAccountTypeTree, glAccountSumsGrouped, glAccountGroupSums, sums, account, sum, new HashMap<String, String>(), delegator); } /** * Common method for the <code>getIncomeStatementByTagByDates</code> service. * Perform the calculation, using the given <code>account</code> and <code>sum</code> which are results from the <code>getIncomeStatementAccountSumsByTagByDate</code> service. They should be returned in the <code>glAccountSums</code> result Map. * @param glAccountTypeTree a previously initialized <code>Map</code> instance of {glAccountTypeId: parent glAccountTypeId} * @param glAccountSumsGrouped a previously initialized <code>Map</code> instance of {glAccountTypeId: List of GL Account info map}, where the info map contains all the fields from the GL account, plus the total amount for this GL account and the corresponding accounting tags * @param glAccountGroupSums a previously initialized <code>Map</code> instance of {glAccountTypeId: total amount} * @param sums a previously initialized <code>Map</code> instance containing grossProfit, operatingIncome, pretaxIncome and netIncome values * @param account the <code>GenericValue</code> that is iterated upon * @param sum the sum corresponding to the given GL account as given by the <code>getIncomeStatementAccountSumsByTagByDate</code> services * @param tagMap a <code>Map</code> of tag field to tag value which will be added to the GL account info map in the <code>glAccountGroupSumsGrouped</code> resulting <code>Map</code> * @param delegator a <code>Delegator</code> value * @throws GenericEntityException if an error occurs */ @SuppressWarnings("unchecked") private static void calculateIncomeStatementMaps(Map<String, String> glAccountTypeTree, Map<String, List<Map>> glAccountSumsGrouped, Map<String, BigDecimal> glAccountGroupSums, Map<String, BigDecimal> sums, GenericValue account, BigDecimal sum, Map<String, String> tagMap, Delegator delegator) throws GenericEntityException { String glAccountTypeId = account.getString("glAccountTypeId"); if (UtilValidate.isEmpty(glAccountTypeId)) { // accounts really *should* have a type TODO maybe put in separate group UNCONFIGURED_TYPE Debug.logWarning("Encountered GlAccount [" + account.get("glAccountId") + "] with no glAccountTypeId.", MODULE); glAccountTypeId = UNCLASSIFIED_TYPE; } // first determine what root glAccountType this is (note the setup of glAccountTypeTree above) glAccountTypeId = glAccountTypeTree.get(glAccountTypeId); if (UtilValidate.isEmpty(glAccountTypeId)) { // those that don't have a root in INCOME_STATEMENT_TYPES are considered unclassified glAccountTypeId = UNCLASSIFIED_TYPE; } // get the group of accounts List<Map> group = glAccountSumsGrouped.get(glAccountTypeId); if (group == null) { // if for some reason the glAccountTypeId was misconfigured (the class is correct, but not the type), then put this account in the unclassified group Debug.logWarning("Unable to determine what type of account [" + account.get("glAccountId") + "] is for purposes of income statement." + " It needs to be a child type of the following GlAccountTypes: " + INCOME_STATEMENT_TYPES + ". This account will be put in the unclassified group for now.", MODULE); glAccountTypeId = UNCLASSIFIED_TYPE; group = glAccountSumsGrouped.get(UNCLASSIFIED_TYPE); } Map accountMap = FastMap.newInstance(); accountMap.putAll(account.getAllFields()); accountMap.putAll(tagMap); if (UtilAccounting.isRevenueAccount(account) || UtilAccounting.isIncomeAccount(account)) { // no sign change } else if (UtilAccounting.isExpenseAccount(account)) { sum = sum.negate(); } else { // if for some reason the class was misconfigured (which should be impossible due to lookup conditions), then put this account in unclassified group Debug.logWarning("Unable to determine if account [" + account.get("glAccountId") + "] is revenue, income or expense. This account will be put in unclassified group.", MODULE); glAccountTypeId = UNCLASSIFIED_TYPE; group = glAccountSumsGrouped.get(UNCLASSIFIED_TYPE); } accountMap.put("accountSum", sum); // Now aggregate the amounts we're interested in. We are doing the sum(glAccountTypeId) here. The arithmetic on the aggregations is done afterwards. if ("REVENUE".equals(glAccountTypeId)) { sums.put("grossProfit", sums.get("grossProfit").add(sum)); } else if ("COGS".equals(glAccountTypeId)) { // because this is an expense account, positive COGS expenses should already be a negative value, so we can add this sums.put("grossProfit", sums.get("grossProfit").add(sum)); } else if ("OPERATING_EXPENSE".equals(glAccountTypeId)) { // note that sign is already negative due to this being an expense, so we add instead of subtract sums.put("operatingIncome", sums.get("operatingIncome").add(sum)); } else if ("OTHER_EXPENSE".equals(glAccountTypeId)) { // note that sign is already negative due to this being an expense, so we add instead of subtract sums.put("pretaxIncome", sums.get("pretaxIncome").add(sum)); } else if ("OTHER_INCOME".equals(glAccountTypeId)) { sums.put("pretaxIncome", sums.get("pretaxIncome").add(sum)); } else if ("TAX_EXPENSE".equals(glAccountTypeId)) { // note that sign is already negative due to this being an expense, so we add instead of subtract sums.put("netIncome", sums.get("netIncome").add(sum)); } else if (UNCLASSIFIED_TYPE.equals(glAccountTypeId)) { sums.put("netIncome", sums.get("netIncome").add(sum)); } // add this account to the group group.add(accountMap); // keep a running total for the group BigDecimal groupSum = glAccountGroupSums.get(glAccountTypeId); glAccountGroupSums.put(glAccountTypeId, groupSum.add(sum)); } @SuppressWarnings("unchecked") private static Map makeIncomeStatementResults(Map glAccountSums, Map<String, List<Map>> glAccountSumsGrouped, Map<String, BigDecimal> glAccountGroupSums, Map<String, BigDecimal> sums, String organizationPartyId, Timestamp fromDate, Timestamp thruDate, Delegator delegator) throws GenericEntityException { // complete the aggregated sums for operating, pretax and net incomes sums.put("operatingIncome", sums.get("operatingIncome").add(sums.get("grossProfit"))); sums.put("pretaxIncome", sums.get("pretaxIncome").add(sums.get("operatingIncome"))); sums.put("netIncome", sums.get("netIncome").add(sums.get("pretaxIncome"))); // was this income statement for periods which are closed? check by seeing if there are any unclosed time periods // in between these dates? If so, then this accounting period has not been closed // TODO: this is not very good. Implement a real service which checks through all interim periods correctly. boolean isClosed = true; EntityCondition conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition("organizationPartyId", EntityOperator.EQUALS, organizationPartyId), EntityCondition.makeCondition("isClosed", EntityOperator.NOT_EQUAL, "Y"), EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("fromDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate), EntityCondition.makeCondition("thruDate", EntityOperator.LESS_THAN_EQUAL_TO, thruDate))); List timePeriods = delegator.findByCondition("CustomTimePeriod", conditions, UtilMisc.toList("customTimePeriodId"), UtilMisc.toList("customTimePeriodId")); if (timePeriods.size() > 0) { isClosed = false; } // now get the profit/loss GlAccount for the organization and return it as well String retainedEarningsGlAccountId = null; GenericValue retainedEarningsGlAccount = null; // get retained earnings account for the organization try { retainedEarningsGlAccountId = UtilAccounting.getDefaultAccountId("RETAINED_EARNINGS", organizationPartyId, delegator); } catch (AccountingException e) { return ServiceUtil.returnError("Cannot find a RETAINED_EARNINGS for organization " + organizationPartyId); } retainedEarningsGlAccount = delegator.findByPrimaryKeyCache("GlAccount", UtilMisc.toMap("glAccountId", retainedEarningsGlAccountId)); // all done Map result = ServiceUtil.returnSuccess(); result.putAll(sums); result.put("glAccountSums", glAccountSumsGrouped); result.put("glAccountGroupSums", glAccountGroupSums); result.put("glAccountSumsFlat", glAccountSums); result.put("isClosed", new Boolean(isClosed)); result.put("retainedEarningsGlAccount", retainedEarningsGlAccount); return result; } /** * Gets a Map of glAccount -> sum of transactions for all income statement accounts (REVENUE, EXPENSE, INCOME) over a period of dates for an organization. * Uses the <code>addToAccountBalances</code> service. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") private static Map getIncomeStatementAccountSumsCommon(DispatchContext dctx, Map context) { return getIncomeStatementAccountSumsCommon(dctx, context, null); } /** * Gets a Map of (glAccountId,tag1,tag2,...) -> sum of transactions for all income statement accounts (REVENUE, EXPENSE, INCOME) over a period of dates for an organization. * Uses the <code>addToAccountBalancesByTag</code> service. * @param dctx a <code>DispatchContext</code> value * @param context a <code>Map</code> value * @param accountingTags the <code>Map</code> of accounting tags to consider when calling the <code>addToAccountBalancesByTag</code> service * @return a <code>Map</code> value */ @SuppressWarnings("unchecked") private static Map getIncomeStatementAccountSumsCommon(DispatchContext dctx, Map context, Map accountingTags) { LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); try { // first find all accounting transaction entries for this organizationPartyId and following into this time period which are // income statement transactions TODO can be configurable List transactionEntries = null; Map input = dctx.getModelService("getAcctgTransAndEntriesByType").makeValid(context, ModelService.IN_PARAM); input.put("glAccountClasses", INCOME_STATEMENT_CLASSES); Map tmpResult = dispatcher.runSync("getAcctgTransAndEntriesByType", input); if ((tmpResult != null) && (tmpResult.get("transactionEntries") != null)) { transactionEntries = (List) tmpResult.get("transactionEntries"); } // very important - we do not want the PERIOD_CLOSING transactions as this will duplicate the net income transactionEntries = EntityUtil.filterOutByCondition(transactionEntries, EntityCondition.makeCondition("acctgTransTypeId", EntityOperator.EQUALS, "PERIOD_CLOSING")); // now add them up by account. since we may have to deal with flipping the signs of transactions, we'd have analysis type of // transaction (debit/credit) vs class of account (debit/credit), so it wasn't possible to just use a view-entity to sum it all up Map<String, BigDecimal> glAccountSums = new HashMap<String, BigDecimal>(); input = UtilMisc.toMap("glAccountSums", glAccountSums, "transactionEntries", transactionEntries, "userLogin", userLogin); String serviceName = "addToAccountBalances"; if (accountingTags != null) { input.put("accountingTags", accountingTags); serviceName = "addToAccountBalancesByTag"; } tmpResult = dispatcher.runSync(serviceName, input); if (tmpResult.get("glAccountSums") == null) { return ServiceUtil.returnError("Cannot sum up account balances properly for income statement"); } else { Map result = ServiceUtil.returnSuccess(); result.put("glAccountSums", glAccountSums); return result; } } catch (GenericServiceException ex) { return ServiceUtil.returnError(ex.getMessage()); } } }
true
true
public static Map getTrialBalanceForDate(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); String organizationPartyId = (String) context.get("organizationPartyId"); Timestamp asOfDate = (Timestamp) context.get("asOfDate"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); Map tags = UtilAccountingTags.getTagParameters(context); // default to generating "ACTUAL" balance sheets if (UtilValidate.isEmpty(glFiscalTypeId)) { glFiscalTypeId = "ACTUAL"; context.put("glFiscalTypeId", glFiscalTypeId); } User user = new User(userLogin); Infrastructure infrastructure = new Infrastructure(dispatcher); DomainsLoader dl = new DomainsLoader(infrastructure, user); try { LedgerRepositoryInterface ledgerRepository = dl.loadDomainsDirectory().getLedgerDomain().getLedgerRepository(); // for totals of balances, debits and credits Map<GenericValue, BigDecimal> accountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> accountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> accountCredits = new HashMap<GenericValue, BigDecimal>(); // per account type Map<GenericValue, BigDecimal> assetAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> assetAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> assetAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountCredits = new HashMap<GenericValue, BigDecimal>(); // try to get the ending date of the most recent accounting time period which has been closed Timestamp lastClosedDate = UtilDateTime.toTimestamp(1, 1, 1970, 0, 0, 0); // default if there never has been a period closing FindLastClosedDateService findLastClosedDate = new FindLastClosedDateService(); findLastClosedDate.setInOrganizationPartyId(organizationPartyId); // this is in case the current time period is already closed, and you try to run a report at the end of the time period // adjust as of date forward 1 second, so if report date is 12/31/XX at 23:59:59.999, but CustomTimePeriod ends at 1/1/XX+1 00:00:00 and the CustomTimePeriod has been // closed, it will get the CustomTimePeriod as the last closed period. Otherwise, it will get the previous time period and add everything again. // but don't change the actual as of date because it may cause inconsistencies with other reports // does not appear to be an issue for balance sheet, income statement, because if it is missed you just re-calculate that time period again // but this report actually adds both, so if you miss a closed time period, it could cause double-counting findLastClosedDate.setInFindDate(UtilDateTime.adjustTimestamp(asOfDate, java.util.Calendar.SECOND, new Integer(1))); findLastClosedDate.setUser(user); findLastClosedDate.runSyncNoNewTransaction(infrastructure); // these are null unless there has been a closed time period before this BigDecimal netIncomeSinceLastClosing = null; GeneralLedgerAccount retainedEarningsGlAccount = ledgerRepository.getDefaultLedgerAccount(GlAccountTypeConstants.RETAINED_EARNINGS, organizationPartyId);; GeneralLedgerAccount profitLossGlAccount = ledgerRepository.getDefaultLedgerAccount(GlAccountTypeConstants.PROFIT_LOSS_ACCOUNT, organizationPartyId); // balance sheet account balances as of the previous closed time period, null if there has been no previous closed time periods Map balanceSheetAccountBalances = null; // if there has been a previous period closing, then we need both the income statement and balance sheet since the last closing if (findLastClosedDate.getOutLastClosedDate() != null) { lastClosedDate = findLastClosedDate.getOutLastClosedDate(); GetIncomeStatementByDatesService getIncomeStatement = new GetIncomeStatementByDatesService(); getIncomeStatement.setInFromDate(lastClosedDate); getIncomeStatement.setInThruDate(asOfDate); getIncomeStatement.setInOrganizationPartyId(organizationPartyId); getIncomeStatement.setInGlFiscalTypeId(glFiscalTypeId); getIncomeStatement.setInTag1((String) tags.get("tag1")); getIncomeStatement.setInTag2((String) tags.get("tag2")); getIncomeStatement.setInTag3((String) tags.get("tag3")); getIncomeStatement.setInTag4((String) tags.get("tag4")); getIncomeStatement.setInTag5((String) tags.get("tag5")); getIncomeStatement.setInTag6((String) tags.get("tag6")); getIncomeStatement.setInTag7((String) tags.get("tag7")); getIncomeStatement.setInTag8((String) tags.get("tag8")); getIncomeStatement.setInTag9((String) tags.get("tag9")); getIncomeStatement.setInTag10((String) tags.get("tag10")); getIncomeStatement.setUser(user); getIncomeStatement.runSyncNoNewTransaction(infrastructure); netIncomeSinceLastClosing = getIncomeStatement.getOutNetIncome(); GetBalanceSheetForDateService getBalanceSheet = new GetBalanceSheetForDateService(); getBalanceSheet.setInAsOfDate(lastClosedDate); getBalanceSheet.setInGlFiscalTypeId(glFiscalTypeId); getBalanceSheet.setInOrganizationPartyId(organizationPartyId); getBalanceSheet.setInTag1((String) tags.get("tag1")); getBalanceSheet.setInTag2((String) tags.get("tag2")); getBalanceSheet.setInTag3((String) tags.get("tag3")); getBalanceSheet.setInTag4((String) tags.get("tag4")); getBalanceSheet.setInTag5((String) tags.get("tag5")); getBalanceSheet.setInTag6((String) tags.get("tag6")); getBalanceSheet.setInTag7((String) tags.get("tag7")); getBalanceSheet.setInTag8((String) tags.get("tag8")); getBalanceSheet.setInTag9((String) tags.get("tag9")); getBalanceSheet.setInTag10((String) tags.get("tag10")); getBalanceSheet.setUser(user); getBalanceSheet.runSyncNoNewTransaction(infrastructure); balanceSheetAccountBalances = getBalanceSheet.getOutAssetAccountBalances(); balanceSheetAccountBalances.putAll(getBalanceSheet.getOutLiabilityAccountBalances()); balanceSheetAccountBalances.putAll(getBalanceSheet.getOutEquityAccountBalances()); } Debug.logInfo("Last closed date is [" + lastClosedDate + "] net income [" + netIncomeSinceLastClosing + "] profit loss account is [" + profitLossGlAccount.getGlAccountId() + "] and retained earnings account [" + retainedEarningsGlAccount.getGlAccountId() + "]", MODULE); // a little bit of a hack, using this method with a "null" for GL account class causes it to return the sum of the transaction entries for all the GL accounts accountBalances = getAcctgTransAndEntriesForClassWithDetails(accountBalances, accountDebits, accountCredits, organizationPartyId, lastClosedDate, asOfDate, glFiscalTypeId, null, tags, userLogin, dispatcher); // if there are balance sheet balances from the last closed time period, then add them to the account balances we just got, thus merging the last closed balance sheet with the trial balance since then if (balanceSheetAccountBalances != null) { Set<GenericValue> balanceSheetGlAccounts = balanceSheetAccountBalances.keySet(); for (GenericValue glAccount: balanceSheetGlAccounts) { UtilCommon.addInMapOfBigDecimal(accountBalances, glAccount, (BigDecimal) balanceSheetAccountBalances.get(glAccount)); } } // now we sort them out into separate sections for assets, liabilities, equities, revenue, expense, income // this is also where we add the net income since last time period closing to the retained earnings and profit loss accounts Set<GenericValue> glAccounts = accountBalances.keySet(); BigDecimal netBalance = BigDecimal.ZERO; // net of debit minus credit BigDecimal totalDebits = BigDecimal.ZERO; BigDecimal totalCredits = BigDecimal.ZERO; // we need to track if this has been done, and if not do it later manually boolean addedNetIncomeSinceLastClosingToRetainedEarnings = false; boolean addedNetIncomeSinceLastCLosingToProfitLoss = false; for (GenericValue glAccount : glAccounts) { BigDecimal balance = accountBalances.get(glAccount); String glAccountId = glAccount.getString("glAccountId"); // add net income since last closing to the retained earnings and profit loss accounts if (netIncomeSinceLastClosing != null) { if (glAccountId.equals(retainedEarningsGlAccount.getGlAccountId())) { balance = balance.add(netIncomeSinceLastClosing).setScale(decimals, rounding); addedNetIncomeSinceLastClosingToRetainedEarnings = true; Debug.logInfo("Adding retained earnings of [" + netIncomeSinceLastClosing + "] to GL account ["+ glAccountId + "] balance is now [" + balance + "]", MODULE); } if (glAccountId.equals(profitLossGlAccount.getGlAccountId())) { balance = balance.add(netIncomeSinceLastClosing).setScale(decimals, rounding); addedNetIncomeSinceLastCLosingToProfitLoss = true; Debug.logInfo("Adding retained earnings of [" + netIncomeSinceLastClosing + "] to GL account ["+ glAccountId + "] balance is now [" + balance + "]", MODULE); } } // add to net balance and total debits and total credits if (balance != null) { if (UtilAccounting.isDebitAccount(glAccount)) { totalDebits = totalDebits.add(balance); netBalance = netBalance.add(balance); } else { totalCredits = totalCredits.add(balance); netBalance = netBalance.subtract(balance); } } if (UtilAccounting.isAssetAccount(glAccount)) { assetAccountBalances.put(glAccount, balance); assetAccountDebits.put(glAccount, balance); } else if (UtilAccounting.isLiabilityAccount(glAccount)) { liabilityAccountBalances.put(glAccount, balance); liabilityAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isEquityAccount(glAccount)) { equityAccountBalances.put(glAccount, balance); equityAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isRevenueAccount(glAccount)) { revenueAccountBalances.put(glAccount, balance); revenueAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isExpenseAccount(glAccount)) { expenseAccountBalances.put(glAccount, balance); expenseAccountDebits.put(glAccount, balance); } else if (UtilAccounting.isIncomeAccount(glAccount)) { incomeAccountBalances.put(glAccount, balance); incomeAccountCredits.put(glAccount, balance); } else { Debug.logWarning("Classification of GL account [" + glAccount.getString("glAccountId") + "] is unknown, putting balance [" + balance + "] under debit", MODULE); otherAccountBalances.put(glAccount, balance); otherAccountDebits.put(glAccount, balance); } } // now manually put in the retained earnings if that was not done already // this assume that since there was no retained earnings from before, it should be zero if ((lastClosedDate != null) && !addedNetIncomeSinceLastClosingToRetainedEarnings) { equityAccountBalances.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); equityAccountDebits.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); equityAccountCredits.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); totalCredits = totalCredits.add(netIncomeSinceLastClosing); netBalance = netBalance.subtract(netIncomeSinceLastClosing); Debug.logInfo("Did not find retained earnings account, so put [" + netIncomeSinceLastClosing + "] for [" + retainedEarningsGlAccount.getGlAccountId() + "]", MODULE); } // do the same for profit loss. this should be OK -- an offsetting amount should've been added to retained earnings or put there right above if ((lastClosedDate != null) && !addedNetIncomeSinceLastCLosingToProfitLoss) { incomeAccountBalances.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); incomeAccountDebits.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); incomeAccountCredits.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); totalDebits = totalDebits.add(netIncomeSinceLastClosing); netBalance = netBalance.add(netIncomeSinceLastClosing); Debug.logInfo("Did not find profit loss account, so put [" + netIncomeSinceLastClosing + "] for [" + profitLossGlAccount.getGlAccountId() + "]", MODULE); } // calculate net income from the last closed date // add it to the retained earnings account and profit and loss account Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("assetAccountBalances", assetAccountBalances); results.put("liabilityAccountBalances", liabilityAccountBalances); results.put("equityAccountBalances", equityAccountBalances); results.put("revenueAccountBalances", revenueAccountBalances); results.put("expenseAccountBalances", expenseAccountBalances); results.put("incomeAccountBalances", incomeAccountBalances); results.put("otherAccountBalances", otherAccountBalances); results.put("assetAccountCredits", assetAccountCredits); results.put("liabilityAccountCredits", liabilityAccountCredits); results.put("equityAccountCredits", equityAccountCredits); results.put("revenueAccountCredits", revenueAccountCredits); results.put("expenseAccountCredits", expenseAccountCredits); results.put("incomeAccountCredits", incomeAccountCredits); results.put("otherAccountCredits", otherAccountCredits); results.put("assetAccountDebits", assetAccountDebits); results.put("liabilityAccountDebits", liabilityAccountDebits); results.put("equityAccountDebits", equityAccountDebits); results.put("revenueAccountDebits", revenueAccountDebits); results.put("expenseAccountDebits", expenseAccountDebits); results.put("incomeAccountDebits", incomeAccountDebits); results.put("otherAccountDebits", otherAccountDebits); results.put("totalBalances", netBalance); results.put("totalDebits", totalDebits); results.put("totalCredits", totalCredits); Debug.logInfo("getTrialBalanceForDate totals => balance = " + netBalance + ", credits = " + totalCredits + ", debits = " + totalDebits + ", calculated balance = " + totalCredits.subtract(totalDebits), MODULE); return results; } catch (GeneralException ex) { return ServiceUtil.returnError(ex.getMessage()); } }
public static Map getTrialBalanceForDate(DispatchContext dctx, Map context) { LocalDispatcher dispatcher = dctx.getDispatcher(); String organizationPartyId = (String) context.get("organizationPartyId"); Timestamp asOfDate = (Timestamp) context.get("asOfDate"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String glFiscalTypeId = (String) context.get("glFiscalTypeId"); Map tags = UtilAccountingTags.getTagParameters(context); // default to generating "ACTUAL" balance sheets if (UtilValidate.isEmpty(glFiscalTypeId)) { glFiscalTypeId = "ACTUAL"; context.put("glFiscalTypeId", glFiscalTypeId); } User user = new User(userLogin); Infrastructure infrastructure = new Infrastructure(dispatcher); DomainsLoader dl = new DomainsLoader(infrastructure, user); try { LedgerRepositoryInterface ledgerRepository = dl.loadDomainsDirectory().getLedgerDomain().getLedgerRepository(); // for totals of balances, debits and credits Map<GenericValue, BigDecimal> accountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> accountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> accountCredits = new HashMap<GenericValue, BigDecimal>(); // per account type Map<GenericValue, BigDecimal> assetAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountBalances = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> assetAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountDebits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> assetAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> liabilityAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> equityAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> revenueAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> expenseAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> incomeAccountCredits = new HashMap<GenericValue, BigDecimal>(); Map<GenericValue, BigDecimal> otherAccountCredits = new HashMap<GenericValue, BigDecimal>(); // try to get the ending date of the most recent accounting time period which has been closed Timestamp lastClosedDate = UtilDateTime.toTimestamp(1, 1, 1970, 0, 0, 0); // default if there never has been a period closing FindLastClosedDateService findLastClosedDate = new FindLastClosedDateService(); findLastClosedDate.setInOrganizationPartyId(organizationPartyId); // this is in case the current time period is already closed, and you try to run a report at the end of the time period // adjust as of date forward 1 second, so if report date is 12/31/XX at 23:59:59.999, but CustomTimePeriod ends at 1/1/XX+1 00:00:00 and the CustomTimePeriod has been // closed, it will get the CustomTimePeriod as the last closed period. Otherwise, it will get the previous time period and add everything again. // but don't change the actual as of date because it may cause inconsistencies with other reports // does not appear to be an issue for balance sheet, income statement, because if it is missed you just re-calculate that time period again // but this report actually adds both, so if you miss a closed time period, it could cause double-counting findLastClosedDate.setInFindDate(new java.sql.Date(UtilDateTime.adjustTimestamp(asOfDate, java.util.Calendar.SECOND, new Integer(1)).getTime())); findLastClosedDate.setUser(user); findLastClosedDate.runSyncNoNewTransaction(infrastructure); // these are null unless there has been a closed time period before this BigDecimal netIncomeSinceLastClosing = null; GeneralLedgerAccount retainedEarningsGlAccount = ledgerRepository.getDefaultLedgerAccount(GlAccountTypeConstants.RETAINED_EARNINGS, organizationPartyId);; GeneralLedgerAccount profitLossGlAccount = ledgerRepository.getDefaultLedgerAccount(GlAccountTypeConstants.PROFIT_LOSS_ACCOUNT, organizationPartyId); // balance sheet account balances as of the previous closed time period, null if there has been no previous closed time periods Map balanceSheetAccountBalances = null; // if there has been a previous period closing, then we need both the income statement and balance sheet since the last closing if (findLastClosedDate.getOutLastClosedDate() != null) { lastClosedDate = findLastClosedDate.getOutLastClosedDate(); GetIncomeStatementByDatesService getIncomeStatement = new GetIncomeStatementByDatesService(); getIncomeStatement.setInFromDate(lastClosedDate); getIncomeStatement.setInThruDate(asOfDate); getIncomeStatement.setInOrganizationPartyId(organizationPartyId); getIncomeStatement.setInGlFiscalTypeId(glFiscalTypeId); getIncomeStatement.setInTag1((String) tags.get("tag1")); getIncomeStatement.setInTag2((String) tags.get("tag2")); getIncomeStatement.setInTag3((String) tags.get("tag3")); getIncomeStatement.setInTag4((String) tags.get("tag4")); getIncomeStatement.setInTag5((String) tags.get("tag5")); getIncomeStatement.setInTag6((String) tags.get("tag6")); getIncomeStatement.setInTag7((String) tags.get("tag7")); getIncomeStatement.setInTag8((String) tags.get("tag8")); getIncomeStatement.setInTag9((String) tags.get("tag9")); getIncomeStatement.setInTag10((String) tags.get("tag10")); getIncomeStatement.setUser(user); getIncomeStatement.runSyncNoNewTransaction(infrastructure); netIncomeSinceLastClosing = getIncomeStatement.getOutNetIncome(); GetBalanceSheetForDateService getBalanceSheet = new GetBalanceSheetForDateService(); getBalanceSheet.setInAsOfDate(lastClosedDate); getBalanceSheet.setInGlFiscalTypeId(glFiscalTypeId); getBalanceSheet.setInOrganizationPartyId(organizationPartyId); getBalanceSheet.setInTag1((String) tags.get("tag1")); getBalanceSheet.setInTag2((String) tags.get("tag2")); getBalanceSheet.setInTag3((String) tags.get("tag3")); getBalanceSheet.setInTag4((String) tags.get("tag4")); getBalanceSheet.setInTag5((String) tags.get("tag5")); getBalanceSheet.setInTag6((String) tags.get("tag6")); getBalanceSheet.setInTag7((String) tags.get("tag7")); getBalanceSheet.setInTag8((String) tags.get("tag8")); getBalanceSheet.setInTag9((String) tags.get("tag9")); getBalanceSheet.setInTag10((String) tags.get("tag10")); getBalanceSheet.setUser(user); getBalanceSheet.runSyncNoNewTransaction(infrastructure); balanceSheetAccountBalances = getBalanceSheet.getOutAssetAccountBalances(); balanceSheetAccountBalances.putAll(getBalanceSheet.getOutLiabilityAccountBalances()); balanceSheetAccountBalances.putAll(getBalanceSheet.getOutEquityAccountBalances()); } Debug.logInfo("Last closed date is [" + lastClosedDate + "] net income [" + netIncomeSinceLastClosing + "] profit loss account is [" + profitLossGlAccount.getGlAccountId() + "] and retained earnings account [" + retainedEarningsGlAccount.getGlAccountId() + "]", MODULE); // a little bit of a hack, using this method with a "null" for GL account class causes it to return the sum of the transaction entries for all the GL accounts accountBalances = getAcctgTransAndEntriesForClassWithDetails(accountBalances, accountDebits, accountCredits, organizationPartyId, lastClosedDate, asOfDate, glFiscalTypeId, null, tags, userLogin, dispatcher); // if there are balance sheet balances from the last closed time period, then add them to the account balances we just got, thus merging the last closed balance sheet with the trial balance since then if (balanceSheetAccountBalances != null) { Set<GenericValue> balanceSheetGlAccounts = balanceSheetAccountBalances.keySet(); for (GenericValue glAccount: balanceSheetGlAccounts) { UtilCommon.addInMapOfBigDecimal(accountBalances, glAccount, (BigDecimal) balanceSheetAccountBalances.get(glAccount)); } } // now we sort them out into separate sections for assets, liabilities, equities, revenue, expense, income // this is also where we add the net income since last time period closing to the retained earnings and profit loss accounts Set<GenericValue> glAccounts = accountBalances.keySet(); BigDecimal netBalance = BigDecimal.ZERO; // net of debit minus credit BigDecimal totalDebits = BigDecimal.ZERO; BigDecimal totalCredits = BigDecimal.ZERO; // we need to track if this has been done, and if not do it later manually boolean addedNetIncomeSinceLastClosingToRetainedEarnings = false; boolean addedNetIncomeSinceLastCLosingToProfitLoss = false; for (GenericValue glAccount : glAccounts) { BigDecimal balance = accountBalances.get(glAccount); String glAccountId = glAccount.getString("glAccountId"); // add net income since last closing to the retained earnings and profit loss accounts if (netIncomeSinceLastClosing != null) { if (glAccountId.equals(retainedEarningsGlAccount.getGlAccountId())) { balance = balance.add(netIncomeSinceLastClosing).setScale(decimals, rounding); addedNetIncomeSinceLastClosingToRetainedEarnings = true; Debug.logInfo("Adding retained earnings of [" + netIncomeSinceLastClosing + "] to GL account ["+ glAccountId + "] balance is now [" + balance + "]", MODULE); } if (glAccountId.equals(profitLossGlAccount.getGlAccountId())) { balance = balance.add(netIncomeSinceLastClosing).setScale(decimals, rounding); addedNetIncomeSinceLastCLosingToProfitLoss = true; Debug.logInfo("Adding retained earnings of [" + netIncomeSinceLastClosing + "] to GL account ["+ glAccountId + "] balance is now [" + balance + "]", MODULE); } } // add to net balance and total debits and total credits if (balance != null) { if (UtilAccounting.isDebitAccount(glAccount)) { totalDebits = totalDebits.add(balance); netBalance = netBalance.add(balance); } else { totalCredits = totalCredits.add(balance); netBalance = netBalance.subtract(balance); } } if (UtilAccounting.isAssetAccount(glAccount)) { assetAccountBalances.put(glAccount, balance); assetAccountDebits.put(glAccount, balance); } else if (UtilAccounting.isLiabilityAccount(glAccount)) { liabilityAccountBalances.put(glAccount, balance); liabilityAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isEquityAccount(glAccount)) { equityAccountBalances.put(glAccount, balance); equityAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isRevenueAccount(glAccount)) { revenueAccountBalances.put(glAccount, balance); revenueAccountCredits.put(glAccount, balance); } else if (UtilAccounting.isExpenseAccount(glAccount)) { expenseAccountBalances.put(glAccount, balance); expenseAccountDebits.put(glAccount, balance); } else if (UtilAccounting.isIncomeAccount(glAccount)) { incomeAccountBalances.put(glAccount, balance); incomeAccountCredits.put(glAccount, balance); } else { Debug.logWarning("Classification of GL account [" + glAccount.getString("glAccountId") + "] is unknown, putting balance [" + balance + "] under debit", MODULE); otherAccountBalances.put(glAccount, balance); otherAccountDebits.put(glAccount, balance); } } // now manually put in the retained earnings if that was not done already // this assume that since there was no retained earnings from before, it should be zero if ((lastClosedDate != null) && !addedNetIncomeSinceLastClosingToRetainedEarnings) { equityAccountBalances.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); equityAccountDebits.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); equityAccountCredits.put(LedgerRepository.genericValueFromEntity(retainedEarningsGlAccount), netIncomeSinceLastClosing); totalCredits = totalCredits.add(netIncomeSinceLastClosing); netBalance = netBalance.subtract(netIncomeSinceLastClosing); Debug.logInfo("Did not find retained earnings account, so put [" + netIncomeSinceLastClosing + "] for [" + retainedEarningsGlAccount.getGlAccountId() + "]", MODULE); } // do the same for profit loss. this should be OK -- an offsetting amount should've been added to retained earnings or put there right above if ((lastClosedDate != null) && !addedNetIncomeSinceLastCLosingToProfitLoss) { incomeAccountBalances.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); incomeAccountDebits.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); incomeAccountCredits.put(LedgerRepository.genericValueFromEntity(profitLossGlAccount), netIncomeSinceLastClosing); totalDebits = totalDebits.add(netIncomeSinceLastClosing); netBalance = netBalance.add(netIncomeSinceLastClosing); Debug.logInfo("Did not find profit loss account, so put [" + netIncomeSinceLastClosing + "] for [" + profitLossGlAccount.getGlAccountId() + "]", MODULE); } // calculate net income from the last closed date // add it to the retained earnings account and profit and loss account Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("assetAccountBalances", assetAccountBalances); results.put("liabilityAccountBalances", liabilityAccountBalances); results.put("equityAccountBalances", equityAccountBalances); results.put("revenueAccountBalances", revenueAccountBalances); results.put("expenseAccountBalances", expenseAccountBalances); results.put("incomeAccountBalances", incomeAccountBalances); results.put("otherAccountBalances", otherAccountBalances); results.put("assetAccountCredits", assetAccountCredits); results.put("liabilityAccountCredits", liabilityAccountCredits); results.put("equityAccountCredits", equityAccountCredits); results.put("revenueAccountCredits", revenueAccountCredits); results.put("expenseAccountCredits", expenseAccountCredits); results.put("incomeAccountCredits", incomeAccountCredits); results.put("otherAccountCredits", otherAccountCredits); results.put("assetAccountDebits", assetAccountDebits); results.put("liabilityAccountDebits", liabilityAccountDebits); results.put("equityAccountDebits", equityAccountDebits); results.put("revenueAccountDebits", revenueAccountDebits); results.put("expenseAccountDebits", expenseAccountDebits); results.put("incomeAccountDebits", incomeAccountDebits); results.put("otherAccountDebits", otherAccountDebits); results.put("totalBalances", netBalance); results.put("totalDebits", totalDebits); results.put("totalCredits", totalCredits); Debug.logInfo("getTrialBalanceForDate totals => balance = " + netBalance + ", credits = " + totalCredits + ", debits = " + totalDebits + ", calculated balance = " + totalCredits.subtract(totalDebits), MODULE); return results; } catch (GeneralException ex) { return ServiceUtil.returnError(ex.getMessage()); } }
diff --git a/core/java/src/net/i2p/util/Addresses.java b/core/java/src/net/i2p/util/Addresses.java index 97e19cf54..0bf7df705 100644 --- a/core/java/src/net/i2p/util/Addresses.java +++ b/core/java/src/net/i2p/util/Addresses.java @@ -1,165 +1,168 @@ package net.i2p.util; /* * public domain */ import java.net.InetAddress; import java.net.Inet4Address; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * Methods to get the local addresses, and other IP utilities * * @since 0.8.3 moved to core from router/transport * @author zzz */ public abstract class Addresses { /** @return the first non-local address it finds, or null */ public static String getAnyAddress() { SortedSet<String> a = getAddresses(); if (!a.isEmpty()) return a.first(); return null; } /** * @return a sorted set of all addresses, excluding * IPv6, local, broadcast, multicast, etc. */ public static SortedSet<String> getAddresses() { return getAddresses(false, false); } /** * @return a sorted set of all addresses, excluding * only link local and multicast * @since 0.8.3 */ public static SortedSet<String> getAllAddresses() { return getAddresses(true, true); } /** * @return a sorted array of all addresses * @param includeLocal whether to include local * @param includeIPv6 whether to include IPV6 * @return an array of all addresses * @since 0.8.3 */ public static SortedSet<String> getAddresses(boolean includeLocal, boolean includeIPv6) { boolean haveIPv4 = false; boolean haveIPv6 = false; SortedSet<String> rv = new TreeSet(); try { InetAddress localhost = InetAddress.getLocalHost(); InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName()); if (allMyIps != null) { for (int i = 0; i < allMyIps.length; i++) { if (allMyIps[i] instanceof Inet4Address) haveIPv4 = true; else haveIPv6 = true; if (shouldInclude(allMyIps[i], includeLocal, includeIPv6)) rv.add(allMyIps[i].getHostAddress()); } } } catch (UnknownHostException e) {} try { - for(Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces(); ifcs.hasMoreElements();) { - NetworkInterface ifc = ifcs.nextElement(); - for(Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) { - InetAddress addr = addrs.nextElement(); - if (addr instanceof Inet4Address) - haveIPv4 = true; - else - haveIPv6 = true; - if (shouldInclude(addr, includeLocal, includeIPv6)) - rv.add(addr.getHostAddress()); + Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces(); + if (ifcs != null) { + while (ifcs.hasMoreElements()) { + NetworkInterface ifc = ifcs.nextElement(); + for(Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) { + InetAddress addr = addrs.nextElement(); + if (addr instanceof Inet4Address) + haveIPv4 = true; + else + haveIPv6 = true; + if (shouldInclude(addr, includeLocal, includeIPv6)) + rv.add(addr.getHostAddress()); + } } } } catch (SocketException e) {} if (includeLocal && haveIPv4) rv.add("0.0.0.0"); if (includeLocal && includeIPv6 && haveIPv6) rv.add("0:0:0:0:0:0:0:0"); // we could do "::" but all the other ones are probably in long form return rv; } private static boolean shouldInclude(InetAddress ia, boolean includeLocal, boolean includeIPv6) { return (!ia.isLinkLocalAddress()) && (!ia.isMulticastAddress()) && (includeLocal || ((!ia.isAnyLocalAddress()) && (!ia.isLoopbackAddress()) && (!ia.isSiteLocalAddress()))) && // Hamachi 5/8 allocated to RIPE (30 November 2010) // Removed from TransportImpl.isPubliclyRoutable() // Check moved to here, for now, but will eventually need to // remove it from here also. (includeLocal || (!ia.getHostAddress().startsWith("5."))) && (includeIPv6 || (ia instanceof Inet4Address)); } /** * Convenience method to convert an IP address to a String * without throwing an exception. * @return "null" for null, and "bad IP length x" if length is invalid * @since 0.8.12 */ public static String toString(byte[] addr) { if (addr == null) return "null"; try { return InetAddress.getByAddress(addr).getHostAddress(); } catch (UnknownHostException uhe) { return "bad IP length " + addr.length; } } /** * Convenience method to convert an IP address and port to a String * without throwing an exception. * @return "ip:port" * @since 0.8.12 */ public static String toString(byte[] addr, int port) { if (addr == null) return "null:" + port; try { String ip = InetAddress.getByAddress(addr).getHostAddress(); if (addr.length != 16) return ip + ':' + port; return '[' + ip + "]:" + port; } catch (UnknownHostException uhe) { return "(bad IP length " + addr.length + "):" + port; } } /** * Print out the local addresses */ public static void main(String[] args) { System.err.println("External Addresses:"); Set<String> a = getAddresses(false, false); for (String s : a) System.err.println(s); System.err.println("All addresses:"); a = getAddresses(true, true); for (String s : a) System.err.println(s); } }
true
true
public static SortedSet<String> getAddresses(boolean includeLocal, boolean includeIPv6) { boolean haveIPv4 = false; boolean haveIPv6 = false; SortedSet<String> rv = new TreeSet(); try { InetAddress localhost = InetAddress.getLocalHost(); InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName()); if (allMyIps != null) { for (int i = 0; i < allMyIps.length; i++) { if (allMyIps[i] instanceof Inet4Address) haveIPv4 = true; else haveIPv6 = true; if (shouldInclude(allMyIps[i], includeLocal, includeIPv6)) rv.add(allMyIps[i].getHostAddress()); } } } catch (UnknownHostException e) {} try { for(Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces(); ifcs.hasMoreElements();) { NetworkInterface ifc = ifcs.nextElement(); for(Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) { InetAddress addr = addrs.nextElement(); if (addr instanceof Inet4Address) haveIPv4 = true; else haveIPv6 = true; if (shouldInclude(addr, includeLocal, includeIPv6)) rv.add(addr.getHostAddress()); } } } catch (SocketException e) {} if (includeLocal && haveIPv4) rv.add("0.0.0.0"); if (includeLocal && includeIPv6 && haveIPv6) rv.add("0:0:0:0:0:0:0:0"); // we could do "::" but all the other ones are probably in long form return rv; }
public static SortedSet<String> getAddresses(boolean includeLocal, boolean includeIPv6) { boolean haveIPv4 = false; boolean haveIPv6 = false; SortedSet<String> rv = new TreeSet(); try { InetAddress localhost = InetAddress.getLocalHost(); InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName()); if (allMyIps != null) { for (int i = 0; i < allMyIps.length; i++) { if (allMyIps[i] instanceof Inet4Address) haveIPv4 = true; else haveIPv6 = true; if (shouldInclude(allMyIps[i], includeLocal, includeIPv6)) rv.add(allMyIps[i].getHostAddress()); } } } catch (UnknownHostException e) {} try { Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces(); if (ifcs != null) { while (ifcs.hasMoreElements()) { NetworkInterface ifc = ifcs.nextElement(); for(Enumeration<InetAddress> addrs = ifc.getInetAddresses(); addrs.hasMoreElements();) { InetAddress addr = addrs.nextElement(); if (addr instanceof Inet4Address) haveIPv4 = true; else haveIPv6 = true; if (shouldInclude(addr, includeLocal, includeIPv6)) rv.add(addr.getHostAddress()); } } } } catch (SocketException e) {} if (includeLocal && haveIPv4) rv.add("0.0.0.0"); if (includeLocal && includeIPv6 && haveIPv6) rv.add("0:0:0:0:0:0:0:0"); // we could do "::" but all the other ones are probably in long form return rv; }
diff --git a/ui/CPUGUIThread.java b/ui/CPUGUIThread.java index a5ed4af..5167634 100755 --- a/ui/CPUGUIThread.java +++ b/ui/CPUGUIThread.java @@ -1,254 +1,266 @@ /* CPUGUIThread.java * * This class handles the multi-threaded CPU object, and acts as a proxy between * the Main class and the CPU class. * (c) 2006 Antonella Scandura, Andrea Spadaccini * * This file is part of the EduMIPS64 project, and is released under the GNU * General Public License. * * 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 edumips64.ui; import edumips64.*; import edumips64.core.*; import edumips64.core.is.*; import edumips64.ui.*; import edumips64.utils.*; import javax.swing.*; /** This class handles the multi-threaded CPU object, and acts as a proxy between * the Main class and the CPU class. * @author Antonella Scandura * @author Andrea Spadaccini * */ public class CPUGUIThread extends Thread{ /** Needed for multithreading. */ private int nStep; /** Booleans for synchronous exception handling */ private boolean masked; private boolean terminate; /** Boolean describing if the CPU is running */ private boolean externalStop; /** Verbose mode */ private boolean verbose; /** Sleep interval between cycles in verbose mode */ private int sleep_interval; private CPU cpu; private GUIFrontend front; private JFrame f; public CPUGUIThread(){ externalStop = false; cpu = CPU.getInstance(); front = Main.getGUIFrontend(); f = Main.getMainFrame(); updateConfigValues(); } /** Used to refresh the internal configuration values. Takes the needed * configuration values from the configuration file. */ public void updateConfigValues() { sleep_interval = (Integer)Config.get("sleep_interval"); verbose = (Boolean)Config.get("verbose"); masked = (Boolean)Config.get("syncexc-masked"); terminate = (Boolean)Config.get("syncexc-terminate"); edumips64.Main.logger.debug("Terminate = " + terminate + "; masked = " + masked); } /** Allows external classes to stop the execution. */ public synchronized void stopExecution(){ externalStop = true; } /** Sets the number of cpu cycles. Set a negative number if you want the CPU * to cycle endlessly. * @param n an integer value*/ public synchronized void setSteps(int n){ nStep = n; } private synchronized void haltCPU() { front.updateComponents(); cpu.setStatus(CPU.CPUStatus.HALTED); Main.changeShownMenuItems(CPU.CPUStatus.HALTED); } /** Run method: waits for an external thread that sends the notify. When the * notify arrives, the method will execute nStep CPU cycles if nStep is * positive or equal to zero, or it will cycle indefinitely if nStep is * negative. */ public void run() { try { while(true){ synchronized(this) { wait(); } // Let's disable the running menu items and enable the stop menu // item Main.setRunningMenuItemsStatus(false); Main.setStopStatus(true); // Progress bar Main.startPB(); if(nStep < 0){ while(true){ if(verbose && (sleep_interval != 0)) { // Main.logger.debug("Waiting for " + sleep_interval + " milliseconds..."); sleep(sleep_interval); } synchronized(this) { if(externalStop == true) { externalStop = false; break; } } try { cpu.step(); front.updateComponents(); if(verbose) { front.represent(); } } catch(StoppedCPUException ex) { edumips64.Main.logger.debug("CPUGUIThread: CPU was stopped"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(BreakException ex) { front.updateComponents(); if(verbose) { front.represent(); } break; } catch(SynchronousException ex) { JOptionPane.showMessageDialog(f, CurrentLocale.getString(ex.getCode() + ".Message"), "EduMIPS64 - " + CurrentLocale.getString("EXCEPTION"), JOptionPane.ERROR_MESSAGE); if(terminate) { haltCPU(); break; } continue; } catch(HaltException ex) { haltCPU(); edumips64.Main.logger.debug("CPUGUIThread: CPU Halted"); front.updateComponents(); if(verbose) { front.represent(); } break; } + catch(MemoryElementNotFoundException ex) { + Main.logger.debug("Attempt to read a non-existent cell"); + haltCPU(); + JOptionPane.showMessageDialog(edumips64.Main.ioFrame, CurrentLocale.getString("ERROR_LABEL"), "EduMIPS64 - " + CurrentLocale.getString("ERROR"), JOptionPane.ERROR_MESSAGE); + break; + } catch(Exception ex) { Main.logger.debug("Exception in CPUGUIThread"); haltCPU(); new ReportDialog(f,ex,CurrentLocale.getString("GUI_STEP_ERROR")); break; } } } else{ for(int i=0 ; i<nStep; i++){ if(verbose && (sleep_interval != 0) && nStep > 1) { // Main.logger.debug("Waiting for " + sleep_interval + " milliseconds..."); sleep(sleep_interval); } synchronized(this) { if(externalStop == true) { externalStop = false; edumips64.Main.logger.debug("Stopping the CPU."); break; } } try { cpu.step(); front.updateComponents(); if(verbose) { front.represent(); } } catch(StoppedCPUException ex) { edumips64.Main.logger.debug("CPUGUIThread: CPU was stopped"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(BreakException ex) { edumips64.Main.logger.debug("Caught a BreakException."); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(SynchronousException ex) { JOptionPane.showMessageDialog(f, CurrentLocale.getString(ex.getCode() + ".Message"), "EduMIPS64 - " + CurrentLocale.getString("EXCEPTION"), JOptionPane.ERROR_MESSAGE); if(terminate) { haltCPU(); break; } continue; } catch(HaltException ex) { haltCPU(); edumips64.Main.logger.debug("CPUGUIThread: CPU Halted"); front.updateComponents(); if(verbose) { front.represent(); } break; } + catch(MemoryElementNotFoundException ex) { + Main.logger.debug("Attempt to read a non-existent cell"); + haltCPU(); + JOptionPane.showMessageDialog(edumips64.Main.ioFrame, CurrentLocale.getString("ERROR_LABEL"), "EduMIPS64 - " + CurrentLocale.getString("ERROR"), JOptionPane.ERROR_MESSAGE); + break; + } catch(Exception ex) { new ReportDialog(f,ex,CurrentLocale.getString("GUI_STEP_ERROR")); haltCPU(); break; } } } if(!verbose) { front.represent(); } if(cpu.getStatus() != CPU.CPUStatus.HALTED) Main.setRunningMenuItemsStatus(true); Main.setStopStatus(false); Main.stopPB(); } } catch(InterruptedException e) { e.printStackTrace(); } } }
false
true
public void run() { try { while(true){ synchronized(this) { wait(); } // Let's disable the running menu items and enable the stop menu // item Main.setRunningMenuItemsStatus(false); Main.setStopStatus(true); // Progress bar Main.startPB(); if(nStep < 0){ while(true){ if(verbose && (sleep_interval != 0)) { // Main.logger.debug("Waiting for " + sleep_interval + " milliseconds..."); sleep(sleep_interval); } synchronized(this) { if(externalStop == true) { externalStop = false; break; } } try { cpu.step(); front.updateComponents(); if(verbose) { front.represent(); } } catch(StoppedCPUException ex) { edumips64.Main.logger.debug("CPUGUIThread: CPU was stopped"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(BreakException ex) { front.updateComponents(); if(verbose) { front.represent(); } break; } catch(SynchronousException ex) { JOptionPane.showMessageDialog(f, CurrentLocale.getString(ex.getCode() + ".Message"), "EduMIPS64 - " + CurrentLocale.getString("EXCEPTION"), JOptionPane.ERROR_MESSAGE); if(terminate) { haltCPU(); break; } continue; } catch(HaltException ex) { haltCPU(); edumips64.Main.logger.debug("CPUGUIThread: CPU Halted"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(Exception ex) { Main.logger.debug("Exception in CPUGUIThread"); haltCPU(); new ReportDialog(f,ex,CurrentLocale.getString("GUI_STEP_ERROR")); break; } } } else{ for(int i=0 ; i<nStep; i++){ if(verbose && (sleep_interval != 0) && nStep > 1) { // Main.logger.debug("Waiting for " + sleep_interval + " milliseconds..."); sleep(sleep_interval); } synchronized(this) { if(externalStop == true) { externalStop = false; edumips64.Main.logger.debug("Stopping the CPU."); break; } } try { cpu.step(); front.updateComponents(); if(verbose) { front.represent(); } } catch(StoppedCPUException ex) { edumips64.Main.logger.debug("CPUGUIThread: CPU was stopped"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(BreakException ex) { edumips64.Main.logger.debug("Caught a BreakException."); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(SynchronousException ex) { JOptionPane.showMessageDialog(f, CurrentLocale.getString(ex.getCode() + ".Message"), "EduMIPS64 - " + CurrentLocale.getString("EXCEPTION"), JOptionPane.ERROR_MESSAGE); if(terminate) { haltCPU(); break; } continue; } catch(HaltException ex) { haltCPU(); edumips64.Main.logger.debug("CPUGUIThread: CPU Halted"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(Exception ex) { new ReportDialog(f,ex,CurrentLocale.getString("GUI_STEP_ERROR")); haltCPU(); break; } } } if(!verbose) { front.represent(); } if(cpu.getStatus() != CPU.CPUStatus.HALTED) Main.setRunningMenuItemsStatus(true); Main.setStopStatus(false); Main.stopPB(); } } catch(InterruptedException e) { e.printStackTrace(); } }
public void run() { try { while(true){ synchronized(this) { wait(); } // Let's disable the running menu items and enable the stop menu // item Main.setRunningMenuItemsStatus(false); Main.setStopStatus(true); // Progress bar Main.startPB(); if(nStep < 0){ while(true){ if(verbose && (sleep_interval != 0)) { // Main.logger.debug("Waiting for " + sleep_interval + " milliseconds..."); sleep(sleep_interval); } synchronized(this) { if(externalStop == true) { externalStop = false; break; } } try { cpu.step(); front.updateComponents(); if(verbose) { front.represent(); } } catch(StoppedCPUException ex) { edumips64.Main.logger.debug("CPUGUIThread: CPU was stopped"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(BreakException ex) { front.updateComponents(); if(verbose) { front.represent(); } break; } catch(SynchronousException ex) { JOptionPane.showMessageDialog(f, CurrentLocale.getString(ex.getCode() + ".Message"), "EduMIPS64 - " + CurrentLocale.getString("EXCEPTION"), JOptionPane.ERROR_MESSAGE); if(terminate) { haltCPU(); break; } continue; } catch(HaltException ex) { haltCPU(); edumips64.Main.logger.debug("CPUGUIThread: CPU Halted"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(MemoryElementNotFoundException ex) { Main.logger.debug("Attempt to read a non-existent cell"); haltCPU(); JOptionPane.showMessageDialog(edumips64.Main.ioFrame, CurrentLocale.getString("ERROR_LABEL"), "EduMIPS64 - " + CurrentLocale.getString("ERROR"), JOptionPane.ERROR_MESSAGE); break; } catch(Exception ex) { Main.logger.debug("Exception in CPUGUIThread"); haltCPU(); new ReportDialog(f,ex,CurrentLocale.getString("GUI_STEP_ERROR")); break; } } } else{ for(int i=0 ; i<nStep; i++){ if(verbose && (sleep_interval != 0) && nStep > 1) { // Main.logger.debug("Waiting for " + sleep_interval + " milliseconds..."); sleep(sleep_interval); } synchronized(this) { if(externalStop == true) { externalStop = false; edumips64.Main.logger.debug("Stopping the CPU."); break; } } try { cpu.step(); front.updateComponents(); if(verbose) { front.represent(); } } catch(StoppedCPUException ex) { edumips64.Main.logger.debug("CPUGUIThread: CPU was stopped"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(BreakException ex) { edumips64.Main.logger.debug("Caught a BreakException."); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(SynchronousException ex) { JOptionPane.showMessageDialog(f, CurrentLocale.getString(ex.getCode() + ".Message"), "EduMIPS64 - " + CurrentLocale.getString("EXCEPTION"), JOptionPane.ERROR_MESSAGE); if(terminate) { haltCPU(); break; } continue; } catch(HaltException ex) { haltCPU(); edumips64.Main.logger.debug("CPUGUIThread: CPU Halted"); front.updateComponents(); if(verbose) { front.represent(); } break; } catch(MemoryElementNotFoundException ex) { Main.logger.debug("Attempt to read a non-existent cell"); haltCPU(); JOptionPane.showMessageDialog(edumips64.Main.ioFrame, CurrentLocale.getString("ERROR_LABEL"), "EduMIPS64 - " + CurrentLocale.getString("ERROR"), JOptionPane.ERROR_MESSAGE); break; } catch(Exception ex) { new ReportDialog(f,ex,CurrentLocale.getString("GUI_STEP_ERROR")); haltCPU(); break; } } } if(!verbose) { front.represent(); } if(cpu.getStatus() != CPU.CPUStatus.HALTED) Main.setRunningMenuItemsStatus(true); Main.setStopStatus(false); Main.stopPB(); } } catch(InterruptedException e) { e.printStackTrace(); } }
diff --git a/test-case/src/test/java/pkg/UsingTwoPlaceHolderWithOneParameterTest.java b/test-case/src/test/java/pkg/UsingTwoPlaceHolderWithOneParameterTest.java index e0d1407..a56f776 100644 --- a/test-case/src/test/java/pkg/UsingTwoPlaceHolderWithOneParameterTest.java +++ b/test-case/src/test/java/pkg/UsingTwoPlaceHolderWithOneParameterTest.java @@ -1,42 +1,42 @@ package pkg; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class UsingTwoPlaceHolderWithOneParameterTest { @Test public void test() throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("target/findbugsXml.xml"); NodeList fileStats = doc.getElementsByTagName("FileStats"); for (int i = 0; i < fileStats.getLength(); ++i) { Node node = fileStats.item(i); NamedNodeMap attr = node.getAttributes(); if (attr.getNamedItem("path").getNodeValue().equals("pkg/UsingTwoPlaceHolderWithOneParameter.java")) { String bugCount = attr.getNamedItem("bugCount").getNodeValue(); - assertThat("UsingTwoPlaceHolderWithOneParameter.java should have no bug", bugCount, is("2")); + assertThat("UsingTwoPlaceHolderWithOneParameter.java should have 2 bugs", bugCount, is("2")); return; } } fail("Result of pkg/UsingTwoPlaceHolderWithOneParameter.java not found"); } }
true
true
public void test() throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("target/findbugsXml.xml"); NodeList fileStats = doc.getElementsByTagName("FileStats"); for (int i = 0; i < fileStats.getLength(); ++i) { Node node = fileStats.item(i); NamedNodeMap attr = node.getAttributes(); if (attr.getNamedItem("path").getNodeValue().equals("pkg/UsingTwoPlaceHolderWithOneParameter.java")) { String bugCount = attr.getNamedItem("bugCount").getNodeValue(); assertThat("UsingTwoPlaceHolderWithOneParameter.java should have no bug", bugCount, is("2")); return; } } fail("Result of pkg/UsingTwoPlaceHolderWithOneParameter.java not found"); }
public void test() throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("target/findbugsXml.xml"); NodeList fileStats = doc.getElementsByTagName("FileStats"); for (int i = 0; i < fileStats.getLength(); ++i) { Node node = fileStats.item(i); NamedNodeMap attr = node.getAttributes(); if (attr.getNamedItem("path").getNodeValue().equals("pkg/UsingTwoPlaceHolderWithOneParameter.java")) { String bugCount = attr.getNamedItem("bugCount").getNodeValue(); assertThat("UsingTwoPlaceHolderWithOneParameter.java should have 2 bugs", bugCount, is("2")); return; } } fail("Result of pkg/UsingTwoPlaceHolderWithOneParameter.java not found"); }
diff --git a/src/main/java/com/admob/rocksteady/reactor/Mongodb.java b/src/main/java/com/admob/rocksteady/reactor/Mongodb.java index 4ca0157..51a2ca3 100644 --- a/src/main/java/com/admob/rocksteady/reactor/Mongodb.java +++ b/src/main/java/com/admob/rocksteady/reactor/Mongodb.java @@ -1,136 +1,136 @@ /** **/ package com.admob.rocksteady.reactor; import org.springframework.beans.factory.annotation.Autowired; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.admob.rocksteady.util.MongodbInterface; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.UpdateListener; import com.espertech.esper.client.PropertyAccessException; /** * * @author Implement Esper UpdateListener to be used when event is triggered. * This is testing the base form. * */ public class Mongodb implements UpdateListener { private static final Logger logger = LoggerFactory.getLogger(Mongodb.class); private String type; private String tag; private String cname; private String suffix; @Autowired private MongodbInterface mongodbInterface; public void setType(String type) { this.type = type; } public void setTag(String tag) { this.tag = tag; } public void setCname(String cname) { this.cname = cname; } public String getTag() { return tag; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } /** * Handle the triggered event * * @param newEvents the new events in the window * @param oldEvents the old events in the window */ public void update(EventBean[] newEvents, EventBean[] oldEvents) { if (newEvents == null) { return; } for (EventBean newEvent : newEvents) { try { String retention; String app; String name; String colo; String value; String hostname; String cluster; String timestamp; retention = newEvent.get("retention").toString(); app = newEvent.get("app").toString(); // get name if (cname != null) { name = newEvent.get("name").toString(); } else { name = cname; } colo = newEvent.get("colo").toString(); String[] splitName = name.split("\\."); if (splitName.length > 2) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < splitName.length-1; i++) { if (sb.length() > 0) { sb.append("."); } sb.append(splitName[i]); } colo = sb.toString(); cluster = splitName[splitName.length-1]; } else { cluster = new String(""); } value = newEvent.get("value").toString(); try { timestamp = newEvent.get("timestamp").toString(); } catch (Exception e) { timestamp = null; } if ( (type != null) && (type.equals("uniq_host"))) { hostname = newEvent.get("hostname").toString(); } else { hostname = new String(""); } if (retention.isEmpty()) { retention = new String(""); } if (suffix == null) { suffix = new String(""); } - logger.debug("mogodb string: " + retention + "." + app + "." + name + "." + colo + "." + cluster + "." + hostname + "." + suffix + " " + value + " " + timestamp); + logger.debug("mogodb string: " + retention + "." + app + "." + name + "." + colo + "." + cluster + "." + hostname + "." + suffix + " " + value + " "); // Send the data mongodbInterface.send(mongodbInterface.mongodbObject(retention, app, name, colo, cluster, hostname, suffix, value, timestamp)); } catch (Exception e) { logger.error("Problem with sending metric to mongodb: " + e.toString()); } } } }
true
true
public void update(EventBean[] newEvents, EventBean[] oldEvents) { if (newEvents == null) { return; } for (EventBean newEvent : newEvents) { try { String retention; String app; String name; String colo; String value; String hostname; String cluster; String timestamp; retention = newEvent.get("retention").toString(); app = newEvent.get("app").toString(); // get name if (cname != null) { name = newEvent.get("name").toString(); } else { name = cname; } colo = newEvent.get("colo").toString(); String[] splitName = name.split("\\."); if (splitName.length > 2) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < splitName.length-1; i++) { if (sb.length() > 0) { sb.append("."); } sb.append(splitName[i]); } colo = sb.toString(); cluster = splitName[splitName.length-1]; } else { cluster = new String(""); } value = newEvent.get("value").toString(); try { timestamp = newEvent.get("timestamp").toString(); } catch (Exception e) { timestamp = null; } if ( (type != null) && (type.equals("uniq_host"))) { hostname = newEvent.get("hostname").toString(); } else { hostname = new String(""); } if (retention.isEmpty()) { retention = new String(""); } if (suffix == null) { suffix = new String(""); } logger.debug("mogodb string: " + retention + "." + app + "." + name + "." + colo + "." + cluster + "." + hostname + "." + suffix + " " + value + " " + timestamp); // Send the data mongodbInterface.send(mongodbInterface.mongodbObject(retention, app, name, colo, cluster, hostname, suffix, value, timestamp)); } catch (Exception e) { logger.error("Problem with sending metric to mongodb: " + e.toString()); } } }
public void update(EventBean[] newEvents, EventBean[] oldEvents) { if (newEvents == null) { return; } for (EventBean newEvent : newEvents) { try { String retention; String app; String name; String colo; String value; String hostname; String cluster; String timestamp; retention = newEvent.get("retention").toString(); app = newEvent.get("app").toString(); // get name if (cname != null) { name = newEvent.get("name").toString(); } else { name = cname; } colo = newEvent.get("colo").toString(); String[] splitName = name.split("\\."); if (splitName.length > 2) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < splitName.length-1; i++) { if (sb.length() > 0) { sb.append("."); } sb.append(splitName[i]); } colo = sb.toString(); cluster = splitName[splitName.length-1]; } else { cluster = new String(""); } value = newEvent.get("value").toString(); try { timestamp = newEvent.get("timestamp").toString(); } catch (Exception e) { timestamp = null; } if ( (type != null) && (type.equals("uniq_host"))) { hostname = newEvent.get("hostname").toString(); } else { hostname = new String(""); } if (retention.isEmpty()) { retention = new String(""); } if (suffix == null) { suffix = new String(""); } logger.debug("mogodb string: " + retention + "." + app + "." + name + "." + colo + "." + cluster + "." + hostname + "." + suffix + " " + value + " "); // Send the data mongodbInterface.send(mongodbInterface.mongodbObject(retention, app, name, colo, cluster, hostname, suffix, value, timestamp)); } catch (Exception e) { logger.error("Problem with sending metric to mongodb: " + e.toString()); } } }
diff --git a/src/main/java/me/desht/scrollingmenusign/commands/GiveMapCommand.java b/src/main/java/me/desht/scrollingmenusign/commands/GiveMapCommand.java index 60cc69f..064eea6 100644 --- a/src/main/java/me/desht/scrollingmenusign/commands/GiveMapCommand.java +++ b/src/main/java/me/desht/scrollingmenusign/commands/GiveMapCommand.java @@ -1,60 +1,60 @@ package me.desht.scrollingmenusign.commands; import me.desht.scrollingmenusign.SMSException; import me.desht.scrollingmenusign.ScrollingMenuSign; import me.desht.scrollingmenusign.util.MiscUtil; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.map.MapView; public class GiveMapCommand extends AbstractCommand { public GiveMapCommand() { super("sms gi", 1, 2); setPermissionNode("scrollingmenusign.commands.givemap"); setUsage("/sms givemap <id> [<amount>]"); } @SuppressWarnings("deprecation") @Override public boolean execute(ScrollingMenuSign plugin, Player player, String[] args) throws SMSException { int amount = 1; if (args.length >= 2) { try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new SMSException("Invalid amount '" + args[1] + "'."); } } short mapId; try { mapId = Short.parseShort(args[0]); } catch (NumberFormatException e) { - throw new SMSException("Invalid amount '" + args[0] + "'."); + throw new SMSException("Invalid map ID '" + args[0] + "'."); } if (amount < 1) amount = 1; if (amount > 64) amount = 64; if (Bukkit.getServer().getMap(mapId) == null) { MapView mv = Bukkit.getServer().createMap(player.getWorld()); mapId = mv.getId(); } ItemStack stack = new ItemStack(Material.MAP, amount); stack.setDurability(mapId); player.getInventory().addItem(stack); player.updateInventory(); String s = amount == 1 ? "" : "s"; MiscUtil.statusMessage(player, String.format("Created %d map%s (map_%d)", amount, s, mapId)); return true; } }
true
true
public boolean execute(ScrollingMenuSign plugin, Player player, String[] args) throws SMSException { int amount = 1; if (args.length >= 2) { try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new SMSException("Invalid amount '" + args[1] + "'."); } } short mapId; try { mapId = Short.parseShort(args[0]); } catch (NumberFormatException e) { throw new SMSException("Invalid amount '" + args[0] + "'."); } if (amount < 1) amount = 1; if (amount > 64) amount = 64; if (Bukkit.getServer().getMap(mapId) == null) { MapView mv = Bukkit.getServer().createMap(player.getWorld()); mapId = mv.getId(); } ItemStack stack = new ItemStack(Material.MAP, amount); stack.setDurability(mapId); player.getInventory().addItem(stack); player.updateInventory(); String s = amount == 1 ? "" : "s"; MiscUtil.statusMessage(player, String.format("Created %d map%s (map_%d)", amount, s, mapId)); return true; }
public boolean execute(ScrollingMenuSign plugin, Player player, String[] args) throws SMSException { int amount = 1; if (args.length >= 2) { try { amount = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new SMSException("Invalid amount '" + args[1] + "'."); } } short mapId; try { mapId = Short.parseShort(args[0]); } catch (NumberFormatException e) { throw new SMSException("Invalid map ID '" + args[0] + "'."); } if (amount < 1) amount = 1; if (amount > 64) amount = 64; if (Bukkit.getServer().getMap(mapId) == null) { MapView mv = Bukkit.getServer().createMap(player.getWorld()); mapId = mv.getId(); } ItemStack stack = new ItemStack(Material.MAP, amount); stack.setDurability(mapId); player.getInventory().addItem(stack); player.updateInventory(); String s = amount == 1 ? "" : "s"; MiscUtil.statusMessage(player, String.format("Created %d map%s (map_%d)", amount, s, mapId)); return true; }
diff --git a/src/main/java/cpw/mods/fml/installer/DownloadUtils.java b/src/main/java/cpw/mods/fml/installer/DownloadUtils.java index 86a2886..b57852a 100644 --- a/src/main/java/cpw/mods/fml/installer/DownloadUtils.java +++ b/src/main/java/cpw/mods/fml/installer/DownloadUtils.java @@ -1,257 +1,261 @@ package cpw.mods.fml.installer; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.jar.JarOutputStream; import java.util.jar.Pack200; import javax.swing.ProgressMonitor; import LZMA.LzmaInputStream; import argo.jdom.JsonNode; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import com.google.common.io.CharStreams; import com.google.common.io.Files; import com.google.common.io.InputSupplier; public class DownloadUtils { private static final String PACK_NAME = ".pack.lzma"; public static int downloadInstalledLibraries(String jsonMarker, File librariesDir, IMonitor monitor, List<JsonNode> libraries, int progress, List<String> grabbed, List<String> bad) { for (JsonNode library : libraries) { String libName = library.getStringValue("name"); List<String> checksums = null; if (library.isArrayNode("checksums")) { checksums = Lists.newArrayList(Lists.transform(library.getArrayNode("checksums"), new Function<JsonNode, String>() { public String apply(JsonNode node) { return node.getText(); } })); } monitor.setNote(String.format("Considering library %s", libName)); if (library.isBooleanValue(jsonMarker) && library.getBooleanValue(jsonMarker)) { String[] nameparts = Iterables.toArray(Splitter.on(':').split(libName), String.class); nameparts[0] = nameparts[0].replace('.', '/'); String jarName = nameparts[1] + '-' + nameparts[2] + ".jar"; String pathName = nameparts[0] + '/' + nameparts[1] + '/' + nameparts[2] + '/' + jarName; File libPath = new File(librariesDir, pathName.replace('/', File.separatorChar)); String libURL = "https://s3.amazonaws.com/Minecraft.Download/libraries/"; if (MirrorData.INSTANCE.hasMirrors() && library.isStringValue("url")) { libURL = MirrorData.INSTANCE.getMirrorURL(); } else if (library.isStringValue("url")) { libURL = library.getStringValue("url") + "/"; } if (libPath.exists() && checksumValid(libPath, checksums)) { monitor.setProgress(progress++); continue; } libPath.getParentFile().mkdirs(); monitor.setNote(String.format("Downloading library %s", libName)); libURL += pathName; File packFile = new File(libPath.getParentFile(), libName + PACK_NAME); if (!downloadFile(libName, packFile, libURL + PACK_NAME, null)) { if (library.isStringValue("url")) { monitor.setNote(String.format("Failed to locate packed library %s, trying unpacked", libName)); } if (!downloadFile(libName, libPath, libURL, checksums)) { bad.add(libName); } + else + { + grabbed.add(libName); + } } else { try { monitor.setNote(String.format("Unpacking packed file %s",packFile.getName())); FileOutputStream jarBytes = new FileOutputStream(libPath); JarOutputStream jos = new JarOutputStream(jarBytes); LzmaInputStream decompressedPackFile = new LzmaInputStream(new FileInputStream(packFile)); Pack200.newUnpacker().unpack(decompressedPackFile, jos); monitor.setNote(String.format("Successfully unpacked packed file %s",packFile.getName())); packFile.delete(); if (checksumValid(libPath, checksums)) { grabbed.add(libName); } else { bad.add(libName); } } catch (Exception e) { bad.add(libName); } } } monitor.setProgress(progress++); } return progress; } private static boolean checksumValid(File libPath, List<String> checksums) { try { return checksums == null || checksums.isEmpty() || checksums.contains(Hashing.sha1().hashBytes(Files.toByteArray(libPath)).toString()); } catch (IOException e) { return false; } } public static List<String> downloadList(String libURL) { try { URL url = new URL(libURL); URLConnection connection = url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputSupplier<InputStream> urlSupplier = new URLISSupplier(connection); return CharStreams.readLines(CharStreams.newReaderSupplier(urlSupplier, Charsets.UTF_8)); } catch (Exception e) { return Collections.emptyList(); } } public static boolean downloadFile(String libName, File libPath, String libURL, List<String> checksums) { try { URL url = new URL(libURL); URLConnection connection = url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); InputSupplier<InputStream> urlSupplier = new URLISSupplier(connection); Files.copy(urlSupplier, libPath); if (checksumValid(libPath, checksums)) { return true; } else { return false; } } catch (Exception e) { return false; } } static class URLISSupplier implements InputSupplier<InputStream> { private final URLConnection connection; private URLISSupplier(URLConnection connection) { this.connection = connection; } @Override public InputStream getInput() throws IOException { return connection.getInputStream(); } } public static IMonitor buildMonitor() { if (ServerInstall.headless) { return new IMonitor() { @Override public void setMaximum(int max) { } @Override public void setNote(String note) { System.out.println("MESSAGE: "+ note); } @Override public void setProgress(int progress) { } @Override public void close() { } }; } else { return new IMonitor() { private ProgressMonitor monitor; { monitor = new ProgressMonitor(null, "Downloading libraries", "Libraries are being analyzed", 0, 1); monitor.setMillisToPopup(0); monitor.setMillisToDecideToPopup(0); } @Override public void setMaximum(int max) { monitor.setMaximum(max); } @Override public void setNote(String note) { monitor.setNote(note); } @Override public void setProgress(int progress) { monitor.setProgress(progress); } @Override public void close() { monitor.close(); } }; } } }
true
true
public static int downloadInstalledLibraries(String jsonMarker, File librariesDir, IMonitor monitor, List<JsonNode> libraries, int progress, List<String> grabbed, List<String> bad) { for (JsonNode library : libraries) { String libName = library.getStringValue("name"); List<String> checksums = null; if (library.isArrayNode("checksums")) { checksums = Lists.newArrayList(Lists.transform(library.getArrayNode("checksums"), new Function<JsonNode, String>() { public String apply(JsonNode node) { return node.getText(); } })); } monitor.setNote(String.format("Considering library %s", libName)); if (library.isBooleanValue(jsonMarker) && library.getBooleanValue(jsonMarker)) { String[] nameparts = Iterables.toArray(Splitter.on(':').split(libName), String.class); nameparts[0] = nameparts[0].replace('.', '/'); String jarName = nameparts[1] + '-' + nameparts[2] + ".jar"; String pathName = nameparts[0] + '/' + nameparts[1] + '/' + nameparts[2] + '/' + jarName; File libPath = new File(librariesDir, pathName.replace('/', File.separatorChar)); String libURL = "https://s3.amazonaws.com/Minecraft.Download/libraries/"; if (MirrorData.INSTANCE.hasMirrors() && library.isStringValue("url")) { libURL = MirrorData.INSTANCE.getMirrorURL(); } else if (library.isStringValue("url")) { libURL = library.getStringValue("url") + "/"; } if (libPath.exists() && checksumValid(libPath, checksums)) { monitor.setProgress(progress++); continue; } libPath.getParentFile().mkdirs(); monitor.setNote(String.format("Downloading library %s", libName)); libURL += pathName; File packFile = new File(libPath.getParentFile(), libName + PACK_NAME); if (!downloadFile(libName, packFile, libURL + PACK_NAME, null)) { if (library.isStringValue("url")) { monitor.setNote(String.format("Failed to locate packed library %s, trying unpacked", libName)); } if (!downloadFile(libName, libPath, libURL, checksums)) { bad.add(libName); } } else { try { monitor.setNote(String.format("Unpacking packed file %s",packFile.getName())); FileOutputStream jarBytes = new FileOutputStream(libPath); JarOutputStream jos = new JarOutputStream(jarBytes); LzmaInputStream decompressedPackFile = new LzmaInputStream(new FileInputStream(packFile)); Pack200.newUnpacker().unpack(decompressedPackFile, jos); monitor.setNote(String.format("Successfully unpacked packed file %s",packFile.getName())); packFile.delete(); if (checksumValid(libPath, checksums)) { grabbed.add(libName); } else { bad.add(libName); } } catch (Exception e) { bad.add(libName); } } } monitor.setProgress(progress++); } return progress; }
public static int downloadInstalledLibraries(String jsonMarker, File librariesDir, IMonitor monitor, List<JsonNode> libraries, int progress, List<String> grabbed, List<String> bad) { for (JsonNode library : libraries) { String libName = library.getStringValue("name"); List<String> checksums = null; if (library.isArrayNode("checksums")) { checksums = Lists.newArrayList(Lists.transform(library.getArrayNode("checksums"), new Function<JsonNode, String>() { public String apply(JsonNode node) { return node.getText(); } })); } monitor.setNote(String.format("Considering library %s", libName)); if (library.isBooleanValue(jsonMarker) && library.getBooleanValue(jsonMarker)) { String[] nameparts = Iterables.toArray(Splitter.on(':').split(libName), String.class); nameparts[0] = nameparts[0].replace('.', '/'); String jarName = nameparts[1] + '-' + nameparts[2] + ".jar"; String pathName = nameparts[0] + '/' + nameparts[1] + '/' + nameparts[2] + '/' + jarName; File libPath = new File(librariesDir, pathName.replace('/', File.separatorChar)); String libURL = "https://s3.amazonaws.com/Minecraft.Download/libraries/"; if (MirrorData.INSTANCE.hasMirrors() && library.isStringValue("url")) { libURL = MirrorData.INSTANCE.getMirrorURL(); } else if (library.isStringValue("url")) { libURL = library.getStringValue("url") + "/"; } if (libPath.exists() && checksumValid(libPath, checksums)) { monitor.setProgress(progress++); continue; } libPath.getParentFile().mkdirs(); monitor.setNote(String.format("Downloading library %s", libName)); libURL += pathName; File packFile = new File(libPath.getParentFile(), libName + PACK_NAME); if (!downloadFile(libName, packFile, libURL + PACK_NAME, null)) { if (library.isStringValue("url")) { monitor.setNote(String.format("Failed to locate packed library %s, trying unpacked", libName)); } if (!downloadFile(libName, libPath, libURL, checksums)) { bad.add(libName); } else { grabbed.add(libName); } } else { try { monitor.setNote(String.format("Unpacking packed file %s",packFile.getName())); FileOutputStream jarBytes = new FileOutputStream(libPath); JarOutputStream jos = new JarOutputStream(jarBytes); LzmaInputStream decompressedPackFile = new LzmaInputStream(new FileInputStream(packFile)); Pack200.newUnpacker().unpack(decompressedPackFile, jos); monitor.setNote(String.format("Successfully unpacked packed file %s",packFile.getName())); packFile.delete(); if (checksumValid(libPath, checksums)) { grabbed.add(libName); } else { bad.add(libName); } } catch (Exception e) { bad.add(libName); } } } monitor.setProgress(progress++); } return progress; }
diff --git a/Gui.java b/Gui.java index 10e9067..a4ee28a 100644 --- a/Gui.java +++ b/Gui.java @@ -1,522 +1,522 @@ import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.lang.reflect.InvocationTargetException; import java.util.Random; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import pt.ipleiria.estg.dei.stackemup.gridpanel.GridPanel; import java.awt.event.*; import java.awt.Toolkit; import java.awt.BorderLayout; import javax.swing.ImageIcon; /** * * Graphical interface class * */ public class Gui extends JFrame implements KeyListener { private JPanel contentPane; protected static GridPanel battlefieldGrid; private BattleField bf; private int xGun; private Random ran; protected int lvl=1; protected static boolean gameOver = false; protected static boolean gameStart = false; protected JLabel lblScore; protected JLabel lblGameOver; protected JLabel lblGameStart; protected JLabel lblLevelFinished; protected JLabel lblEarthDestroyed; protected JLabel lblStartLevel; protected JLabel lblIcon; protected String info; protected static Thread novaThread; protected static int levelNumber = 1; protected static boolean levelFinished = false; protected static boolean pause = false; protected static boolean gameLoad = true; protected static boolean gameEnd = false; protected ImageManage im; protected ImageManageGun imGun; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Gui frame = new Gui(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the Graphical interface * * @throws IllegalElementException * @throws IllegalPositionException */ public Gui() throws IllegalElementException, IllegalPositionException { this.addKeyListener(this); Color col = new Color(000000); setIconImage(Toolkit.getDefaultToolkit().getImage(Gui.class.getResource("/image/icon.png"))); // System.out.println("test"); setTitle("Space Invaders - Erasmus Project 2013"); bf = new BattleField("es-in.txt"); ran = new Random(0); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setBounds(100, 100,694,691); setBounds(100, 100, 50 * bf.getColumns(), 50 + 50 * bf.getRows()); contentPane = new JPanel(); info = (" Earth life : " + bf.life + " Score : " + bf.score + " Level : " + lvl); contentPane.setBackground(col); contentPane.setBorder(new EmptyBorder(0, 0, 0, 0)); contentPane.setLayout(new BorderLayout(0, 0)); Sound.setCurrentMusic(Sound.music); setContentPane(contentPane); battlefieldGrid = new GridPanel(); battlefieldGrid.setShowGridLines(false); battlefieldGrid.setBackground(col); battlefieldGrid.setRows(bf.getRows()); battlefieldGrid.setColumns(bf.getColumns()); contentPane.add(battlefieldGrid, BorderLayout.CENTER); lblScore = new JLabel(info); lblScore.setFont(new Font("Space Invaders", Font.PLAIN, 16)); lblScore.setHorizontalAlignment(SwingConstants.LEFT); lblScore.setForeground(Color.WHITE); contentPane.add(lblScore, BorderLayout.NORTH); lblIcon = new JLabel(); lblIcon.setFont(new Font("Space Invaders", Font.PLAIN, 16)); lblIcon.setForeground(Color.BLACK); lblIcon.setHorizontalAlignment(SwingConstants.CENTER); lblIcon.setIcon(new ImageIcon(Gui.class .getResource("image/startScreen1.png"))); contentPane.add(lblIcon, BorderLayout.CENTER); xGun = 0; for (int i = 0; i < bf.columns; i++) { if (bf.battlefield[bf.rows - 2][i].toString().equals("G")) { xGun = i; break; } } final Runnable iterator = new Runnable() { public void run() { try { bf.move(); im = new ImageManage(bf,battlefieldGrid); imGun = new ImageManageGun(bf,battlefieldGrid); battlefieldGrid.repaint(); } catch (IllegalElementException e) { e.printStackTrace(); } catch (IllegalPositionException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; novaThread = new Thread() { public void run() { lblScore.setVisible(false); lblStartLevel = new JLabel(); lblStartLevel.setHorizontalAlignment(SwingConstants.CENTER); - lblStartLevel.setIcon(new ImageIcon(Gui.class.getResource("/image/start4.gif"))); + lblStartLevel.setIcon(new ImageIcon(Gui.class.getResource("/image/start3.gif"))); contentPane.add(lblStartLevel, BorderLayout.CENTER); repaint(); pause = true; try { sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } gameLoad = false; lblStartLevel.setIcon(new ImageIcon(Gui.class .getResource("/image/startBar.gif"))); repaint(); while (gameStart == false) { try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } pause = false; lblStartLevel.setVisible(false); battlefieldGrid.setVisible(true); battlefieldGrid.setGridBackground(Color.BLACK); lblScore.setVisible(true); contentPane.add(battlefieldGrid, BorderLayout.CENTER); int sc = 0; int li = 3; while (gameOver == false) { if (pause) { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } else { info = (" Earth life : " + BattleField.life + " Score : " + BattleField.score + " Level : " + levelNumber); int newli = BattleField.life; if (newli != li) { if (BattleField.life <= 0) { gameOver = true; // //////////////// lblEarthDestroyed = new JLabel(); lblEarthDestroyed.setFont(new Font( "Space Invaders", Font.PLAIN, 16)); lblEarthDestroyed.setForeground(Color.BLACK); lblEarthDestroyed .setHorizontalAlignment(SwingConstants.CENTER); lblEarthDestroyed.setIcon(new ImageIcon(Gui.class.getResource("image/earthDestroyed.png"))); contentPane.add(lblEarthDestroyed, BorderLayout.CENTER); // ////////////// lblGameOver = new JLabel("Score : " + BattleField.score); lblGameOver.setFont(new Font("Space Invaders",Font.PLAIN, 25)); lblGameOver.setHorizontalAlignment(SwingConstants.CENTER); lblGameOver.setForeground(Color.WHITE); contentPane.add(lblGameOver, BorderLayout.SOUTH); battlefieldGrid.setVisible(false); lblScore.setVisible(false); gameEnd = true; this.interrupt(); } lblScore.setText(info); li = newli; } if (levelFinished == true) { if(levelNumber<5){ try { sleep(2000); levelNumber++; info = (" Earth life : " + bf.life + " Score : " + bf.score + " Level : " + levelNumber); bf.newLevel(levelNumber); levelFinished=false; } catch (IllegalElementException e) { e.printStackTrace(); } catch (IllegalPositionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } else{ lblLevelFinished = new JLabel("You saved the earth ! - Score : "+BattleField.score); lblLevelFinished.setFont(new Font("Space Invaders", Font.PLAIN, 25)); lblLevelFinished.setHorizontalAlignment(SwingConstants.CENTER); lblLevelFinished.setForeground(Color.WHITE); contentPane.add(lblLevelFinished, BorderLayout.CENTER); battlefieldGrid.setVisible(false); lblScore.setVisible(false); this.interrupt(); } } int newsc = BattleField.score; if (newsc != sc) { sc = newsc; lblScore.setText(info); } for (int i = 0; i < bf.columns; i++) { if (bf.battlefield[bf.rows - 2][i].toString().equals( "G")) { xGun = i; break; } } try { SwingUtilities.invokeAndWait(iterator); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { System.out.println("Thread Stoped"); } if (BattleField.dead) { try { BattleField.score-=250; if(BattleField.score<0) BattleField.score=0; } catch (Exception e) { e.printStackTrace(); } } int numRand = ran.nextInt(100) + 1; if (numRand < 3) { try { bf.setBattleFieldElement(0, bf.columns - 1,new RedSpacecraft(0, bf.columns - 1)); } catch (Exception e) { System.out.println("RedSPaceCraft problem in Gui.java"); } } try { im = new ImageManage(bf, battlefieldGrid); imGun = new ImageManageGun(bf, battlefieldGrid); sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; novaThread.start(); } static boolean left = false; static boolean right = false; static boolean shot = false; /** * Key Detection */ public void keyPressed(KeyEvent e) { if (gameLoad == true) { } else { while (gameStart == false) { int keyCode = e.getKeyCode(); switch (keyCode) { case KeyEvent.VK_SPACE: gameStart = true; break; default: gameStart = true; break; } // try { // bf.clearShot(); // } catch (IllegalElementException e2) { // e2.printStackTrace(); // } catch (IllegalPositionException e2) { // e2.printStackTrace(); // } } int keyCode = e.getKeyCode(); switch (keyCode) { case KeyEvent.VK_LEFT : if (left == false && xGun > 0 && gameOver == false && BattleField.dead == false && pause==false) { left = true; try { if (bf.battlefield[bf.rows - 2][xGun - 1].toString().equals("S")) { BattleField.score-=250; if(BattleField.score<0){ BattleField.score=0; } bf.gunCounter--; Sound.explosion.play(); BattleField.dead = true; bf.setBattleFieldElement(bf.rows - 2, xGun, new Empty(bf.rows - 2, xGun)); bf.setBattleFieldElement(bf.rows - 2, xGun - 1,new GunExplosion(bf.rows - 2, xGun - 1)); bf.setBattleFieldElement(bf.rows - 2, bf.columns / 2,new Gun(bf.rows - 2, bf.columns / 2)); xGun = 0; } else { bf.battlefield[bf.rows - 2][xGun].move(bf.rows - 2, xGun - 1); bf.battlefield[bf.rows - 2][xGun - 1] = bf.battlefield[bf.rows - 2][xGun]; bf.setBattleFieldElement(bf.rows - 2, xGun, new Empty(bf.rows - 2, xGun)); } xGun--; imGun = new ImageManageGun(bf,battlefieldGrid); battlefieldGrid.repaint(); } catch (IllegalElementException | IllegalPositionException | ArrayIndexOutOfBoundsException e1) { System.out.println("ArrayIndexOutOfBoundsException exception in Gui.java"); } } break; case KeyEvent.VK_RIGHT : if ( right == false && xGun < bf.columns - 1 && gameOver == false && BattleField.dead == false && pause==false) { right = true; try { if (bf.battlefield[bf.rows - 2][xGun + 1].toString().equals("S")) { BattleField.score-=250; if(BattleField.score<0){ BattleField.score=0; } bf.gunCounter--; // bf.life--; Sound.explosion.play(); BattleField.dead = true; bf.setBattleFieldElement(bf.rows - 2, xGun, new Empty(bf.rows - 2, xGun)); bf.setBattleFieldElement(bf.rows - 2, xGun + 1,new GunExplosion(bf.rows - 2, xGun + 1)); bf.setBattleFieldElement(bf.rows - 2, bf.columns / 2,new Gun(bf.rows - 2, bf.columns / 2)); xGun = 0; } else { bf.battlefield[bf.rows - 2][xGun].move(bf.rows - 2,xGun + 1); bf.battlefield[bf.rows - 2][xGun + 1] = bf.battlefield[bf.rows - 2][xGun]; bf.setBattleFieldElement(bf.rows - 2, xGun, new Empty(bf.rows - 2, xGun)); } xGun++; imGun = new ImageManageGun(bf,battlefieldGrid); battlefieldGrid.repaint(); } catch (IllegalElementException | IllegalPositionException | ArrayIndexOutOfBoundsException e1) { System.out.println(xGun + " = " + e1); } } break; case KeyEvent.VK_SPACE : if (shot == false && gameOver == false && BattleField.dead == false && pause==false) { shot = true; try { bf.setBattleFieldElement(bf.rows - 3, xGun, new GunShot(bf.rows - 3, xGun)); im = new ImageManage(bf, battlefieldGrid); battlefieldGrid.repaint(); } catch (IllegalElementException | IllegalPositionException e1) { System.out.println("Probel shot inside the Gui.java"); } } break; case KeyEvent.VK_P : if (pause == false) { pause = true; } else { pause = false; } break; case KeyEvent.VK_ENTER : if (gameEnd ==true ) { } break; default: break; } } } /** * Key Released */ public void keyReleased(KeyEvent e) { if (gameLoad == true) { } else { int keyCode = e.getKeyCode(); switch (keyCode) { case KeyEvent.VK_LEFT: left = false; break; case KeyEvent.VK_RIGHT: right = false; break; case KeyEvent.VK_SPACE: shot = false; break; default: break; } } } /** * Key Typed (Not used in this case) */ public void keyTyped(KeyEvent e) { if (gameLoad == true) { } } }
true
true
public Gui() throws IllegalElementException, IllegalPositionException { this.addKeyListener(this); Color col = new Color(000000); setIconImage(Toolkit.getDefaultToolkit().getImage(Gui.class.getResource("/image/icon.png"))); // System.out.println("test"); setTitle("Space Invaders - Erasmus Project 2013"); bf = new BattleField("es-in.txt"); ran = new Random(0); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setBounds(100, 100,694,691); setBounds(100, 100, 50 * bf.getColumns(), 50 + 50 * bf.getRows()); contentPane = new JPanel(); info = (" Earth life : " + bf.life + " Score : " + bf.score + " Level : " + lvl); contentPane.setBackground(col); contentPane.setBorder(new EmptyBorder(0, 0, 0, 0)); contentPane.setLayout(new BorderLayout(0, 0)); Sound.setCurrentMusic(Sound.music); setContentPane(contentPane); battlefieldGrid = new GridPanel(); battlefieldGrid.setShowGridLines(false); battlefieldGrid.setBackground(col); battlefieldGrid.setRows(bf.getRows()); battlefieldGrid.setColumns(bf.getColumns()); contentPane.add(battlefieldGrid, BorderLayout.CENTER); lblScore = new JLabel(info); lblScore.setFont(new Font("Space Invaders", Font.PLAIN, 16)); lblScore.setHorizontalAlignment(SwingConstants.LEFT); lblScore.setForeground(Color.WHITE); contentPane.add(lblScore, BorderLayout.NORTH); lblIcon = new JLabel(); lblIcon.setFont(new Font("Space Invaders", Font.PLAIN, 16)); lblIcon.setForeground(Color.BLACK); lblIcon.setHorizontalAlignment(SwingConstants.CENTER); lblIcon.setIcon(new ImageIcon(Gui.class .getResource("image/startScreen1.png"))); contentPane.add(lblIcon, BorderLayout.CENTER); xGun = 0; for (int i = 0; i < bf.columns; i++) { if (bf.battlefield[bf.rows - 2][i].toString().equals("G")) { xGun = i; break; } } final Runnable iterator = new Runnable() { public void run() { try { bf.move(); im = new ImageManage(bf,battlefieldGrid); imGun = new ImageManageGun(bf,battlefieldGrid); battlefieldGrid.repaint(); } catch (IllegalElementException e) { e.printStackTrace(); } catch (IllegalPositionException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; novaThread = new Thread() { public void run() { lblScore.setVisible(false); lblStartLevel = new JLabel(); lblStartLevel.setHorizontalAlignment(SwingConstants.CENTER); lblStartLevel.setIcon(new ImageIcon(Gui.class.getResource("/image/start4.gif"))); contentPane.add(lblStartLevel, BorderLayout.CENTER); repaint(); pause = true; try { sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } gameLoad = false; lblStartLevel.setIcon(new ImageIcon(Gui.class .getResource("/image/startBar.gif"))); repaint(); while (gameStart == false) { try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } pause = false; lblStartLevel.setVisible(false); battlefieldGrid.setVisible(true); battlefieldGrid.setGridBackground(Color.BLACK); lblScore.setVisible(true); contentPane.add(battlefieldGrid, BorderLayout.CENTER); int sc = 0; int li = 3; while (gameOver == false) { if (pause) { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } else { info = (" Earth life : " + BattleField.life + " Score : " + BattleField.score + " Level : " + levelNumber); int newli = BattleField.life; if (newli != li) { if (BattleField.life <= 0) { gameOver = true; // //////////////// lblEarthDestroyed = new JLabel(); lblEarthDestroyed.setFont(new Font( "Space Invaders", Font.PLAIN, 16)); lblEarthDestroyed.setForeground(Color.BLACK); lblEarthDestroyed .setHorizontalAlignment(SwingConstants.CENTER); lblEarthDestroyed.setIcon(new ImageIcon(Gui.class.getResource("image/earthDestroyed.png"))); contentPane.add(lblEarthDestroyed, BorderLayout.CENTER); // ////////////// lblGameOver = new JLabel("Score : " + BattleField.score); lblGameOver.setFont(new Font("Space Invaders",Font.PLAIN, 25)); lblGameOver.setHorizontalAlignment(SwingConstants.CENTER); lblGameOver.setForeground(Color.WHITE); contentPane.add(lblGameOver, BorderLayout.SOUTH); battlefieldGrid.setVisible(false); lblScore.setVisible(false); gameEnd = true; this.interrupt(); } lblScore.setText(info); li = newli; } if (levelFinished == true) { if(levelNumber<5){ try { sleep(2000); levelNumber++; info = (" Earth life : " + bf.life + " Score : " + bf.score + " Level : " + levelNumber); bf.newLevel(levelNumber); levelFinished=false; } catch (IllegalElementException e) { e.printStackTrace(); } catch (IllegalPositionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } else{ lblLevelFinished = new JLabel("You saved the earth ! - Score : "+BattleField.score); lblLevelFinished.setFont(new Font("Space Invaders", Font.PLAIN, 25)); lblLevelFinished.setHorizontalAlignment(SwingConstants.CENTER); lblLevelFinished.setForeground(Color.WHITE); contentPane.add(lblLevelFinished, BorderLayout.CENTER); battlefieldGrid.setVisible(false); lblScore.setVisible(false); this.interrupt(); } } int newsc = BattleField.score; if (newsc != sc) { sc = newsc; lblScore.setText(info); } for (int i = 0; i < bf.columns; i++) { if (bf.battlefield[bf.rows - 2][i].toString().equals( "G")) { xGun = i; break; } } try { SwingUtilities.invokeAndWait(iterator); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { System.out.println("Thread Stoped"); } if (BattleField.dead) { try { BattleField.score-=250; if(BattleField.score<0) BattleField.score=0; } catch (Exception e) { e.printStackTrace(); } } int numRand = ran.nextInt(100) + 1; if (numRand < 3) { try { bf.setBattleFieldElement(0, bf.columns - 1,new RedSpacecraft(0, bf.columns - 1)); } catch (Exception e) { System.out.println("RedSPaceCraft problem in Gui.java"); } } try { im = new ImageManage(bf, battlefieldGrid); imGun = new ImageManageGun(bf, battlefieldGrid); sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; novaThread.start(); }
public Gui() throws IllegalElementException, IllegalPositionException { this.addKeyListener(this); Color col = new Color(000000); setIconImage(Toolkit.getDefaultToolkit().getImage(Gui.class.getResource("/image/icon.png"))); // System.out.println("test"); setTitle("Space Invaders - Erasmus Project 2013"); bf = new BattleField("es-in.txt"); ran = new Random(0); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // setBounds(100, 100,694,691); setBounds(100, 100, 50 * bf.getColumns(), 50 + 50 * bf.getRows()); contentPane = new JPanel(); info = (" Earth life : " + bf.life + " Score : " + bf.score + " Level : " + lvl); contentPane.setBackground(col); contentPane.setBorder(new EmptyBorder(0, 0, 0, 0)); contentPane.setLayout(new BorderLayout(0, 0)); Sound.setCurrentMusic(Sound.music); setContentPane(contentPane); battlefieldGrid = new GridPanel(); battlefieldGrid.setShowGridLines(false); battlefieldGrid.setBackground(col); battlefieldGrid.setRows(bf.getRows()); battlefieldGrid.setColumns(bf.getColumns()); contentPane.add(battlefieldGrid, BorderLayout.CENTER); lblScore = new JLabel(info); lblScore.setFont(new Font("Space Invaders", Font.PLAIN, 16)); lblScore.setHorizontalAlignment(SwingConstants.LEFT); lblScore.setForeground(Color.WHITE); contentPane.add(lblScore, BorderLayout.NORTH); lblIcon = new JLabel(); lblIcon.setFont(new Font("Space Invaders", Font.PLAIN, 16)); lblIcon.setForeground(Color.BLACK); lblIcon.setHorizontalAlignment(SwingConstants.CENTER); lblIcon.setIcon(new ImageIcon(Gui.class .getResource("image/startScreen1.png"))); contentPane.add(lblIcon, BorderLayout.CENTER); xGun = 0; for (int i = 0; i < bf.columns; i++) { if (bf.battlefield[bf.rows - 2][i].toString().equals("G")) { xGun = i; break; } } final Runnable iterator = new Runnable() { public void run() { try { bf.move(); im = new ImageManage(bf,battlefieldGrid); imGun = new ImageManageGun(bf,battlefieldGrid); battlefieldGrid.repaint(); } catch (IllegalElementException e) { e.printStackTrace(); } catch (IllegalPositionException e) { e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; novaThread = new Thread() { public void run() { lblScore.setVisible(false); lblStartLevel = new JLabel(); lblStartLevel.setHorizontalAlignment(SwingConstants.CENTER); lblStartLevel.setIcon(new ImageIcon(Gui.class.getResource("/image/start3.gif"))); contentPane.add(lblStartLevel, BorderLayout.CENTER); repaint(); pause = true; try { sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } gameLoad = false; lblStartLevel.setIcon(new ImageIcon(Gui.class .getResource("/image/startBar.gif"))); repaint(); while (gameStart == false) { try { sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } pause = false; lblStartLevel.setVisible(false); battlefieldGrid.setVisible(true); battlefieldGrid.setGridBackground(Color.BLACK); lblScore.setVisible(true); contentPane.add(battlefieldGrid, BorderLayout.CENTER); int sc = 0; int li = 3; while (gameOver == false) { if (pause) { try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } else { info = (" Earth life : " + BattleField.life + " Score : " + BattleField.score + " Level : " + levelNumber); int newli = BattleField.life; if (newli != li) { if (BattleField.life <= 0) { gameOver = true; // //////////////// lblEarthDestroyed = new JLabel(); lblEarthDestroyed.setFont(new Font( "Space Invaders", Font.PLAIN, 16)); lblEarthDestroyed.setForeground(Color.BLACK); lblEarthDestroyed .setHorizontalAlignment(SwingConstants.CENTER); lblEarthDestroyed.setIcon(new ImageIcon(Gui.class.getResource("image/earthDestroyed.png"))); contentPane.add(lblEarthDestroyed, BorderLayout.CENTER); // ////////////// lblGameOver = new JLabel("Score : " + BattleField.score); lblGameOver.setFont(new Font("Space Invaders",Font.PLAIN, 25)); lblGameOver.setHorizontalAlignment(SwingConstants.CENTER); lblGameOver.setForeground(Color.WHITE); contentPane.add(lblGameOver, BorderLayout.SOUTH); battlefieldGrid.setVisible(false); lblScore.setVisible(false); gameEnd = true; this.interrupt(); } lblScore.setText(info); li = newli; } if (levelFinished == true) { if(levelNumber<5){ try { sleep(2000); levelNumber++; info = (" Earth life : " + bf.life + " Score : " + bf.score + " Level : " + levelNumber); bf.newLevel(levelNumber); levelFinished=false; } catch (IllegalElementException e) { e.printStackTrace(); } catch (IllegalPositionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } else{ lblLevelFinished = new JLabel("You saved the earth ! - Score : "+BattleField.score); lblLevelFinished.setFont(new Font("Space Invaders", Font.PLAIN, 25)); lblLevelFinished.setHorizontalAlignment(SwingConstants.CENTER); lblLevelFinished.setForeground(Color.WHITE); contentPane.add(lblLevelFinished, BorderLayout.CENTER); battlefieldGrid.setVisible(false); lblScore.setVisible(false); this.interrupt(); } } int newsc = BattleField.score; if (newsc != sc) { sc = newsc; lblScore.setText(info); } for (int i = 0; i < bf.columns; i++) { if (bf.battlefield[bf.rows - 2][i].toString().equals( "G")) { xGun = i; break; } } try { SwingUtilities.invokeAndWait(iterator); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InterruptedException e) { System.out.println("Thread Stoped"); } if (BattleField.dead) { try { BattleField.score-=250; if(BattleField.score<0) BattleField.score=0; } catch (Exception e) { e.printStackTrace(); } } int numRand = ran.nextInt(100) + 1; if (numRand < 3) { try { bf.setBattleFieldElement(0, bf.columns - 1,new RedSpacecraft(0, bf.columns - 1)); } catch (Exception e) { System.out.println("RedSPaceCraft problem in Gui.java"); } } try { im = new ImageManage(bf, battlefieldGrid); imGun = new ImageManageGun(bf, battlefieldGrid); sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } } } } }; novaThread.start(); }
diff --git a/src/main/java/org/encog/workbench/dialogs/activation/ActivationDialog.java b/src/main/java/org/encog/workbench/dialogs/activation/ActivationDialog.java index 70a8da83..56b38d4f 100644 --- a/src/main/java/org/encog/workbench/dialogs/activation/ActivationDialog.java +++ b/src/main/java/org/encog/workbench/dialogs/activation/ActivationDialog.java @@ -1,214 +1,214 @@ /* * Encog(tm) Workbench v3.0 * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2011 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.workbench.dialogs.activation; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import org.encog.engine.network.activation.ActivationBiPolar; import org.encog.engine.network.activation.ActivationCompetitive; import org.encog.engine.network.activation.ActivationElliott; import org.encog.engine.network.activation.ActivationElliottSymmetric; import org.encog.engine.network.activation.ActivationFunction; import org.encog.engine.network.activation.ActivationGaussian; import org.encog.engine.network.activation.ActivationLOG; import org.encog.engine.network.activation.ActivationLinear; import org.encog.engine.network.activation.ActivationRamp; import org.encog.engine.network.activation.ActivationSIN; import org.encog.engine.network.activation.ActivationSigmoid; import org.encog.engine.network.activation.ActivationSoftMax; import org.encog.engine.network.activation.ActivationSteepenedSigmoid; import org.encog.engine.network.activation.ActivationStep; import org.encog.engine.network.activation.ActivationTANH; import org.encog.workbench.dialogs.common.EncogCommonDialog; import org.encog.workbench.dialogs.common.ValidationException; public class ActivationDialog extends EncogCommonDialog implements ItemListener { public static final String[] ACTIVATION_FUNCTION = { "ActivationBiPolar", "ActivationCompetitive", "ActivationGaussian", "ActivationLinear", "ActivationLOG", "ActivationSigmoid", "ActivationSIN", "ActivationSoftMax", "ActivationStep", "ActivationTANH", "ActivationRamp", "ActivationElliott", "ActivationElliottSymmetric", "ActivationSteepenedSigmoid" }; private JComboBox select = new JComboBox(ACTIVATION_FUNCTION); private EquationPanel equation; private JCheckBox derivative; private JButton params; private ActivationFunction activation; public ActivationDialog(JFrame owner) { super(owner); init(); } public ActivationDialog(JDialog owner) { super(owner); init(); } private void init() { this.setSize(600, 300); JPanel contents = this.getBodyPanel(); contents.setLayout(new BorderLayout()); contents.add(this.equation = new EquationPanel(), BorderLayout.CENTER); JPanel upper = new JPanel(); upper.setLayout(new BorderLayout()); contents.add(upper, BorderLayout.NORTH); this.select.addItemListener(this); this.derivative = new JCheckBox("View Derivative"); upper.add(select, BorderLayout.CENTER); this.params = new JButton("Params"); JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(1, 2)); buttons.add(this.derivative); buttons.add(this.params); upper.add(buttons, BorderLayout.EAST); this.derivative.addActionListener(this); this.params.addActionListener(this); } @Override public void collectFields() throws ValidationException { // TODO Auto-generated method stub } @Override public void setFields() { // TODO Auto-generated method stub } public void changeEquation() { boolean der = this.derivative.isSelected(); ActivationFunction newActivation = null; switch (this.select.getSelectedIndex()) { case 0: newActivation = new ActivationBiPolar(); break; case 1: newActivation = new ActivationCompetitive(); break; case 2: - newActivation = new ActivationGaussian(0, 1, 1); + newActivation = new ActivationGaussian(0, 1); break; case 3: newActivation = new ActivationLinear(); break; case 4: newActivation = new ActivationLOG(); break; case 5: newActivation = new ActivationSigmoid(); break; case 6: newActivation = new ActivationSIN(); break; case 7: newActivation = new ActivationSoftMax(); break; case 8: newActivation = new ActivationStep(); break; case 9: newActivation = new ActivationTANH(); break; case 10: newActivation = new ActivationRamp(); break; case 11: newActivation = new ActivationElliott(); break; case 12: newActivation = new ActivationElliottSymmetric(); break; case 13: newActivation = new ActivationSteepenedSigmoid(); break; } if( this.activation.getClass() != newActivation.getClass() ) { this.activation = newActivation; } this.equation.setupEquation(newActivation,!der); this.params.setEnabled(this.activation.getParams().length>0); } public void itemStateChanged(ItemEvent e) { if (e.getSource() == this.select) { changeEquation(); } } public void actionPerformed(final ActionEvent e) { super.actionPerformed(e); if (e.getSource() == this.derivative) { changeEquation(); } else if (e.getSource() == this.params) { ParamsDialog dlg = new ParamsDialog(this,this.activation); dlg.load(this.activation); if( dlg.process() ) { dlg.save(this.activation); this.equation.setupEquation(this.activation,!this.derivative.isSelected()); } } } public ActivationFunction getActivation() { return activation; } public void setActivation(ActivationFunction activation) { this.activation = activation; for (int i = 0; i < ACTIVATION_FUNCTION.length; i++) { if (ACTIVATION_FUNCTION[i].equals(activation.getClass() .getSimpleName())) { this.select.setSelectedIndex(i); } } this.equation.setupEquation(this.activation,!this.derivative.isSelected()); } }
true
true
public void changeEquation() { boolean der = this.derivative.isSelected(); ActivationFunction newActivation = null; switch (this.select.getSelectedIndex()) { case 0: newActivation = new ActivationBiPolar(); break; case 1: newActivation = new ActivationCompetitive(); break; case 2: newActivation = new ActivationGaussian(0, 1, 1); break; case 3: newActivation = new ActivationLinear(); break; case 4: newActivation = new ActivationLOG(); break; case 5: newActivation = new ActivationSigmoid(); break; case 6: newActivation = new ActivationSIN(); break; case 7: newActivation = new ActivationSoftMax(); break; case 8: newActivation = new ActivationStep(); break; case 9: newActivation = new ActivationTANH(); break; case 10: newActivation = new ActivationRamp(); break; case 11: newActivation = new ActivationElliott(); break; case 12: newActivation = new ActivationElliottSymmetric(); break; case 13: newActivation = new ActivationSteepenedSigmoid(); break; } if( this.activation.getClass() != newActivation.getClass() ) { this.activation = newActivation; } this.equation.setupEquation(newActivation,!der); this.params.setEnabled(this.activation.getParams().length>0); }
public void changeEquation() { boolean der = this.derivative.isSelected(); ActivationFunction newActivation = null; switch (this.select.getSelectedIndex()) { case 0: newActivation = new ActivationBiPolar(); break; case 1: newActivation = new ActivationCompetitive(); break; case 2: newActivation = new ActivationGaussian(0, 1); break; case 3: newActivation = new ActivationLinear(); break; case 4: newActivation = new ActivationLOG(); break; case 5: newActivation = new ActivationSigmoid(); break; case 6: newActivation = new ActivationSIN(); break; case 7: newActivation = new ActivationSoftMax(); break; case 8: newActivation = new ActivationStep(); break; case 9: newActivation = new ActivationTANH(); break; case 10: newActivation = new ActivationRamp(); break; case 11: newActivation = new ActivationElliott(); break; case 12: newActivation = new ActivationElliottSymmetric(); break; case 13: newActivation = new ActivationSteepenedSigmoid(); break; } if( this.activation.getClass() != newActivation.getClass() ) { this.activation = newActivation; } this.equation.setupEquation(newActivation,!der); this.params.setEnabled(this.activation.getParams().length>0); }
diff --git a/gagarin-model/src/main/java/ro/gagarin/utils/StatisticsContainer.java b/gagarin-model/src/main/java/ro/gagarin/utils/StatisticsContainer.java index 4c1b771..f136e44 100644 --- a/gagarin-model/src/main/java/ro/gagarin/utils/StatisticsContainer.java +++ b/gagarin-model/src/main/java/ro/gagarin/utils/StatisticsContainer.java @@ -1,30 +1,33 @@ package ro.gagarin.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; public class StatisticsContainer { private static ConcurrentHashMap<String, Statistic> statContainer = new ConcurrentHashMap<String, Statistic>( new HashMap<String, Statistic>()); public static void add(Statistic statistic) { statContainer.put(statistic.getName(), statistic); } public static List<Statistic> exportStatistics(String filter) { Pattern pattern = null; if (filter != null) { pattern = Pattern.compile(filter); } ArrayList<Statistic> list = new ArrayList<Statistic>(); for (Statistic stat : statContainer.values()) { - if (pattern != null && pattern.matcher(stat.getName()).matches()) + if (pattern == null) { list.add(new Statistic(stat)); + } else if (pattern.matcher(stat.getName()).matches()) { + list.add(new Statistic(stat)); + } } return list; } }
false
true
public static List<Statistic> exportStatistics(String filter) { Pattern pattern = null; if (filter != null) { pattern = Pattern.compile(filter); } ArrayList<Statistic> list = new ArrayList<Statistic>(); for (Statistic stat : statContainer.values()) { if (pattern != null && pattern.matcher(stat.getName()).matches()) list.add(new Statistic(stat)); } return list; }
public static List<Statistic> exportStatistics(String filter) { Pattern pattern = null; if (filter != null) { pattern = Pattern.compile(filter); } ArrayList<Statistic> list = new ArrayList<Statistic>(); for (Statistic stat : statContainer.values()) { if (pattern == null) { list.add(new Statistic(stat)); } else if (pattern.matcher(stat.getName()).matches()) { list.add(new Statistic(stat)); } } return list; }
diff --git a/src/src/main/java/net/sprauer/sitzplaner/model/Generation.java b/src/src/main/java/net/sprauer/sitzplaner/model/Generation.java index 41bdf79..7973b4b 100644 --- a/src/src/main/java/net/sprauer/sitzplaner/model/Generation.java +++ b/src/src/main/java/net/sprauer/sitzplaner/model/Generation.java @@ -1,142 +1,143 @@ package net.sprauer.sitzplaner.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Vector; import net.sprauer.sitzplaner.EA.Chromosome; import net.sprauer.sitzplaner.EA.Configuration; import net.sprauer.sitzplaner.EA.EAFactory; import net.sprauer.sitzplaner.EA.Strategy; public class Generation { private List<Chromosome> population = new Vector<Chromosome>(); Chromosome bestSolution = null; Chromosome worstSolution = null; private final Configuration configuration; public Generation(Configuration conf) throws Exception { this.configuration = conf; add(EAFactory.greedy(conf)); } public Chromosome getBestSolution() { return bestSolution; } public void clear() { population = new Vector<Chromosome>(); bestSolution = null; worstSolution = null; } public Configuration getConfiguration() { return configuration; } public List<Chromosome> getPopulation() { return population; } private void add(List<Chromosome> children) { for (Chromosome chromosome : children) { add(chromosome); } } public void add(Chromosome chrome) { population.add(chrome); if (bestSolution == null || chrome.getFitness() >= bestSolution.getFitness()) { bestSolution = chrome; } if (worstSolution == null || chrome.getFitness() <= worstSolution.getFitness()) { worstSolution = chrome; } } public synchronized void evolve() { sortPopulation(); List<Chromosome> parents = selecteTheBestAndKillTheRest(); List<Chromosome> children = new ArrayList<Chromosome>(); if (configuration.getStrategy() == Strategy.Rank) { children.addAll(rankBasedSwaps(parents)); children.addAll(rankBasedInversions(parents)); } else { for (Chromosome chromosome : parents) { children.addAll(chromosome.swap()); children.addAll(chromosome.invert()); } } add(children); } private List<Chromosome> rankBasedSwaps(List<Chromosome> parents) { int round = 1; List<Chromosome> children = new ArrayList<Chromosome>(); while (children.size() < configuration.getDescendantsUsingSwap()) { for (int i = 0; i < round && i < parents.size(); i++) { children.add(parents.get(i).doOneSwap()); } round++; } return children; } private List<Chromosome> rankBasedInversions(List<Chromosome> parents) { int round = 1; List<Chromosome> children = new ArrayList<Chromosome>(); while (children.size() < configuration.getDescendantsUsingInversion()) { for (int i = 0; i < round && i < parents.size(); i++) { children.add(parents.get(i).doOneInvert()); } round++; } return children; } private List<Chromosome> selecteTheBestAndKillTheRest() { List<Chromosome> parents = new ArrayList<Chromosome>(); if (configuration.getStrategy() == Strategy.Tournament) { tournamentSelection(parents); } else { int index = 0; double fitness = Double.MAX_VALUE; do { Chromosome chromosome = population.get(index); double delta = Math.abs(fitness - chromosome.getFitness()); - if (delta > 0.5) + if (delta > 0.5) { parents.add(chromosome); + fitness = chromosome.getFitness(); + } index++; - fitness = chromosome.getFitness(); } while (parents.size() < Math.min(population.size(), configuration.getParents()) && index < population.size()); } clear(); if (configuration.isStrategiePlus()) { add(parents); } return parents; } private void tournamentSelection(List<Chromosome> parents) { int best = population.size(); for (int i = 0; i < configuration.getTournamentSize(); i++) { int index = (int) (Math.random() * population.size()); if (index < best) { best = index; } } parents.add(population.get(best)); } public Chromosome getWorstSolution() { return worstSolution; } public void sortPopulation() { Collections.sort(population); } }
false
true
private List<Chromosome> selecteTheBestAndKillTheRest() { List<Chromosome> parents = new ArrayList<Chromosome>(); if (configuration.getStrategy() == Strategy.Tournament) { tournamentSelection(parents); } else { int index = 0; double fitness = Double.MAX_VALUE; do { Chromosome chromosome = population.get(index); double delta = Math.abs(fitness - chromosome.getFitness()); if (delta > 0.5) parents.add(chromosome); index++; fitness = chromosome.getFitness(); } while (parents.size() < Math.min(population.size(), configuration.getParents()) && index < population.size()); } clear(); if (configuration.isStrategiePlus()) { add(parents); } return parents; }
private List<Chromosome> selecteTheBestAndKillTheRest() { List<Chromosome> parents = new ArrayList<Chromosome>(); if (configuration.getStrategy() == Strategy.Tournament) { tournamentSelection(parents); } else { int index = 0; double fitness = Double.MAX_VALUE; do { Chromosome chromosome = population.get(index); double delta = Math.abs(fitness - chromosome.getFitness()); if (delta > 0.5) { parents.add(chromosome); fitness = chromosome.getFitness(); } index++; } while (parents.size() < Math.min(population.size(), configuration.getParents()) && index < population.size()); } clear(); if (configuration.isStrategiePlus()) { add(parents); } return parents; }
diff --git a/hot-deploy/financials/src/com/opensourcestrategies/financials/payment/PaymentActions.java b/hot-deploy/financials/src/com/opensourcestrategies/financials/payment/PaymentActions.java index 9ae73fec1..6ba9b9360 100644 --- a/hot-deploy/financials/src/com/opensourcestrategies/financials/payment/PaymentActions.java +++ b/hot-deploy/financials/src/com/opensourcestrategies/financials/payment/PaymentActions.java @@ -1,271 +1,272 @@ /* * Copyright (c) 2006 - 2010 Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package com.opensourcestrategies.financials.payment; import java.math.BigDecimal; import java.sql.Timestamp; import java.text.ParseException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import com.opensourcestrategies.financials.util.UtilFinancial; import javolution.util.FastList; import javolution.util.FastMap; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityFunction; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.party.party.PartyHelper; import org.opentaps.base.constants.PaymentTypeConstants; import org.opentaps.base.constants.StatusTypeConstants; import org.opentaps.base.entities.PaymentAndPaymentApplication; import org.opentaps.base.entities.PaymentMethod; import org.opentaps.base.entities.PaymentMethodType; import org.opentaps.base.entities.PaymentType; import org.opentaps.base.entities.StatusItem; import org.opentaps.common.builder.EntityListBuilder; import org.opentaps.common.builder.PageBuilder; import org.opentaps.common.util.UtilAccountingTags; import org.opentaps.common.util.UtilCommon; import org.opentaps.common.util.UtilDate; import org.opentaps.domain.DomainsDirectory; import org.opentaps.domain.billing.BillingDomainInterface; import org.opentaps.domain.billing.payment.Payment; import org.opentaps.domain.billing.payment.PaymentRepositoryInterface; import org.opentaps.domain.organization.Organization; import org.opentaps.domain.organization.OrganizationRepositoryInterface; import org.opentaps.foundation.action.ActionContext; /** * PaymentActions - Java Actions for payments. */ public final class PaymentActions { private static final String MODULE = PaymentActions.class.getName(); private PaymentActions() { } /** * Action for the find / list payments screen. * @param context the screen context * @throws GeneralException if an error occurs * @throws ParseException if an error occurs */ public static void findPayments(Map<String, Object> context) throws GeneralException, ParseException { final ActionContext ac = new ActionContext(context); final HttpServletRequest request = ac.getRequest(); final GenericDelegator delegator = ac.getDelegator(); final Locale locale = ac.getLocale(); final TimeZone timeZone = ac.getTimeZone(); final String organizationPartyId = UtilCommon.getOrganizationPartyId(request); if (organizationPartyId == null) { Debug.logError("No organizationPartyId set in the current request.", MODULE); return; } ac.put("organizationPartyId", organizationPartyId); DomainsDirectory dd = DomainsDirectory.getDomainsDirectory(ac); BillingDomainInterface billingDomain = dd.getBillingDomain(); PaymentRepositoryInterface paymentRepository = billingDomain.getPaymentRepository(); OrganizationRepositoryInterface organizationRepository = dd.getOrganizationDomain().getOrganizationRepository(); Organization organization = organizationRepository.getOrganizationById(organizationPartyId); // this gets overrided later according to the payment type ac.put("decoratorLocation", "component://opentaps-common/widget/screens/common/CommonScreens.xml"); // set the disbursement flag which is used to set the partyIdFrom/To to that of the organization on the find payment form as a hidden field // also set a default status id which is based on whether it's a disbursement (SENT) or not (RECEIVED), but this is overriden by parameters.statusId ac.put("headerItem", "receivables"); // for accounting tag filtering String tagsType = UtilAccountingTags.LOOKUP_RECEIPT_PAYMENT_TAG; boolean findDisbursement = false; String findPaymentTypeId = ac.getParameter("findPaymentTypeId"); if ("DISBURSEMENT".equals(findPaymentTypeId)) { findDisbursement = true; tagsType = UtilAccountingTags.LOOKUP_DISBURSEMENT_PAYMENT_TAG; ac.put("headerItem", "payables"); } ac.put("findDisbursement", findDisbursement); // get the list of paymentMethods, PaymentMethodTypes, paymentTypes List<String> supportedPaymentTypes = null; if (findDisbursement) { ac.put("decoratorLocation", "component://financials/widget/financials/screens/payables/PayablesScreens.xml"); ac.put("headerItem", "payables"); ac.put("paymentMethodList", organization.getRelated(PaymentMethod.class, UtilMisc.toList("paymentMethodTypeId"))); supportedPaymentTypes = Arrays.asList(PaymentTypeConstants.Disbursement.CUSTOMER_REFUND, PaymentTypeConstants.Disbursement.VENDOR_PAYMENT, PaymentTypeConstants.Disbursement.VENDOR_PREPAY, PaymentTypeConstants.Disbursement.COMMISSION_PAYMENT, PaymentTypeConstants.TaxPayment.SALES_TAX_PAYMENT, PaymentTypeConstants.TaxPayment.INCOME_TAX_PAYMENT, PaymentTypeConstants.TaxPayment.PAYROLL_TAX_PAYMENT); } else { ac.put("decoratorLocation", "component://financials/widget/financials/screens/receivables/ReceivablesScreens.xml"); ac.put("headerItem", "receivables"); ac.put("paymentMethodTypeList", UtilFinancial.getSimpleCustomerPaymentMethodTypes(delegator)); supportedPaymentTypes = Arrays.asList(PaymentTypeConstants.Receipt.INTEREST_RECEIPT, PaymentTypeConstants.Receipt.VENDOR_CREDIT_RCPT, PaymentTypeConstants.Receipt.CUSTOMER_PAYMENT, PaymentTypeConstants.Receipt.CUSTOMER_DEPOSIT); } List<PaymentType> paymentTypeList = paymentRepository.findListCache(PaymentType.class, EntityCondition.makeCondition(PaymentType.Fields.paymentTypeId.name(), EntityOperator.IN, supportedPaymentTypes)); ac.put("paymentTypeList", paymentTypeList); List<StatusItem> statusList = paymentRepository.findListCache(StatusItem.class, paymentRepository.map(StatusItem.Fields.statusTypeId, StatusTypeConstants.PMNT_STATUS), UtilMisc.toList(StatusItem.Fields.sequenceId.desc())); ac.put("statusList", statusList); // get the accounting tags for the select inputs if (tagsType != null) { ac.put("tagFilters", UtilAccountingTags.getAccountingTagFiltersForOrganization(organizationPartyId, tagsType, delegator, locale)); } // possible fields we're searching by String paymentId = ac.getParameter("paymentId"); String partyIdFrom = ac.getParameter("partyIdFrom"); String partyIdTo = ac.getParameter("partyIdTo"); String paymentTypeId = ac.getParameter("paymentTypeId"); String paymentMethodId = ac.getParameter("paymentMethodId"); String paymentMethodTypeId = ac.getParameter("paymentMethodTypeId"); String paymentRefNum = ac.getParameter("paymentRefNum"); String statusId = ac.getParameter("statusId"); Timestamp fromDate = UtilDate.toTimestamp(ac.getCompositeParameter("fromDate"), timeZone, locale); Timestamp thruDate = UtilDate.toTimestamp(ac.getCompositeParameter("thruDate"), timeZone, locale); String amountFrom = ac.getParameter("amountFrom"); String amountThru = ac.getParameter("amountThru"); String openAmountFrom = ac.getParameter("openAmountFrom"); String openAmountThru = ac.getParameter("openAmountThru"); // construct search conditions List<EntityCondition> searchConditions = new FastList<EntityCondition>(); if (paymentId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentId.name(), EntityOperator.EQUALS, paymentId)); } // force one of the party to the organization according to the payment type if (findDisbursement) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdFrom.name(), EntityOperator.EQUALS, organizationPartyId)); if (partyIdTo != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdTo.name(), EntityOperator.EQUALS, partyIdTo)); } } else { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdTo.name(), EntityOperator.EQUALS, organizationPartyId)); if (partyIdFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdFrom.name(), EntityOperator.EQUALS, partyIdFrom)); } } if (paymentTypeId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentTypeId.name(), EntityOperator.EQUALS, paymentTypeId)); } else { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentTypeId.name(), EntityOperator.IN, supportedPaymentTypes)); } if (findDisbursement) { if (paymentMethodId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentMethodId.name(), EntityOperator.EQUALS, paymentMethodId)); } } else { if (paymentMethodTypeId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentMethodTypeId.name(), EntityOperator.EQUALS, paymentMethodTypeId)); } } if (paymentRefNum != null) { // make sure the look up is case insensitive searchConditions.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(Payment.Fields.paymentRefNum.name()), EntityOperator.LIKE, EntityFunction.UPPER(paymentRefNum + "%"))); } if (statusId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.statusId.name(), EntityOperator.EQUALS, statusId)); } if (fromDate != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.effectiveDate.name(), EntityOperator.GREATER_THAN_EQUAL_TO, fromDate)); } if (thruDate != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.effectiveDate.name(), EntityOperator.LESS_THAN_EQUAL_TO, thruDate)); } if (amountFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.amount.name(), EntityOperator.GREATER_THAN_EQUAL_TO, new BigDecimal(amountFrom))); } if (amountThru != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.amount.name(), EntityOperator.LESS_THAN_EQUAL_TO, new BigDecimal(amountThru))); } if (openAmountFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.openAmount.name(), EntityOperator.GREATER_THAN_EQUAL_TO, new BigDecimal(openAmountFrom))); } if (openAmountThru != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.openAmount.name(), EntityOperator.LESS_THAN_EQUAL_TO, new BigDecimal(openAmountThru))); } if (tagsType != null) { // if the organization is using allocatePaymentTagsToApplications then the tags are on the payment applications, // else they are on the Payments if (organization.allocatePaymentTagsToApplications()) { searchConditions.addAll(UtilAccountingTags.buildTagConditions(organizationPartyId, tagsType, delegator, request, UtilAccountingTags.TAG_PARAM_PREFIX, "applAcctgTagEnumId")); } else { searchConditions.addAll(UtilAccountingTags.buildTagConditions(organizationPartyId, tagsType, delegator, request)); } } // Pagination Set<String> fieldsToSelect = new HashSet<String>(new Payment().getAllFieldsNames()); + fieldsToSelect.retainAll(new PaymentAndPaymentApplication().getAllFieldsNames()); EntityListBuilder paymentListBuilder = new EntityListBuilder(paymentRepository, PaymentAndPaymentApplication.class, EntityCondition.makeCondition(searchConditions, EntityOperator.AND), fieldsToSelect, UtilMisc.toList(PaymentAndPaymentApplication.Fields.effectiveDate.desc())); PageBuilder<PaymentAndPaymentApplication> pageBuilder = new PageBuilder<PaymentAndPaymentApplication>() { public List<Map<String, Object>> build(List<PaymentAndPaymentApplication> page) throws Exception { GenericDelegator delegator = ac.getDelegator(); List<Map<String, Object>> newPage = FastList.newInstance(); for (PaymentAndPaymentApplication payment : page) { Map<String, Object> newRow = FastMap.newInstance(); newRow.putAll(payment.toMap()); StatusItem status = payment.getStatusItem(); newRow.put("statusDescription", status.get(StatusItem.Fields.description.name(), locale)); PaymentMethodType meth = payment.getPaymentMethodType(); if (meth != null) { newRow.put("paymentMethodDescription", meth.get(PaymentMethodType.Fields.description.name(), locale)); } newRow.put("partyNameFrom", PartyHelper.getPartyName(delegator, payment.getPartyIdFrom(), false)); newRow.put("partyNameTo", PartyHelper.getPartyName(delegator, payment.getPartyIdTo(), false)); newPage.add(newRow); } return newPage; } }; paymentListBuilder.setPageBuilder(pageBuilder); ac.put("paymentListBuilder", paymentListBuilder); } }
true
true
public static void findPayments(Map<String, Object> context) throws GeneralException, ParseException { final ActionContext ac = new ActionContext(context); final HttpServletRequest request = ac.getRequest(); final GenericDelegator delegator = ac.getDelegator(); final Locale locale = ac.getLocale(); final TimeZone timeZone = ac.getTimeZone(); final String organizationPartyId = UtilCommon.getOrganizationPartyId(request); if (organizationPartyId == null) { Debug.logError("No organizationPartyId set in the current request.", MODULE); return; } ac.put("organizationPartyId", organizationPartyId); DomainsDirectory dd = DomainsDirectory.getDomainsDirectory(ac); BillingDomainInterface billingDomain = dd.getBillingDomain(); PaymentRepositoryInterface paymentRepository = billingDomain.getPaymentRepository(); OrganizationRepositoryInterface organizationRepository = dd.getOrganizationDomain().getOrganizationRepository(); Organization organization = organizationRepository.getOrganizationById(organizationPartyId); // this gets overrided later according to the payment type ac.put("decoratorLocation", "component://opentaps-common/widget/screens/common/CommonScreens.xml"); // set the disbursement flag which is used to set the partyIdFrom/To to that of the organization on the find payment form as a hidden field // also set a default status id which is based on whether it's a disbursement (SENT) or not (RECEIVED), but this is overriden by parameters.statusId ac.put("headerItem", "receivables"); // for accounting tag filtering String tagsType = UtilAccountingTags.LOOKUP_RECEIPT_PAYMENT_TAG; boolean findDisbursement = false; String findPaymentTypeId = ac.getParameter("findPaymentTypeId"); if ("DISBURSEMENT".equals(findPaymentTypeId)) { findDisbursement = true; tagsType = UtilAccountingTags.LOOKUP_DISBURSEMENT_PAYMENT_TAG; ac.put("headerItem", "payables"); } ac.put("findDisbursement", findDisbursement); // get the list of paymentMethods, PaymentMethodTypes, paymentTypes List<String> supportedPaymentTypes = null; if (findDisbursement) { ac.put("decoratorLocation", "component://financials/widget/financials/screens/payables/PayablesScreens.xml"); ac.put("headerItem", "payables"); ac.put("paymentMethodList", organization.getRelated(PaymentMethod.class, UtilMisc.toList("paymentMethodTypeId"))); supportedPaymentTypes = Arrays.asList(PaymentTypeConstants.Disbursement.CUSTOMER_REFUND, PaymentTypeConstants.Disbursement.VENDOR_PAYMENT, PaymentTypeConstants.Disbursement.VENDOR_PREPAY, PaymentTypeConstants.Disbursement.COMMISSION_PAYMENT, PaymentTypeConstants.TaxPayment.SALES_TAX_PAYMENT, PaymentTypeConstants.TaxPayment.INCOME_TAX_PAYMENT, PaymentTypeConstants.TaxPayment.PAYROLL_TAX_PAYMENT); } else { ac.put("decoratorLocation", "component://financials/widget/financials/screens/receivables/ReceivablesScreens.xml"); ac.put("headerItem", "receivables"); ac.put("paymentMethodTypeList", UtilFinancial.getSimpleCustomerPaymentMethodTypes(delegator)); supportedPaymentTypes = Arrays.asList(PaymentTypeConstants.Receipt.INTEREST_RECEIPT, PaymentTypeConstants.Receipt.VENDOR_CREDIT_RCPT, PaymentTypeConstants.Receipt.CUSTOMER_PAYMENT, PaymentTypeConstants.Receipt.CUSTOMER_DEPOSIT); } List<PaymentType> paymentTypeList = paymentRepository.findListCache(PaymentType.class, EntityCondition.makeCondition(PaymentType.Fields.paymentTypeId.name(), EntityOperator.IN, supportedPaymentTypes)); ac.put("paymentTypeList", paymentTypeList); List<StatusItem> statusList = paymentRepository.findListCache(StatusItem.class, paymentRepository.map(StatusItem.Fields.statusTypeId, StatusTypeConstants.PMNT_STATUS), UtilMisc.toList(StatusItem.Fields.sequenceId.desc())); ac.put("statusList", statusList); // get the accounting tags for the select inputs if (tagsType != null) { ac.put("tagFilters", UtilAccountingTags.getAccountingTagFiltersForOrganization(organizationPartyId, tagsType, delegator, locale)); } // possible fields we're searching by String paymentId = ac.getParameter("paymentId"); String partyIdFrom = ac.getParameter("partyIdFrom"); String partyIdTo = ac.getParameter("partyIdTo"); String paymentTypeId = ac.getParameter("paymentTypeId"); String paymentMethodId = ac.getParameter("paymentMethodId"); String paymentMethodTypeId = ac.getParameter("paymentMethodTypeId"); String paymentRefNum = ac.getParameter("paymentRefNum"); String statusId = ac.getParameter("statusId"); Timestamp fromDate = UtilDate.toTimestamp(ac.getCompositeParameter("fromDate"), timeZone, locale); Timestamp thruDate = UtilDate.toTimestamp(ac.getCompositeParameter("thruDate"), timeZone, locale); String amountFrom = ac.getParameter("amountFrom"); String amountThru = ac.getParameter("amountThru"); String openAmountFrom = ac.getParameter("openAmountFrom"); String openAmountThru = ac.getParameter("openAmountThru"); // construct search conditions List<EntityCondition> searchConditions = new FastList<EntityCondition>(); if (paymentId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentId.name(), EntityOperator.EQUALS, paymentId)); } // force one of the party to the organization according to the payment type if (findDisbursement) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdFrom.name(), EntityOperator.EQUALS, organizationPartyId)); if (partyIdTo != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdTo.name(), EntityOperator.EQUALS, partyIdTo)); } } else { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdTo.name(), EntityOperator.EQUALS, organizationPartyId)); if (partyIdFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdFrom.name(), EntityOperator.EQUALS, partyIdFrom)); } } if (paymentTypeId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentTypeId.name(), EntityOperator.EQUALS, paymentTypeId)); } else { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentTypeId.name(), EntityOperator.IN, supportedPaymentTypes)); } if (findDisbursement) { if (paymentMethodId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentMethodId.name(), EntityOperator.EQUALS, paymentMethodId)); } } else { if (paymentMethodTypeId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentMethodTypeId.name(), EntityOperator.EQUALS, paymentMethodTypeId)); } } if (paymentRefNum != null) { // make sure the look up is case insensitive searchConditions.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(Payment.Fields.paymentRefNum.name()), EntityOperator.LIKE, EntityFunction.UPPER(paymentRefNum + "%"))); } if (statusId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.statusId.name(), EntityOperator.EQUALS, statusId)); } if (fromDate != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.effectiveDate.name(), EntityOperator.GREATER_THAN_EQUAL_TO, fromDate)); } if (thruDate != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.effectiveDate.name(), EntityOperator.LESS_THAN_EQUAL_TO, thruDate)); } if (amountFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.amount.name(), EntityOperator.GREATER_THAN_EQUAL_TO, new BigDecimal(amountFrom))); } if (amountThru != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.amount.name(), EntityOperator.LESS_THAN_EQUAL_TO, new BigDecimal(amountThru))); } if (openAmountFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.openAmount.name(), EntityOperator.GREATER_THAN_EQUAL_TO, new BigDecimal(openAmountFrom))); } if (openAmountThru != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.openAmount.name(), EntityOperator.LESS_THAN_EQUAL_TO, new BigDecimal(openAmountThru))); } if (tagsType != null) { // if the organization is using allocatePaymentTagsToApplications then the tags are on the payment applications, // else they are on the Payments if (organization.allocatePaymentTagsToApplications()) { searchConditions.addAll(UtilAccountingTags.buildTagConditions(organizationPartyId, tagsType, delegator, request, UtilAccountingTags.TAG_PARAM_PREFIX, "applAcctgTagEnumId")); } else { searchConditions.addAll(UtilAccountingTags.buildTagConditions(organizationPartyId, tagsType, delegator, request)); } } // Pagination Set<String> fieldsToSelect = new HashSet<String>(new Payment().getAllFieldsNames()); EntityListBuilder paymentListBuilder = new EntityListBuilder(paymentRepository, PaymentAndPaymentApplication.class, EntityCondition.makeCondition(searchConditions, EntityOperator.AND), fieldsToSelect, UtilMisc.toList(PaymentAndPaymentApplication.Fields.effectiveDate.desc())); PageBuilder<PaymentAndPaymentApplication> pageBuilder = new PageBuilder<PaymentAndPaymentApplication>() { public List<Map<String, Object>> build(List<PaymentAndPaymentApplication> page) throws Exception { GenericDelegator delegator = ac.getDelegator(); List<Map<String, Object>> newPage = FastList.newInstance(); for (PaymentAndPaymentApplication payment : page) { Map<String, Object> newRow = FastMap.newInstance(); newRow.putAll(payment.toMap()); StatusItem status = payment.getStatusItem(); newRow.put("statusDescription", status.get(StatusItem.Fields.description.name(), locale)); PaymentMethodType meth = payment.getPaymentMethodType(); if (meth != null) { newRow.put("paymentMethodDescription", meth.get(PaymentMethodType.Fields.description.name(), locale)); } newRow.put("partyNameFrom", PartyHelper.getPartyName(delegator, payment.getPartyIdFrom(), false)); newRow.put("partyNameTo", PartyHelper.getPartyName(delegator, payment.getPartyIdTo(), false)); newPage.add(newRow); } return newPage; } }; paymentListBuilder.setPageBuilder(pageBuilder); ac.put("paymentListBuilder", paymentListBuilder); }
public static void findPayments(Map<String, Object> context) throws GeneralException, ParseException { final ActionContext ac = new ActionContext(context); final HttpServletRequest request = ac.getRequest(); final GenericDelegator delegator = ac.getDelegator(); final Locale locale = ac.getLocale(); final TimeZone timeZone = ac.getTimeZone(); final String organizationPartyId = UtilCommon.getOrganizationPartyId(request); if (organizationPartyId == null) { Debug.logError("No organizationPartyId set in the current request.", MODULE); return; } ac.put("organizationPartyId", organizationPartyId); DomainsDirectory dd = DomainsDirectory.getDomainsDirectory(ac); BillingDomainInterface billingDomain = dd.getBillingDomain(); PaymentRepositoryInterface paymentRepository = billingDomain.getPaymentRepository(); OrganizationRepositoryInterface organizationRepository = dd.getOrganizationDomain().getOrganizationRepository(); Organization organization = organizationRepository.getOrganizationById(organizationPartyId); // this gets overrided later according to the payment type ac.put("decoratorLocation", "component://opentaps-common/widget/screens/common/CommonScreens.xml"); // set the disbursement flag which is used to set the partyIdFrom/To to that of the organization on the find payment form as a hidden field // also set a default status id which is based on whether it's a disbursement (SENT) or not (RECEIVED), but this is overriden by parameters.statusId ac.put("headerItem", "receivables"); // for accounting tag filtering String tagsType = UtilAccountingTags.LOOKUP_RECEIPT_PAYMENT_TAG; boolean findDisbursement = false; String findPaymentTypeId = ac.getParameter("findPaymentTypeId"); if ("DISBURSEMENT".equals(findPaymentTypeId)) { findDisbursement = true; tagsType = UtilAccountingTags.LOOKUP_DISBURSEMENT_PAYMENT_TAG; ac.put("headerItem", "payables"); } ac.put("findDisbursement", findDisbursement); // get the list of paymentMethods, PaymentMethodTypes, paymentTypes List<String> supportedPaymentTypes = null; if (findDisbursement) { ac.put("decoratorLocation", "component://financials/widget/financials/screens/payables/PayablesScreens.xml"); ac.put("headerItem", "payables"); ac.put("paymentMethodList", organization.getRelated(PaymentMethod.class, UtilMisc.toList("paymentMethodTypeId"))); supportedPaymentTypes = Arrays.asList(PaymentTypeConstants.Disbursement.CUSTOMER_REFUND, PaymentTypeConstants.Disbursement.VENDOR_PAYMENT, PaymentTypeConstants.Disbursement.VENDOR_PREPAY, PaymentTypeConstants.Disbursement.COMMISSION_PAYMENT, PaymentTypeConstants.TaxPayment.SALES_TAX_PAYMENT, PaymentTypeConstants.TaxPayment.INCOME_TAX_PAYMENT, PaymentTypeConstants.TaxPayment.PAYROLL_TAX_PAYMENT); } else { ac.put("decoratorLocation", "component://financials/widget/financials/screens/receivables/ReceivablesScreens.xml"); ac.put("headerItem", "receivables"); ac.put("paymentMethodTypeList", UtilFinancial.getSimpleCustomerPaymentMethodTypes(delegator)); supportedPaymentTypes = Arrays.asList(PaymentTypeConstants.Receipt.INTEREST_RECEIPT, PaymentTypeConstants.Receipt.VENDOR_CREDIT_RCPT, PaymentTypeConstants.Receipt.CUSTOMER_PAYMENT, PaymentTypeConstants.Receipt.CUSTOMER_DEPOSIT); } List<PaymentType> paymentTypeList = paymentRepository.findListCache(PaymentType.class, EntityCondition.makeCondition(PaymentType.Fields.paymentTypeId.name(), EntityOperator.IN, supportedPaymentTypes)); ac.put("paymentTypeList", paymentTypeList); List<StatusItem> statusList = paymentRepository.findListCache(StatusItem.class, paymentRepository.map(StatusItem.Fields.statusTypeId, StatusTypeConstants.PMNT_STATUS), UtilMisc.toList(StatusItem.Fields.sequenceId.desc())); ac.put("statusList", statusList); // get the accounting tags for the select inputs if (tagsType != null) { ac.put("tagFilters", UtilAccountingTags.getAccountingTagFiltersForOrganization(organizationPartyId, tagsType, delegator, locale)); } // possible fields we're searching by String paymentId = ac.getParameter("paymentId"); String partyIdFrom = ac.getParameter("partyIdFrom"); String partyIdTo = ac.getParameter("partyIdTo"); String paymentTypeId = ac.getParameter("paymentTypeId"); String paymentMethodId = ac.getParameter("paymentMethodId"); String paymentMethodTypeId = ac.getParameter("paymentMethodTypeId"); String paymentRefNum = ac.getParameter("paymentRefNum"); String statusId = ac.getParameter("statusId"); Timestamp fromDate = UtilDate.toTimestamp(ac.getCompositeParameter("fromDate"), timeZone, locale); Timestamp thruDate = UtilDate.toTimestamp(ac.getCompositeParameter("thruDate"), timeZone, locale); String amountFrom = ac.getParameter("amountFrom"); String amountThru = ac.getParameter("amountThru"); String openAmountFrom = ac.getParameter("openAmountFrom"); String openAmountThru = ac.getParameter("openAmountThru"); // construct search conditions List<EntityCondition> searchConditions = new FastList<EntityCondition>(); if (paymentId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentId.name(), EntityOperator.EQUALS, paymentId)); } // force one of the party to the organization according to the payment type if (findDisbursement) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdFrom.name(), EntityOperator.EQUALS, organizationPartyId)); if (partyIdTo != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdTo.name(), EntityOperator.EQUALS, partyIdTo)); } } else { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdTo.name(), EntityOperator.EQUALS, organizationPartyId)); if (partyIdFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.partyIdFrom.name(), EntityOperator.EQUALS, partyIdFrom)); } } if (paymentTypeId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentTypeId.name(), EntityOperator.EQUALS, paymentTypeId)); } else { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentTypeId.name(), EntityOperator.IN, supportedPaymentTypes)); } if (findDisbursement) { if (paymentMethodId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentMethodId.name(), EntityOperator.EQUALS, paymentMethodId)); } } else { if (paymentMethodTypeId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.paymentMethodTypeId.name(), EntityOperator.EQUALS, paymentMethodTypeId)); } } if (paymentRefNum != null) { // make sure the look up is case insensitive searchConditions.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(Payment.Fields.paymentRefNum.name()), EntityOperator.LIKE, EntityFunction.UPPER(paymentRefNum + "%"))); } if (statusId != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.statusId.name(), EntityOperator.EQUALS, statusId)); } if (fromDate != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.effectiveDate.name(), EntityOperator.GREATER_THAN_EQUAL_TO, fromDate)); } if (thruDate != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.effectiveDate.name(), EntityOperator.LESS_THAN_EQUAL_TO, thruDate)); } if (amountFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.amount.name(), EntityOperator.GREATER_THAN_EQUAL_TO, new BigDecimal(amountFrom))); } if (amountThru != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.amount.name(), EntityOperator.LESS_THAN_EQUAL_TO, new BigDecimal(amountThru))); } if (openAmountFrom != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.openAmount.name(), EntityOperator.GREATER_THAN_EQUAL_TO, new BigDecimal(openAmountFrom))); } if (openAmountThru != null) { searchConditions.add(EntityCondition.makeCondition(Payment.Fields.openAmount.name(), EntityOperator.LESS_THAN_EQUAL_TO, new BigDecimal(openAmountThru))); } if (tagsType != null) { // if the organization is using allocatePaymentTagsToApplications then the tags are on the payment applications, // else they are on the Payments if (organization.allocatePaymentTagsToApplications()) { searchConditions.addAll(UtilAccountingTags.buildTagConditions(organizationPartyId, tagsType, delegator, request, UtilAccountingTags.TAG_PARAM_PREFIX, "applAcctgTagEnumId")); } else { searchConditions.addAll(UtilAccountingTags.buildTagConditions(organizationPartyId, tagsType, delegator, request)); } } // Pagination Set<String> fieldsToSelect = new HashSet<String>(new Payment().getAllFieldsNames()); fieldsToSelect.retainAll(new PaymentAndPaymentApplication().getAllFieldsNames()); EntityListBuilder paymentListBuilder = new EntityListBuilder(paymentRepository, PaymentAndPaymentApplication.class, EntityCondition.makeCondition(searchConditions, EntityOperator.AND), fieldsToSelect, UtilMisc.toList(PaymentAndPaymentApplication.Fields.effectiveDate.desc())); PageBuilder<PaymentAndPaymentApplication> pageBuilder = new PageBuilder<PaymentAndPaymentApplication>() { public List<Map<String, Object>> build(List<PaymentAndPaymentApplication> page) throws Exception { GenericDelegator delegator = ac.getDelegator(); List<Map<String, Object>> newPage = FastList.newInstance(); for (PaymentAndPaymentApplication payment : page) { Map<String, Object> newRow = FastMap.newInstance(); newRow.putAll(payment.toMap()); StatusItem status = payment.getStatusItem(); newRow.put("statusDescription", status.get(StatusItem.Fields.description.name(), locale)); PaymentMethodType meth = payment.getPaymentMethodType(); if (meth != null) { newRow.put("paymentMethodDescription", meth.get(PaymentMethodType.Fields.description.name(), locale)); } newRow.put("partyNameFrom", PartyHelper.getPartyName(delegator, payment.getPartyIdFrom(), false)); newRow.put("partyNameTo", PartyHelper.getPartyName(delegator, payment.getPartyIdTo(), false)); newPage.add(newRow); } return newPage; } }; paymentListBuilder.setPageBuilder(pageBuilder); ac.put("paymentListBuilder", paymentListBuilder); }
diff --git a/src/main/java/br/com/gm/model/Rover.java b/src/main/java/br/com/gm/model/Rover.java index fc41e4c..7abf954 100644 --- a/src/main/java/br/com/gm/model/Rover.java +++ b/src/main/java/br/com/gm/model/Rover.java @@ -1,165 +1,165 @@ package br.com.gm.model; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import br.com.gm.enumerated.Movement; import br.com.gm.enumerated.Orientation; import br.com.gm.exception.CreatingRoverException; import br.com.gm.exception.MovementInvalidException; import br.com.gm.exception.MovementNotFoundException; import br.com.gm.exception.OrientationNotFoundException; public class Rover { private Orientation orientation; private int coordenateX; private int coordenateY; private MarsRover marsRover; private Logger logger = LogManager.getLogger(Rover.class); public Rover(int coordenateX, int coordenateY, char orientation, MarsRover marsRover) throws CreatingRoverException { super(); try{ this.orientation = Orientation.getOrientation(orientation); this.coordenateX = coordenateX; this.coordenateY = coordenateY; this.marsRover = marsRover; } catch (OrientationNotFoundException e) { throw new CreatingRoverException(e.getMessage()); } } public Orientation getOrientation() { return orientation; } public void setOrientation(Orientation orientation) { this.orientation = orientation; } public int getCoordenateX() { return coordenateX; } public void setCoordenateX(int coordenateX) { this.coordenateX = coordenateX; } public int getCoordenateY() { return coordenateY; } public void setCoordenateY(int coordenateY) { this.coordenateY = coordenateY; } public void processCommand(String command) throws MovementNotFoundException{ //TODO treat the exception for MOVE error char[] commandArray = command.toCharArray(); for (char aCommand : commandArray){ Movement movement = Movement.getMovement(aCommand); switch (movement) { case LEFT: rotateLeft(getOrientation()); break; case RIGHT: rotateRight(getOrientation()); break; case MIDDLE: try{ moveForward(getOrientation()); } catch (MovementInvalidException e) { logger.error(e.getMessage()); } break; default: break; } } } public String getPosition(){ StringBuilder sb = new StringBuilder(); sb.append(coordenateX); sb.append(" "); sb.append(coordenateY); sb.append(" "); sb.append(this.orientation.toString().charAt(0)); return sb.toString(); } private void rotateLeft(Orientation orientation){ switch (orientation) { case NORTH: setOrientation(Orientation.WEST); break; case WEST: setOrientation(Orientation.SOUTH); break; case EAST: setOrientation(Orientation.NORTH); break; case SOUTH: setOrientation(Orientation.EAST); break; default: break; } } private void rotateRight(Orientation orientation){ switch (orientation) { case NORTH: setOrientation(Orientation.EAST); break; case WEST: setOrientation(Orientation.NORTH); break; case EAST: setOrientation(Orientation.SOUTH); break; case SOUTH: setOrientation(Orientation.WEST); break; default: break; } } private void moveForward(Orientation orientation) throws MovementInvalidException{ //TODO check MarsRover space and throw exception switch (orientation) { case NORTH: if(marsRover.getMaxCoordenateY() > getCoordenateY()) setCoordenateY(getCoordenateY() + 1); else throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED); break; case WEST: if(marsRover.getMinCoordenateX() < getCoordenateX()) setCoordenateX(getCoordenateX() - 1); else throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED); break; case EAST: - if(marsRover.getMaxCoordenateX() < getCoordenateX()) + if(marsRover.getMaxCoordenateX() > getCoordenateX()) setCoordenateX(getCoordenateX() + 1); else throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED); break; case SOUTH: if(marsRover.getMinCoordenateY() < getCoordenateY()) setCoordenateY(getCoordenateY() - 1); else throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED); break; default: break; } } }
true
true
private void moveForward(Orientation orientation) throws MovementInvalidException{ //TODO check MarsRover space and throw exception switch (orientation) { case NORTH: if(marsRover.getMaxCoordenateY() > getCoordenateY()) setCoordenateY(getCoordenateY() + 1); else throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED); break; case WEST: if(marsRover.getMinCoordenateX() < getCoordenateX()) setCoordenateX(getCoordenateX() - 1); else throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED); break; case EAST: if(marsRover.getMaxCoordenateX() < getCoordenateX()) setCoordenateX(getCoordenateX() + 1); else throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED); break; case SOUTH: if(marsRover.getMinCoordenateY() < getCoordenateY()) setCoordenateY(getCoordenateY() - 1); else throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED); break; default: break; } }
private void moveForward(Orientation orientation) throws MovementInvalidException{ //TODO check MarsRover space and throw exception switch (orientation) { case NORTH: if(marsRover.getMaxCoordenateY() > getCoordenateY()) setCoordenateY(getCoordenateY() + 1); else throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED); break; case WEST: if(marsRover.getMinCoordenateX() < getCoordenateX()) setCoordenateX(getCoordenateX() - 1); else throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED); break; case EAST: if(marsRover.getMaxCoordenateX() > getCoordenateX()) setCoordenateX(getCoordenateX() + 1); else throw new MovementInvalidException(MovementInvalidException.MAX_POSITION_ALREADY_REACHED); break; case SOUTH: if(marsRover.getMinCoordenateY() < getCoordenateY()) setCoordenateY(getCoordenateY() - 1); else throw new MovementInvalidException(MovementInvalidException.MIN_POSITION_ALREADY_REACHED); break; default: break; } }
diff --git a/src/main/java/de/chrfritz/jolokiamunin/daemon/Client.java b/src/main/java/de/chrfritz/jolokiamunin/daemon/Client.java index 8f4dc8d..54a0ae0 100644 --- a/src/main/java/de/chrfritz/jolokiamunin/daemon/Client.java +++ b/src/main/java/de/chrfritz/jolokiamunin/daemon/Client.java @@ -1,86 +1,86 @@ // ______________________________________________________________________________ // // Project: jolokia-munin-plugin // Module: jolokia-munin-plugin // Class: Client // File: Client.java // changed by: christian // change date: 23.04.13 19:06 // description: // ______________________________________________________________________________ // // Copyright: (c) Christian Fritz, all rights reserved // ______________________________________________________________________________ package de.chrfritz.jolokiamunin.daemon; import de.chrfritz.jolokiamunin.config.Configuration; import de.chrfritz.jolokiamunin.controller.Dispatcher; import de.chrfritz.jolokiamunin.munin.MuninProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.charset.Charset; public class Client implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Client.class); private static final int SOCKET_TIMEOUT = 1000 * 15; private final Socket clientSocket; private final Configuration configuration; private final MuninProvider muninProvider; private final Charset charset = Charset.forName("UTF-8"); public Client(Socket clientSocket, MuninProvider muninProvider, Configuration configuration) { this.muninProvider = muninProvider; this.configuration = configuration; this.clientSocket = clientSocket; LOGGER.info("Connection accepted from {}", clientSocket.getRemoteSocketAddress()); } /** * @see Thread#run() */ @Override public void run() { try ( Socket socket = clientSocket; BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)) ) { socket.setSoTimeout(SOCKET_TIMEOUT); while (!Thread.interrupted()) { - String command = reader.readLine().trim(); - String response = handleCommands(command); + String command = reader.readLine(); + String response = handleCommands(command.trim()); writer.write(response); writer.flush(); } } catch (SocketTimeoutException e) { LOGGER.info("Closing connection because of read timeout"); } catch (IOException e) { LOGGER.error("Can not open streams", e); } } protected String handleCommands(String commandLine) { String[] parts = commandLine.split("[\n ]+", 2); String command = parts[0]; switch (command) { case "quit": case "exit": Thread.currentThread().interrupt(); return ""; default: Dispatcher dispatcher = new Dispatcher(configuration, muninProvider); return dispatcher.handleRequest(commandLine) + "\n"; } } }
true
true
public void run() { try ( Socket socket = clientSocket; BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)) ) { socket.setSoTimeout(SOCKET_TIMEOUT); while (!Thread.interrupted()) { String command = reader.readLine().trim(); String response = handleCommands(command); writer.write(response); writer.flush(); } } catch (SocketTimeoutException e) { LOGGER.info("Closing connection because of read timeout"); } catch (IOException e) { LOGGER.error("Can not open streams", e); } }
public void run() { try ( Socket socket = clientSocket; BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset)) ) { socket.setSoTimeout(SOCKET_TIMEOUT); while (!Thread.interrupted()) { String command = reader.readLine(); String response = handleCommands(command.trim()); writer.write(response); writer.flush(); } } catch (SocketTimeoutException e) { LOGGER.info("Closing connection because of read timeout"); } catch (IOException e) { LOGGER.error("Can not open streams", e); } }
diff --git a/core/src/main/java/org/apache/mahout/cf/taste/hadoop/item/RecommenderJob.java b/core/src/main/java/org/apache/mahout/cf/taste/hadoop/item/RecommenderJob.java index bcbb741e3..983374ff3 100644 --- a/core/src/main/java/org/apache/mahout/cf/taste/hadoop/item/RecommenderJob.java +++ b/core/src/main/java/org/apache/mahout/cf/taste/hadoop/item/RecommenderJob.java @@ -1,302 +1,302 @@ /* * 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.mahout.cf.taste.hadoop.item; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.ToolRunner; import org.apache.mahout.cf.taste.hadoop.EntityPrefWritable; import org.apache.mahout.cf.taste.hadoop.MaybePruneRowsMapper; import org.apache.mahout.cf.taste.hadoop.RecommendedItemsWritable; import org.apache.mahout.cf.taste.hadoop.ToItemPrefsMapper; import org.apache.mahout.cf.taste.hadoop.similarity.item.ToItemVectorsReducer; import org.apache.mahout.common.AbstractJob; import org.apache.mahout.math.VarIntWritable; import org.apache.mahout.math.VarLongWritable; import org.apache.mahout.math.VectorWritable; import org.apache.mahout.math.hadoop.DistributedRowMatrix; import org.apache.mahout.math.hadoop.similarity.RowSimilarityJob; import org.apache.mahout.math.hadoop.similarity.SimilarityType; import java.io.IOException; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p>Runs a completely distributed recommender job as a series of mapreduces.</p> * * <p>Preferences in the input file should look like {@code userID,itemID[,preferencevalue]}</p> * * <p> * Preference value is optional to accommodate applications that have no notion of a preference value (that is, the user * simply expresses a preference for an item, but no degree of preference). * </p> * * <p> * The preference value is assumed to be parseable as a {@code double}. The user IDs and item IDs are * parsed as {@code long}s. * </p> * * <p>Command line arguments specific to this class are:</p> * * <ol> * <li>-Dmapred.input.dir=(path): Directory containing one or more text files with the preference data</li> * <li>-Dmapred.output.dir=(path): output path where recommender output should go</li> * <li>--similarityClassname (classname): Name of distributed similarity class to instantiate or a predefined similarity * from {@link SimilarityType}</li> * <li>--usersFile (path): only compute recommendations for user IDs contained in this file (optional)</li> * <li>--itemsFile (path): only include item IDs from this file in the recommendations (optional)</li> * <li>--filterFile (path): file containing comma-separated userID,itemID pairs. Used to exclude the item from the * recommendations for that user (optional)</li> * <li>--numRecommendations (integer): Number of recommendations to compute per user (10)</li> * <li>--booleanData (boolean): Treat input data as having no pref values (false)</li> * <li>--maxPrefsPerUser (integer): Maximum number of preferences considered per user in * final recommendation phase (10)</li> * <li>--maxSimilaritiesPerItem (integer): Maximum number of similarities considered per item (100)</li> * <li>--maxCooccurrencesPerItem (integer): Maximum number of cooccurrences considered per item (100)</li> * </ol> * * <p>General command line options are documented in {@link AbstractJob}.</p> * * <p>Note that because of how Hadoop parses arguments, all "-D" arguments must appear before all other * arguments.</p> */ public final class RecommenderJob extends AbstractJob { public static final String BOOLEAN_DATA = "booleanData"; private static final int DEFAULT_MAX_SIMILARITIES_PER_ITEM = 100; private static final int DEFAULT_MAX_COOCCURRENCES_PER_ITEM = 100; private static final int DEFAULT_MIN_PREFS_PER_USER = 1; @Override public int run(String[] args) throws IOException, ClassNotFoundException, InterruptedException { addInputOption(); addOutputOption(); addOption("numRecommendations", "n", "Number of recommendations per user", String.valueOf(AggregateAndRecommendReducer.DEFAULT_NUM_RECOMMENDATIONS)); addOption("usersFile", "u", "File of users to recommend for", null); addOption("itemsFile", "i", "File of items to recommend for", null); addOption("filterFile", "f", "File containing comma-separated userID,itemID pairs. Used to exclude the item from " + "the recommendations for that user (optional)", null); addOption("booleanData", "b", "Treat input as without pref values", Boolean.FALSE.toString()); - addOption("maxPrefsPerUser", "mp", + addOption("maxPrefsPerUser", "mxp", "Maximum number of preferences considered per user in final recommendation phase", String.valueOf(UserVectorSplitterMapper.DEFAULT_MAX_PREFS_PER_USER_CONSIDERED)); addOption("minPrefsPerUser", "mp", "ignore users with less preferences than this in the similarity computation " + "(default: " + DEFAULT_MIN_PREFS_PER_USER + ')', String.valueOf(DEFAULT_MIN_PREFS_PER_USER)); addOption("maxSimilaritiesPerItem", "m", "Maximum number of similarities considered per item ", String.valueOf(DEFAULT_MAX_SIMILARITIES_PER_ITEM)); addOption("maxCooccurrencesPerItem", "mo", "try to cap the number of cooccurrences per item to this " + "number (default: " + DEFAULT_MAX_COOCCURRENCES_PER_ITEM + ')', String.valueOf(DEFAULT_MAX_COOCCURRENCES_PER_ITEM)); addOption("similarityClassname", "s", "Name of distributed similarity class to instantiate, alternatively use " + "one of the predefined similarities (" + SimilarityType.listEnumNames() + ')', String.valueOf(SimilarityType.SIMILARITY_COOCCURRENCE)); Map<String,String> parsedArgs = parseArguments(args); if (parsedArgs == null) { return -1; } Path inputPath = getInputPath(); Path outputPath = getOutputPath(); int numRecommendations = Integer.parseInt(parsedArgs.get("--numRecommendations")); String usersFile = parsedArgs.get("--usersFile"); String itemsFile = parsedArgs.get("--itemsFile"); String filterFile = parsedArgs.get("--filterFile"); boolean booleanData = Boolean.valueOf(parsedArgs.get("--booleanData")); int maxPrefsPerUser = Integer.parseInt(parsedArgs.get("--maxPrefsPerUser")); int minPrefsPerUser = Integer.parseInt(parsedArgs.get("--minPrefsPerUser")); int maxSimilaritiesPerItem = Integer.parseInt(parsedArgs.get("--maxSimilaritiesPerItem")); int maxCooccurrencesPerItem = Integer.parseInt(parsedArgs.get("--maxCooccurrencesPerItem")); String similarityClassname = parsedArgs.get("--similarityClassname"); Path userVectorPath = getTempPath("userVectors"); Path itemIDIndexPath = getTempPath("itemIDIndex"); Path countUsersPath = getTempPath("countUsers"); Path itemUserMatrixPath = getTempPath("itemUserMatrix"); Path similarityMatrixPath = getTempPath("similarityMatrix"); Path prePartialMultiplyPath1 = getTempPath("prePartialMultiply1"); Path prePartialMultiplyPath2 = getTempPath("prePartialMultiply2"); Path explicitFilterPath = getTempPath("explicitFilterPath"); Path partialMultiplyPath = getTempPath("partialMultiply"); AtomicInteger currentPhase = new AtomicInteger(); if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job itemIDIndex = prepareJob( inputPath, itemIDIndexPath, TextInputFormat.class, ItemIDIndexMapper.class, VarIntWritable.class, VarLongWritable.class, ItemIDIndexReducer.class, VarIntWritable.class, VarLongWritable.class, SequenceFileOutputFormat.class); itemIDIndex.setCombinerClass(ItemIDIndexReducer.class); itemIDIndex.waitForCompletion(true); } int numberOfUsers = 0; if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job toUserVector = prepareJob( inputPath, userVectorPath, TextInputFormat.class, ToItemPrefsMapper.class, VarLongWritable.class, booleanData ? VarLongWritable.class : EntityPrefWritable.class, ToUserVectorReducer.class, VarLongWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); toUserVector.getConfiguration().setBoolean(BOOLEAN_DATA, booleanData); toUserVector.getConfiguration().setInt(ToUserVectorReducer.MIN_PREFERENCES_PER_USER, minPrefsPerUser); toUserVector.waitForCompletion(true); numberOfUsers = (int) toUserVector.getCounters().findCounter(ToUserVectorReducer.Counters.USERS).getValue(); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job maybePruneAndTransponse = prepareJob(userVectorPath, itemUserMatrixPath, SequenceFileInputFormat.class, MaybePruneRowsMapper.class, IntWritable.class, DistributedRowMatrix.MatrixEntryWritable.class, ToItemVectorsReducer.class, IntWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); maybePruneAndTransponse.getConfiguration().setInt(MaybePruneRowsMapper.MAX_COOCCURRENCES, maxCooccurrencesPerItem); maybePruneAndTransponse.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { /* Once DistributedRowMatrix uses the hadoop 0.20 API, we should refactor this call to something like * new DistributedRowMatrix(...).rowSimilarity(...) */ try { ToolRunner.run(getConf(), new RowSimilarityJob(), new String[] { "-Dmapred.input.dir=" + itemUserMatrixPath, "-Dmapred.output.dir=" + similarityMatrixPath, "--numberOfColumns", String.valueOf(numberOfUsers), "--similarityClassname", similarityClassname, "--maxSimilaritiesPerRow", String.valueOf(maxSimilaritiesPerItem + 1), "--tempDir", getTempPath().toString() }); } catch (Exception e) { throw new IllegalStateException("item-item-similarity computation failed", e); } } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job prePartialMultiply1 = prepareJob( similarityMatrixPath, prePartialMultiplyPath1, SequenceFileInputFormat.class, SimilarityMatrixRowWrapperMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); prePartialMultiply1.waitForCompletion(true); Job prePartialMultiply2 = prepareJob( userVectorPath, prePartialMultiplyPath2, SequenceFileInputFormat.class, UserVectorSplitterMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); if (usersFile != null) { prePartialMultiply2.getConfiguration().set(UserVectorSplitterMapper.USERS_FILE, usersFile); } prePartialMultiply2.getConfiguration().setInt(UserVectorSplitterMapper.MAX_PREFS_PER_USER_CONSIDERED, maxPrefsPerUser); prePartialMultiply2.waitForCompletion(true); Job partialMultiply = prepareJob( new Path(prePartialMultiplyPath1 + "," + prePartialMultiplyPath2), partialMultiplyPath, SequenceFileInputFormat.class, Mapper.class, VarIntWritable.class, VectorOrPrefWritable.class, ToVectorAndPrefReducer.class, VarIntWritable.class, VectorAndPrefsWritable.class, SequenceFileOutputFormat.class); setS3SafeCombinedInputPath(partialMultiply, getTempPath(), prePartialMultiplyPath1, prePartialMultiplyPath2); partialMultiply.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { /* convert the user/item pairs to filter if a filterfile has been specified */ if (filterFile != null) { Job itemFiltering = prepareJob(new Path(filterFile), explicitFilterPath, TextInputFormat.class, ItemFilterMapper.class, VarLongWritable.class, VarLongWritable.class, ItemFilterAsVectorAndPrefsReducer.class, VarIntWritable.class, VectorAndPrefsWritable.class, SequenceFileOutputFormat.class); itemFiltering.waitForCompletion(true); } String aggregateAndRecommendInput = partialMultiplyPath.toString(); if (filterFile != null) { aggregateAndRecommendInput += "," + explicitFilterPath; } Job aggregateAndRecommend = prepareJob( new Path(aggregateAndRecommendInput), outputPath, SequenceFileInputFormat.class, PartialMultiplyMapper.class, VarLongWritable.class, PrefAndSimilarityColumnWritable.class, AggregateAndRecommendReducer.class, VarLongWritable.class, RecommendedItemsWritable.class, TextOutputFormat.class); Configuration aggregateAndRecommendConf = aggregateAndRecommend.getConfiguration(); if (itemsFile != null) { aggregateAndRecommendConf.set(AggregateAndRecommendReducer.ITEMS_FILE, itemsFile); } if (filterFile != null) { setS3SafeCombinedInputPath(aggregateAndRecommend, getTempPath(), partialMultiplyPath, explicitFilterPath); } setIOSort(aggregateAndRecommend); aggregateAndRecommendConf.set(AggregateAndRecommendReducer.ITEMID_INDEX_PATH, itemIDIndexPath.toString()); aggregateAndRecommendConf.setInt(AggregateAndRecommendReducer.NUM_RECOMMENDATIONS, numRecommendations); aggregateAndRecommendConf.setBoolean(BOOLEAN_DATA, booleanData); aggregateAndRecommend.waitForCompletion(true); } return 0; } private static void setIOSort(JobContext job) { Configuration conf = job.getConfiguration(); conf.setInt("io.sort.factor", 100); int assumedHeapSize = 512; String javaOpts = conf.get("mapred.child.java.opts"); if (javaOpts != null) { Matcher m = Pattern.compile("-Xmx([0-9]+)([mMgG])").matcher(javaOpts); if (m.find()) { assumedHeapSize = Integer.parseInt(m.group(1)); String megabyteOrGigabyte = m.group(2); if ("g".equalsIgnoreCase(megabyteOrGigabyte)) { assumedHeapSize *= 1024; } } } conf.setInt("io.sort.mb", assumedHeapSize / 2); // For some reason the Merger doesn't report status for a long time; increase // timeout when running these jobs conf.setInt("mapred.task.timeout", 60 * 60 * 1000); } public static void main(String[] args) throws Exception { ToolRunner.run(new Configuration(), new RecommenderJob(), args); } }
true
true
public int run(String[] args) throws IOException, ClassNotFoundException, InterruptedException { addInputOption(); addOutputOption(); addOption("numRecommendations", "n", "Number of recommendations per user", String.valueOf(AggregateAndRecommendReducer.DEFAULT_NUM_RECOMMENDATIONS)); addOption("usersFile", "u", "File of users to recommend for", null); addOption("itemsFile", "i", "File of items to recommend for", null); addOption("filterFile", "f", "File containing comma-separated userID,itemID pairs. Used to exclude the item from " + "the recommendations for that user (optional)", null); addOption("booleanData", "b", "Treat input as without pref values", Boolean.FALSE.toString()); addOption("maxPrefsPerUser", "mp", "Maximum number of preferences considered per user in final recommendation phase", String.valueOf(UserVectorSplitterMapper.DEFAULT_MAX_PREFS_PER_USER_CONSIDERED)); addOption("minPrefsPerUser", "mp", "ignore users with less preferences than this in the similarity computation " + "(default: " + DEFAULT_MIN_PREFS_PER_USER + ')', String.valueOf(DEFAULT_MIN_PREFS_PER_USER)); addOption("maxSimilaritiesPerItem", "m", "Maximum number of similarities considered per item ", String.valueOf(DEFAULT_MAX_SIMILARITIES_PER_ITEM)); addOption("maxCooccurrencesPerItem", "mo", "try to cap the number of cooccurrences per item to this " + "number (default: " + DEFAULT_MAX_COOCCURRENCES_PER_ITEM + ')', String.valueOf(DEFAULT_MAX_COOCCURRENCES_PER_ITEM)); addOption("similarityClassname", "s", "Name of distributed similarity class to instantiate, alternatively use " + "one of the predefined similarities (" + SimilarityType.listEnumNames() + ')', String.valueOf(SimilarityType.SIMILARITY_COOCCURRENCE)); Map<String,String> parsedArgs = parseArguments(args); if (parsedArgs == null) { return -1; } Path inputPath = getInputPath(); Path outputPath = getOutputPath(); int numRecommendations = Integer.parseInt(parsedArgs.get("--numRecommendations")); String usersFile = parsedArgs.get("--usersFile"); String itemsFile = parsedArgs.get("--itemsFile"); String filterFile = parsedArgs.get("--filterFile"); boolean booleanData = Boolean.valueOf(parsedArgs.get("--booleanData")); int maxPrefsPerUser = Integer.parseInt(parsedArgs.get("--maxPrefsPerUser")); int minPrefsPerUser = Integer.parseInt(parsedArgs.get("--minPrefsPerUser")); int maxSimilaritiesPerItem = Integer.parseInt(parsedArgs.get("--maxSimilaritiesPerItem")); int maxCooccurrencesPerItem = Integer.parseInt(parsedArgs.get("--maxCooccurrencesPerItem")); String similarityClassname = parsedArgs.get("--similarityClassname"); Path userVectorPath = getTempPath("userVectors"); Path itemIDIndexPath = getTempPath("itemIDIndex"); Path countUsersPath = getTempPath("countUsers"); Path itemUserMatrixPath = getTempPath("itemUserMatrix"); Path similarityMatrixPath = getTempPath("similarityMatrix"); Path prePartialMultiplyPath1 = getTempPath("prePartialMultiply1"); Path prePartialMultiplyPath2 = getTempPath("prePartialMultiply2"); Path explicitFilterPath = getTempPath("explicitFilterPath"); Path partialMultiplyPath = getTempPath("partialMultiply"); AtomicInteger currentPhase = new AtomicInteger(); if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job itemIDIndex = prepareJob( inputPath, itemIDIndexPath, TextInputFormat.class, ItemIDIndexMapper.class, VarIntWritable.class, VarLongWritable.class, ItemIDIndexReducer.class, VarIntWritable.class, VarLongWritable.class, SequenceFileOutputFormat.class); itemIDIndex.setCombinerClass(ItemIDIndexReducer.class); itemIDIndex.waitForCompletion(true); } int numberOfUsers = 0; if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job toUserVector = prepareJob( inputPath, userVectorPath, TextInputFormat.class, ToItemPrefsMapper.class, VarLongWritable.class, booleanData ? VarLongWritable.class : EntityPrefWritable.class, ToUserVectorReducer.class, VarLongWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); toUserVector.getConfiguration().setBoolean(BOOLEAN_DATA, booleanData); toUserVector.getConfiguration().setInt(ToUserVectorReducer.MIN_PREFERENCES_PER_USER, minPrefsPerUser); toUserVector.waitForCompletion(true); numberOfUsers = (int) toUserVector.getCounters().findCounter(ToUserVectorReducer.Counters.USERS).getValue(); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job maybePruneAndTransponse = prepareJob(userVectorPath, itemUserMatrixPath, SequenceFileInputFormat.class, MaybePruneRowsMapper.class, IntWritable.class, DistributedRowMatrix.MatrixEntryWritable.class, ToItemVectorsReducer.class, IntWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); maybePruneAndTransponse.getConfiguration().setInt(MaybePruneRowsMapper.MAX_COOCCURRENCES, maxCooccurrencesPerItem); maybePruneAndTransponse.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { /* Once DistributedRowMatrix uses the hadoop 0.20 API, we should refactor this call to something like * new DistributedRowMatrix(...).rowSimilarity(...) */ try { ToolRunner.run(getConf(), new RowSimilarityJob(), new String[] { "-Dmapred.input.dir=" + itemUserMatrixPath, "-Dmapred.output.dir=" + similarityMatrixPath, "--numberOfColumns", String.valueOf(numberOfUsers), "--similarityClassname", similarityClassname, "--maxSimilaritiesPerRow", String.valueOf(maxSimilaritiesPerItem + 1), "--tempDir", getTempPath().toString() }); } catch (Exception e) { throw new IllegalStateException("item-item-similarity computation failed", e); } } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job prePartialMultiply1 = prepareJob( similarityMatrixPath, prePartialMultiplyPath1, SequenceFileInputFormat.class, SimilarityMatrixRowWrapperMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); prePartialMultiply1.waitForCompletion(true); Job prePartialMultiply2 = prepareJob( userVectorPath, prePartialMultiplyPath2, SequenceFileInputFormat.class, UserVectorSplitterMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); if (usersFile != null) { prePartialMultiply2.getConfiguration().set(UserVectorSplitterMapper.USERS_FILE, usersFile); } prePartialMultiply2.getConfiguration().setInt(UserVectorSplitterMapper.MAX_PREFS_PER_USER_CONSIDERED, maxPrefsPerUser); prePartialMultiply2.waitForCompletion(true); Job partialMultiply = prepareJob( new Path(prePartialMultiplyPath1 + "," + prePartialMultiplyPath2), partialMultiplyPath, SequenceFileInputFormat.class, Mapper.class, VarIntWritable.class, VectorOrPrefWritable.class, ToVectorAndPrefReducer.class, VarIntWritable.class, VectorAndPrefsWritable.class, SequenceFileOutputFormat.class); setS3SafeCombinedInputPath(partialMultiply, getTempPath(), prePartialMultiplyPath1, prePartialMultiplyPath2); partialMultiply.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { /* convert the user/item pairs to filter if a filterfile has been specified */ if (filterFile != null) { Job itemFiltering = prepareJob(new Path(filterFile), explicitFilterPath, TextInputFormat.class, ItemFilterMapper.class, VarLongWritable.class, VarLongWritable.class, ItemFilterAsVectorAndPrefsReducer.class, VarIntWritable.class, VectorAndPrefsWritable.class, SequenceFileOutputFormat.class); itemFiltering.waitForCompletion(true); } String aggregateAndRecommendInput = partialMultiplyPath.toString(); if (filterFile != null) { aggregateAndRecommendInput += "," + explicitFilterPath; } Job aggregateAndRecommend = prepareJob( new Path(aggregateAndRecommendInput), outputPath, SequenceFileInputFormat.class, PartialMultiplyMapper.class, VarLongWritable.class, PrefAndSimilarityColumnWritable.class, AggregateAndRecommendReducer.class, VarLongWritable.class, RecommendedItemsWritable.class, TextOutputFormat.class); Configuration aggregateAndRecommendConf = aggregateAndRecommend.getConfiguration(); if (itemsFile != null) { aggregateAndRecommendConf.set(AggregateAndRecommendReducer.ITEMS_FILE, itemsFile); } if (filterFile != null) { setS3SafeCombinedInputPath(aggregateAndRecommend, getTempPath(), partialMultiplyPath, explicitFilterPath); } setIOSort(aggregateAndRecommend); aggregateAndRecommendConf.set(AggregateAndRecommendReducer.ITEMID_INDEX_PATH, itemIDIndexPath.toString()); aggregateAndRecommendConf.setInt(AggregateAndRecommendReducer.NUM_RECOMMENDATIONS, numRecommendations); aggregateAndRecommendConf.setBoolean(BOOLEAN_DATA, booleanData); aggregateAndRecommend.waitForCompletion(true); } return 0; }
public int run(String[] args) throws IOException, ClassNotFoundException, InterruptedException { addInputOption(); addOutputOption(); addOption("numRecommendations", "n", "Number of recommendations per user", String.valueOf(AggregateAndRecommendReducer.DEFAULT_NUM_RECOMMENDATIONS)); addOption("usersFile", "u", "File of users to recommend for", null); addOption("itemsFile", "i", "File of items to recommend for", null); addOption("filterFile", "f", "File containing comma-separated userID,itemID pairs. Used to exclude the item from " + "the recommendations for that user (optional)", null); addOption("booleanData", "b", "Treat input as without pref values", Boolean.FALSE.toString()); addOption("maxPrefsPerUser", "mxp", "Maximum number of preferences considered per user in final recommendation phase", String.valueOf(UserVectorSplitterMapper.DEFAULT_MAX_PREFS_PER_USER_CONSIDERED)); addOption("minPrefsPerUser", "mp", "ignore users with less preferences than this in the similarity computation " + "(default: " + DEFAULT_MIN_PREFS_PER_USER + ')', String.valueOf(DEFAULT_MIN_PREFS_PER_USER)); addOption("maxSimilaritiesPerItem", "m", "Maximum number of similarities considered per item ", String.valueOf(DEFAULT_MAX_SIMILARITIES_PER_ITEM)); addOption("maxCooccurrencesPerItem", "mo", "try to cap the number of cooccurrences per item to this " + "number (default: " + DEFAULT_MAX_COOCCURRENCES_PER_ITEM + ')', String.valueOf(DEFAULT_MAX_COOCCURRENCES_PER_ITEM)); addOption("similarityClassname", "s", "Name of distributed similarity class to instantiate, alternatively use " + "one of the predefined similarities (" + SimilarityType.listEnumNames() + ')', String.valueOf(SimilarityType.SIMILARITY_COOCCURRENCE)); Map<String,String> parsedArgs = parseArguments(args); if (parsedArgs == null) { return -1; } Path inputPath = getInputPath(); Path outputPath = getOutputPath(); int numRecommendations = Integer.parseInt(parsedArgs.get("--numRecommendations")); String usersFile = parsedArgs.get("--usersFile"); String itemsFile = parsedArgs.get("--itemsFile"); String filterFile = parsedArgs.get("--filterFile"); boolean booleanData = Boolean.valueOf(parsedArgs.get("--booleanData")); int maxPrefsPerUser = Integer.parseInt(parsedArgs.get("--maxPrefsPerUser")); int minPrefsPerUser = Integer.parseInt(parsedArgs.get("--minPrefsPerUser")); int maxSimilaritiesPerItem = Integer.parseInt(parsedArgs.get("--maxSimilaritiesPerItem")); int maxCooccurrencesPerItem = Integer.parseInt(parsedArgs.get("--maxCooccurrencesPerItem")); String similarityClassname = parsedArgs.get("--similarityClassname"); Path userVectorPath = getTempPath("userVectors"); Path itemIDIndexPath = getTempPath("itemIDIndex"); Path countUsersPath = getTempPath("countUsers"); Path itemUserMatrixPath = getTempPath("itemUserMatrix"); Path similarityMatrixPath = getTempPath("similarityMatrix"); Path prePartialMultiplyPath1 = getTempPath("prePartialMultiply1"); Path prePartialMultiplyPath2 = getTempPath("prePartialMultiply2"); Path explicitFilterPath = getTempPath("explicitFilterPath"); Path partialMultiplyPath = getTempPath("partialMultiply"); AtomicInteger currentPhase = new AtomicInteger(); if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job itemIDIndex = prepareJob( inputPath, itemIDIndexPath, TextInputFormat.class, ItemIDIndexMapper.class, VarIntWritable.class, VarLongWritable.class, ItemIDIndexReducer.class, VarIntWritable.class, VarLongWritable.class, SequenceFileOutputFormat.class); itemIDIndex.setCombinerClass(ItemIDIndexReducer.class); itemIDIndex.waitForCompletion(true); } int numberOfUsers = 0; if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job toUserVector = prepareJob( inputPath, userVectorPath, TextInputFormat.class, ToItemPrefsMapper.class, VarLongWritable.class, booleanData ? VarLongWritable.class : EntityPrefWritable.class, ToUserVectorReducer.class, VarLongWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); toUserVector.getConfiguration().setBoolean(BOOLEAN_DATA, booleanData); toUserVector.getConfiguration().setInt(ToUserVectorReducer.MIN_PREFERENCES_PER_USER, minPrefsPerUser); toUserVector.waitForCompletion(true); numberOfUsers = (int) toUserVector.getCounters().findCounter(ToUserVectorReducer.Counters.USERS).getValue(); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job maybePruneAndTransponse = prepareJob(userVectorPath, itemUserMatrixPath, SequenceFileInputFormat.class, MaybePruneRowsMapper.class, IntWritable.class, DistributedRowMatrix.MatrixEntryWritable.class, ToItemVectorsReducer.class, IntWritable.class, VectorWritable.class, SequenceFileOutputFormat.class); maybePruneAndTransponse.getConfiguration().setInt(MaybePruneRowsMapper.MAX_COOCCURRENCES, maxCooccurrencesPerItem); maybePruneAndTransponse.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { /* Once DistributedRowMatrix uses the hadoop 0.20 API, we should refactor this call to something like * new DistributedRowMatrix(...).rowSimilarity(...) */ try { ToolRunner.run(getConf(), new RowSimilarityJob(), new String[] { "-Dmapred.input.dir=" + itemUserMatrixPath, "-Dmapred.output.dir=" + similarityMatrixPath, "--numberOfColumns", String.valueOf(numberOfUsers), "--similarityClassname", similarityClassname, "--maxSimilaritiesPerRow", String.valueOf(maxSimilaritiesPerItem + 1), "--tempDir", getTempPath().toString() }); } catch (Exception e) { throw new IllegalStateException("item-item-similarity computation failed", e); } } if (shouldRunNextPhase(parsedArgs, currentPhase)) { Job prePartialMultiply1 = prepareJob( similarityMatrixPath, prePartialMultiplyPath1, SequenceFileInputFormat.class, SimilarityMatrixRowWrapperMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); prePartialMultiply1.waitForCompletion(true); Job prePartialMultiply2 = prepareJob( userVectorPath, prePartialMultiplyPath2, SequenceFileInputFormat.class, UserVectorSplitterMapper.class, VarIntWritable.class, VectorOrPrefWritable.class, Reducer.class, VarIntWritable.class, VectorOrPrefWritable.class, SequenceFileOutputFormat.class); if (usersFile != null) { prePartialMultiply2.getConfiguration().set(UserVectorSplitterMapper.USERS_FILE, usersFile); } prePartialMultiply2.getConfiguration().setInt(UserVectorSplitterMapper.MAX_PREFS_PER_USER_CONSIDERED, maxPrefsPerUser); prePartialMultiply2.waitForCompletion(true); Job partialMultiply = prepareJob( new Path(prePartialMultiplyPath1 + "," + prePartialMultiplyPath2), partialMultiplyPath, SequenceFileInputFormat.class, Mapper.class, VarIntWritable.class, VectorOrPrefWritable.class, ToVectorAndPrefReducer.class, VarIntWritable.class, VectorAndPrefsWritable.class, SequenceFileOutputFormat.class); setS3SafeCombinedInputPath(partialMultiply, getTempPath(), prePartialMultiplyPath1, prePartialMultiplyPath2); partialMultiply.waitForCompletion(true); } if (shouldRunNextPhase(parsedArgs, currentPhase)) { /* convert the user/item pairs to filter if a filterfile has been specified */ if (filterFile != null) { Job itemFiltering = prepareJob(new Path(filterFile), explicitFilterPath, TextInputFormat.class, ItemFilterMapper.class, VarLongWritable.class, VarLongWritable.class, ItemFilterAsVectorAndPrefsReducer.class, VarIntWritable.class, VectorAndPrefsWritable.class, SequenceFileOutputFormat.class); itemFiltering.waitForCompletion(true); } String aggregateAndRecommendInput = partialMultiplyPath.toString(); if (filterFile != null) { aggregateAndRecommendInput += "," + explicitFilterPath; } Job aggregateAndRecommend = prepareJob( new Path(aggregateAndRecommendInput), outputPath, SequenceFileInputFormat.class, PartialMultiplyMapper.class, VarLongWritable.class, PrefAndSimilarityColumnWritable.class, AggregateAndRecommendReducer.class, VarLongWritable.class, RecommendedItemsWritable.class, TextOutputFormat.class); Configuration aggregateAndRecommendConf = aggregateAndRecommend.getConfiguration(); if (itemsFile != null) { aggregateAndRecommendConf.set(AggregateAndRecommendReducer.ITEMS_FILE, itemsFile); } if (filterFile != null) { setS3SafeCombinedInputPath(aggregateAndRecommend, getTempPath(), partialMultiplyPath, explicitFilterPath); } setIOSort(aggregateAndRecommend); aggregateAndRecommendConf.set(AggregateAndRecommendReducer.ITEMID_INDEX_PATH, itemIDIndexPath.toString()); aggregateAndRecommendConf.setInt(AggregateAndRecommendReducer.NUM_RECOMMENDATIONS, numRecommendations); aggregateAndRecommendConf.setBoolean(BOOLEAN_DATA, booleanData); aggregateAndRecommend.waitForCompletion(true); } return 0; }
diff --git a/mmstudio/src/org/micromanager/acquisition/VirtualAcquisitionDisplay.java b/mmstudio/src/org/micromanager/acquisition/VirtualAcquisitionDisplay.java index dec75bd7..18f35b29 100644 --- a/mmstudio/src/org/micromanager/acquisition/VirtualAcquisitionDisplay.java +++ b/mmstudio/src/org/micromanager/acquisition/VirtualAcquisitionDisplay.java @@ -1,2213 +1,2213 @@ /////////////////////////////////////////////////////////////////////////////// //FILE: VirtualAcquisitionDisplay.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio //----------------------------------------------------------------------------- // // AUTHOR: Henry Pinkard, [email protected], & Arthur Edelstein, 2010 // // COPYRIGHT: University of California, San Francisco, 2012 // // LICENSE: This file is distributed under the BSD license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // package org.micromanager.acquisition; import org.micromanager.internalinterfaces.DisplayControls; import org.micromanager.internalinterfaces.Histograms; import java.lang.reflect.InvocationTargetException; import ij.ImageStack; import ij.process.LUT; import ij.CompositeImage; import ij.ImagePlus; import ij.WindowManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.gui.ScrollbarWithLabel; import ij.gui.StackWindow; import ij.gui.Toolbar; import ij.io.FileInfo; import ij.measure.Calibration; import ij.plugin.frame.ContrastAdjuster; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; import java.util.prefs.Preferences; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.Timer; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.*; import org.micromanager.graph.HistogramControlsState; import org.micromanager.graph.MultiChannelHistograms; import org.micromanager.graph.SingleChannelHistogram; import org.micromanager.utils.*; public final class VirtualAcquisitionDisplay implements AcquisitionDisplay, ImageCacheListener { public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) { ImageStack stack = imgp.getStack(); if (stack instanceof AcquisitionVirtualStack) { return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay(); } else { return null; } } final static Color[] rgb = {Color.red, Color.green, Color.blue}; final static String[] rgbNames = {"Red", "Blue", "Green"}; final ImageCache imageCache_; final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass()); private static final String SIMPLE_WIN_X = "simple_x"; private static final String SIMPLE_WIN_Y = "simple_y"; private AcquisitionEngine eng_; private boolean finished_ = false; private boolean promptToSave_ = true; private String name_; private long lastDisplayTime_; private int lastFrameShown_ = 0; private int lastSliceShown_ = 0; private int lastPositionShown_ = 0; private boolean updating_ = false; private int preferredSlice_ = -1; private int preferredPosition_ = -1; private int preferredChannel_ = -1; private Timer preferredPositionTimer_; private int numComponents_; private ImagePlus hyperImage_; private ScrollbarWithLabel pSelector_; private ScrollbarWithLabel tSelector_; private ScrollbarWithLabel zSelector_; private ScrollbarWithLabel cSelector_; private DisplayControls controls_; public AcquisitionVirtualStack virtualStack_; private boolean simple_ = false; private boolean mda_ = false; //flag if display corresponds to MD acquisition private MetadataPanel mdPanel_; private boolean newDisplay_ = true; //used for autostretching on window opening private double framesPerSec_ = 7; private java.util.Timer zAnimationTimer_ = new java.util.Timer(); private java.util.Timer tAnimationTimer_ = new java.util.Timer(); private boolean zAnimated_ = false, tAnimated_ = false; private int animatedSliceIndex_ = -1; private Component zIcon_, pIcon_, tIcon_, cIcon_; private HashMap<Integer, Integer> zStackMins_; private HashMap<Integer, Integer> zStackMaxes_; private Histograms histograms_; private HistogramControlsState histogramControlsState_; private boolean albumSaved_ = false; private boolean[] channelContrastInitialized_; private static double snapWinMag_ = -1; private JPopupMenu saveTypePopup_; /** * This interface and the following two classes * allow us to manipulate the dimensions * in an ImagePlus without it throwing conniptions. */ public interface IMMImagePlus { public int getNChannelsUnverified(); public int getNSlicesUnverified(); public int getNFramesUnverified(); public void setNChannelsUnverified(int nChannels); public void setNSlicesUnverified(int nSlices); public void setNFramesUnverified(int nFrames); public void drawWithoutUpdate(); public void updateAndDrawWithoutGUIUpdater(); } public class MMCompositeImage extends CompositeImage implements IMMImagePlus { private GUIUpdater updater1 = new GUIUpdater(), updater2 = new GUIUpdater(), updater3 = new GUIUpdater(); MMCompositeImage(ImagePlus imgp, int type) { super(imgp, type); } @Override public String getTitle() { return name_; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superReset() { super.reset(); } @Override public void reset() { if (SwingUtilities.isEventDispatchThread()) { super.reset(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { superReset(); } }); } } @Override public synchronized void setMode(final int mode) { superSetMode(mode); } private void superSetMode(int mode) { super.setMode(mode); } @Override public synchronized void setChannelLut(final LUT lut) { superSetLut(lut); } private void superSetLut(LUT lut) { super.setChannelLut(lut); } @Override public synchronized void updateImage() { superUpdateImage(); } private void superUpdateImage() { //Need to set this field to null, or else an infintie loop can be entered when //The imageJ contrast adjuster is open ContrastAdjuster ca = (ContrastAdjuster) WindowManager.getFrame("B&C"); if (ca != null) { try { JavaUtils.setRestrictedFieldValue(ca, ContrastAdjuster.class, "instance", null); } catch (NoSuchFieldException ex) { ReportingUtils.logError("ImageJ ContrastAdjuster doesn't have field named instance"); } } super.updateImage(); } private Runnable updateAndDrawRunnable() { return new Runnable() { @Override public void run() { superUpdateImage(); imageChangedUpdate(); try { GUIUtils.invokeLater(new Runnable() { public void run() { try { JavaUtils.invokeRestrictedMethod(this, ImagePlus.class, "notifyListeners", 2); } catch (Exception ex) { } superDraw(); MMStudioMainFrame.getInstance().getLiveModeTimer().updateFPS(); } }); } catch (Exception e) { ReportingUtils.logError(e); } } }; } public void updateAndDrawWithoutGUIUpdater() { try { GUIUtils.invokeLater(updateAndDrawRunnable()); } catch (Exception e) { ReportingUtils.logError(e); } } @Override public void updateAndDraw() { updater1.post(updateAndDrawRunnable()); } private void superDraw() { if (super.win != null ) { super.getCanvas().paint(super.getCanvas().getGraphics()); } } @Override public void draw() { Runnable runnable = new Runnable() { public void run() { imageChangedUpdate(); superDraw(); MMStudioMainFrame.getInstance().getLiveModeTimer().updateFPS(); } }; updater2.post(runnable); } @Override public void drawWithoutUpdate() { Runnable runnable = new Runnable() { @Override public void run() { getWindow().getCanvas().setImageUpdated(); superDraw(); } }; updater3.post(runnable); } } public class MMImagePlus extends ImagePlus implements IMMImagePlus { private GUIUpdater updater1 = new GUIUpdater(), updater2 = new GUIUpdater(); public VirtualAcquisitionDisplay display_; MMImagePlus(String title, ImageStack stack, VirtualAcquisitionDisplay disp) { super(title, stack); display_ = disp; } @Override public String getTitle() { return name_; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superDraw() { if (super.win != null ) { super.getCanvas().paint(super.getCanvas().getGraphics()); } } private Runnable drawRunnable() { return new Runnable() { @Override public void run() { imageChangedUpdate(); superDraw(); MMStudioMainFrame.getInstance().getLiveModeTimer().updateFPS(); } }; } public void updateAndDrawWithoutGUIUpdater() { try { GUIUtils.invokeLater(drawRunnable()); } catch (Exception e) { ReportingUtils.logError(e); } } @Override public void draw() { updater1.post(drawRunnable()); } @Override public void drawWithoutUpdate() { Runnable runnable = new Runnable() { @Override public void run() { //ImageJ requires (this getWindow().getCanvas().setImageUpdated(); superDraw(); } }; updater2.post(runnable); } } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) { this(imageCache, eng, WindowManager.getUniqueName("Untitled")); } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) { name_ = name; imageCache_ = imageCache; eng_ = eng; pSelector_ = createPositionScrollbar(); mda_ = eng != null; zStackMins_ = new HashMap<Integer, Integer>(); zStackMaxes_ = new HashMap<Integer, Integer>(); this.albumSaved_ = imageCache.isFinished(); } //used for snap and live public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException { simple_ = true; imageCache_ = imageCache; name_ = name; mda_ = false; this.albumSaved_ = imageCache.isFinished(); } private void startup(JSONObject firstImageMetadata) { // EDTProfiler edtp = new EDTProfiler(); mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 1; int width = 0; int height = 0; int numComponents = 1; try { if (firstImageMetadata != null) { width = MDUtils.getWidth(firstImageMetadata); height = MDUtils.getHeight(firstImageMetadata); } else { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); } numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); int imageChannelIndex; try { imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata); } catch (Exception e) { imageChannelIndex = -1; } numChannels = Math.max(1 + imageChannelIndex, Math.max(summaryMetadata.getInt("Channels"), 1)); numPositions = Math.max(summaryMetadata.getInt("Positions"), 1); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { if (firstImageMetadata != null) { type = MDUtils.getSingleChannelType(firstImageMetadata); } else { type = MDUtils.getSingleChannelType(summaryMetadata); } } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache_, numGrayChannels * numSlices * numFrames, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } if (simple_) { controls_ = new SimpleWindowControls(this); } else { controls_ = new HyperstackControls(this); } hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_), numGrayChannels, numSlices, numFrames, virtualStack_, controls_); applyPixelSizeCalibration(hyperImage_); histogramControlsState_ = mdPanel_.getContrastPanel().createDefaultControlsState(); makeHistograms(); createWindow(); //Make sure contrast panel sets up correctly here windowToFront(); cSelector_ = getSelector("c"); if (!simple_) { tSelector_ = getSelector("t"); zSelector_ = getSelector("z"); if (zSelector_ != null) { zSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredSlice_ = zSelector_.getValue(); } }); } if (cSelector_ != null) { cSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredChannel_ = cSelector_.getValue(); } }); } - if (imageCache_.lastAcquiredFrame() > 1) { + if (imageCache_.lastAcquiredFrame() > 0) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } configureAnimationControls(); setNumPositions(numPositions); } //Load contrast settigns if opening datset if (imageCache_.isFinished()) { } updateAndDraw(false); updateWindowTitleAndStatus(); forcePainting(); } /* * Set display to one of three modes: * ij.CompositeImage.COMPOSITE * ij.CompositeImage.GRAYSCALE * ij.CompositeImage.COLOR */ public void setDisplayMode(int displayMode) { mdPanel_.getContrastPanel().setDisplayMode(displayMode); } private void forcePainting() { Runnable forcePaint = new Runnable() { public void run() { if (zIcon_ != null) { zIcon_.paint(zIcon_.getGraphics()); } if (tIcon_ != null) { tIcon_.paint(tIcon_.getGraphics()); } if (cIcon_ != null) { cIcon_.paint(cIcon_.getGraphics()); } if (controls_ != null) { controls_.paint(controls_.getGraphics()); } if (pIcon_ != null && pIcon_.isValid()) { pIcon_.paint(pIcon_.getGraphics()); } } }; try { GUIUtils.invokeAndWait(forcePaint); } catch (Exception ex) { ReportingUtils.logError(ex); } } private void animateSlices(final boolean animate) { if (!animate) { zAnimationTimer_.cancel(); zAnimated_ = false; refreshAnimationIcons(); return; } else { zAnimationTimer_ = new java.util.Timer(); animateFrames(false); final int slicesPerStep; long interval = (long) (1000.0 / framesPerSec_); if (interval < 33) { interval = 33; slicesPerStep = (int) Math.round(framesPerSec_*33.0/1000.0); } else { slicesPerStep = 1; } TimerTask task = new TimerTask() { public void run() { int slice = hyperImage_.getSlice(); if (slice >= zSelector_.getMaximum() - 1) { hyperImage_.setPosition(hyperImage_.getChannel(), 1, hyperImage_.getFrame()); } else { hyperImage_.setPosition(hyperImage_.getChannel(), slice + slicesPerStep, hyperImage_.getFrame()); } } }; zAnimationTimer_.schedule(task, 0, interval); zAnimated_ = true; refreshAnimationIcons(); } } private void animateFrames(final boolean animate) { if (!animate) { tAnimationTimer_.cancel(); tAnimated_ = false; refreshAnimationIcons(); return; } else { tAnimationTimer_ = new java.util.Timer(); animateSlices(false); final int framesPerStep; long interval = (long) (1000.0 / framesPerSec_); if (interval < 33) { interval = 33; framesPerStep = (int) Math.round(framesPerSec_*33.0/1000.0); } else { framesPerStep = 1; } TimerTask task = new TimerTask() { public void run() { int frame = hyperImage_.getFrame(); if (frame >= tSelector_.getMaximum() - 1) { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), 1); } else { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame + framesPerStep); } } }; tAnimationTimer_.schedule(task, 0, interval); tAnimated_ = true; refreshAnimationIcons(); } } private void refreshAnimationIcons() { if (zIcon_ != null) { zIcon_.repaint(); } if (tIcon_ != null) { tIcon_.repaint(); } } private void configureAnimationControls() { if (zIcon_ != null) { zIcon_.addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { animateSlices(!zAnimated_); } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); } if (tIcon_ != null) { tIcon_.addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { animateFrames(!tAnimated_); } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); } } /** * Allows bypassing the prompt to Save * @param promptToSave boolean flag */ public void promptToSave(boolean promptToSave) { promptToSave_ = promptToSave; } /* * Method required by ImageCacheListener */ @Override public void imageReceived(final TaggedImage taggedImage) { updateDisplay(taggedImage, false); } /* * Method required by ImageCacheListener */ @Override public void imagingFinished(String path) { updateDisplay(null, true); updateAndDraw(); if (!(eng_ != null && eng_.abortRequested())) { updateWindowTitleAndStatus(); } } private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) { try { long t = System.currentTimeMillis(); JSONObject tags; if (taggedImage != null) { tags = taggedImage.tags; } else { tags = imageCache_.getLastImageTags(); } if (tags == null) { return; } int frame = MDUtils.getFrameIndex(tags); int ch = MDUtils.getChannelIndex(tags); int slice = MDUtils.getSliceIndex(tags); int position = MDUtils.getPositionIndex(tags); boolean show = finalUpdate || frame == 0 || (Math.abs(t - lastDisplayTime_) > 30) || (ch == getNumChannels() - 1 && lastFrameShown_ == frame && lastSliceShown_ == slice && lastPositionShown_ == position) || (slice == getNumSlices() - 1 && frame == 0 && position == 0 && ch == getNumChannels() - 1); if (show) { showImage(tags, true); lastFrameShown_ = frame; lastSliceShown_ = slice; lastPositionShown_ = position; lastDisplayTime_ = t; forceImagePaint(); } } catch (Exception e) { ReportingUtils.logError(e); } } private void forceImagePaint() { hyperImage_.getWindow().getCanvas().paint(hyperImage_.getWindow().getCanvas().getGraphics()); } public int rgbToGrayChannel(int channelIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return channelIndex * 3; } return channelIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public int grayToRGBChannel(int grayIndex) { try { if (imageCache_ != null) { if (imageCache_.getSummaryMetadata() != null) if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return grayIndex / 3; } } return grayIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) { try { JSONObject displaySettings = new JSONObject(); JSONArray chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors"); JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames"); JSONArray chMaxes, chMins; if ( summaryMetadata.has("ChContrastMin")) { chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin"); } else { chMins = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMins.put(0); } if ( summaryMetadata.has("ChContrastMax")) { chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax"); } else { int max = 65536; if (summaryMetadata.has("BitDepth")) max = (int) (Math.pow(2, summaryMetadata.getInt("BitDepth"))-1); chMaxes = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMaxes.put(max); } int numComponents = MDUtils.getNumberOfComponents(summaryMetadata); JSONArray channels = new JSONArray(); if (numComponents > 1) //RGB { int rgbChannelBitDepth; try { rgbChannelBitDepth = MDUtils.getBitDepth(summaryMetadata); } catch (Exception e) { rgbChannelBitDepth = summaryMetadata.getString("PixelType").endsWith("32") ? 8 : 16; } for (int k = 0; k < 3; k++) { JSONObject channelObject = new JSONObject(); channelObject.put("Color", rgb[k].getRGB()); channelObject.put("Name", rgbNames[k]); channelObject.put("Gamma", 1.0); channelObject.put("Min", 0); channelObject.put("Max", Math.pow(2, rgbChannelBitDepth) - 1); channels.put(channelObject); } } else { for (int k = 0; k < chNames.length(); ++k) { String name = (String) chNames.get(k); int color = 0; if (k < chColors.length()) color = chColors.getInt(k); int min = 0; if (k < chMins.length()) min = chMins.getInt(k); int max = chMaxes.getInt(0); if (k < chMaxes.length()) max = chMaxes.getInt(k); JSONObject channelObject = new JSONObject(); channelObject.put("Color", color); channelObject.put("Name", name); channelObject.put("Gamma", 1.0); channelObject.put("Min", min); channelObject.put("Max", max); channels.put(channelObject); } } displaySettings.put("Channels", channels); JSONObject comments = new JSONObject(); String summary = ""; try { summary = summaryMetadata.getString("Comment"); } catch (JSONException ex) { summaryMetadata.put("Comment", ""); } comments.put("Summary", summary); displaySettings.put("Comments", comments); return displaySettings; } catch (Exception e) { ReportingUtils.showError("Summary metadata not found or corrupt. Is this a Micro-Manager dataset?"); return null; } } /** * Sets ImageJ pixel size calibration * @param hyperImage */ private void applyPixelSizeCalibration(final ImagePlus hyperImage) { try { JSONObject summary = getSummaryMetadata(); double pixSizeUm = summary.getDouble("PixelSize_um"); if (pixSizeUm > 0) { Calibration cal = new Calibration(); cal.setUnit("um"); cal.pixelWidth = pixSizeUm; cal.pixelHeight = pixSizeUm; String intMs = "Interval_ms"; if (summary.has(intMs)) cal.frameInterval = summary.getDouble(intMs) / 1000.0; String zStepUm = "z-step_um"; if (summary.has(zStepUm)) cal.pixelDepth = summary.getDouble(zStepUm); hyperImage.setCalibration(cal); } } catch (JSONException ex) { // no pixelsize defined. Nothing to do } } private void setNumPositions(int n) { if (simple_) { return; } pSelector_.setMinimum(0); pSelector_.setMaximum(n); ImageWindow win = hyperImage_.getWindow(); if (n > 1 && pSelector_.getParent() == null) { win.add(pSelector_, win.getComponentCount() - 1); } else if (n <= 1 && pSelector_.getParent() != null) { win.remove(pSelector_); } win.pack(); } private void setNumFrames(int n) { if (simple_) { return; } if (tSelector_ != null) { //ImageWindow win = hyperImage_.getWindow(); ((IMMImagePlus) hyperImage_).setNFramesUnverified(n); tSelector_.setMaximum(n + 1); // JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n); } } private void setNumSlices(int n) { if (simple_) { return; } if (zSelector_ != null) { ((IMMImagePlus) hyperImage_).setNSlicesUnverified(n); zSelector_.setMaximum(n + 1); } } private void setNumChannels(int n) { if (cSelector_ != null) { ((IMMImagePlus) hyperImage_).setNChannelsUnverified(n); cSelector_.setMaximum(1 + n); } } public ImagePlus getHyperImage() { return hyperImage_; } public int getStackSize() { if (hyperImage_ == null) { return -1; } int s = hyperImage_.getNSlices(); int c = hyperImage_.getNChannels(); int f = hyperImage_.getNFrames(); if ((s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1)) { return s * c * f; } return Math.max(Math.max(s, c), f); } private void imageChangedWindowUpdate() { if (hyperImage_ != null && hyperImage_.isVisible()) { TaggedImage ti = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (ti != null) { controls_.newImageUpdate(ti.tags); } } } public void updateAndDraw() { updateAndDraw(true); } public void updateAndDraw(boolean useGUIUpdater) { if (hyperImage_ != null && hyperImage_.isVisible()) { if (!useGUIUpdater) { ((IMMImagePlus) hyperImage_).updateAndDrawWithoutGUIUpdater(); } else { hyperImage_.updateAndDraw(); } } } public void updateWindowTitleAndStatus() { if (simple_) { int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); String title = hyperImage_.getTitle() + " ("+mag+"%)"; hyperImage_.getWindow().setTitle(title); return; } if (controls_ == null) { return; } String status = ""; final AcquisitionEngine eng = eng_; if (eng != null) { if (acquisitionIsRunning()) { if (!abortRequested()) { controls_.acquiringImagesUpdate(true); if (isPaused()) { status = "paused"; } else { status = "running"; } } else { controls_.acquiringImagesUpdate(false); status = "interrupted"; } } else { controls_.acquiringImagesUpdate(false); if (!status.contentEquals("interrupted")) { if (eng.isFinished()) { status = "finished"; eng_ = null; } } } status += ", "; if (eng.isFinished()) { eng_ = null; finished_ = true; } } else { if (finished_ == true) { status = "finished, "; } controls_.acquiringImagesUpdate(false); } if (isDiskCached() || albumSaved_) { status += "on disk"; } else { status += "not yet saved"; } controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null); String path = isDiskCached() ? new File(imageCache_.getDiskLocation()).getName() : name_; if (hyperImage_.isVisible()) { int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); hyperImage_.getWindow().setTitle(path + " (" + status + ") (" + mag + "%)" ); } } private void windowToFront() { if (hyperImage_ == null || hyperImage_.getWindow() == null) { return; } hyperImage_.getWindow().toFront(); } /** * Displays tagged image in the multi-D viewer * Will wait for the screen update * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg) throws Exception { showImage(taggedImg, true); } /** * Displays tagged image in the multi-D viewer * Optionally waits for the display to draw the image * * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { showImage(taggedImg.tags, waitForDisplay); } public void showImage(final JSONObject tags, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { updateWindowTitleAndStatus(); if (tags == null) { return; } if (hyperImage_ == null) { GUIUtils.invokeAndWait(new Runnable() { public void run() { try { startup(tags); } catch (Exception e) { ReportingUtils.logError(e); } } }); } int channel = 0, frame = 0, slice = 0, position = 0, superChannel = 0; try { frame = MDUtils.getFrameIndex(tags); slice = MDUtils.getSliceIndex(tags); channel = MDUtils.getChannelIndex(tags); position = MDUtils.getPositionIndex(tags); superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(tags)); } catch (Exception ex) { ReportingUtils.logError(ex); } //This block allows animation to be reset to where it was before iamges were added final boolean framesAnimated = isTAnimated(), slicesAnimated = isZAnimated(); final int animatedFrameIndex = hyperImage_.getFrame(); if (slice == 0) animatedSliceIndex_ = hyperImage_.getSlice(); if (framesAnimated || slicesAnimated) { animateFrames(false); animateSlices(false); } //make sure pixels get properly set if (hyperImage_ != null && frame == 0) { IMMImagePlus img = (IMMImagePlus) hyperImage_; if (img.getNChannelsUnverified() == 1) { if (img.getNSlicesUnverified() == 1) { hyperImage_.getProcessor().setPixels(virtualStack_.getPixels(1)); } } else if (hyperImage_ instanceof MMCompositeImage) { //reset rebuilds each of the channel ImageProcessors with the correct pixels //from AcquisitionVirtualStack MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); //This line is neccessary for image processor to have correct pixels in grayscale mode ci.getProcessor().setPixels(virtualStack_.getPixels(ci.getCurrentSlice())); } } else if (hyperImage_ instanceof MMCompositeImage) { MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); } if (cSelector_ != null) { if (cSelector_.getMaximum() <= (1 + superChannel)) { this.setNumChannels(1 + superChannel); ((CompositeImage) hyperImage_).reset(); //JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class, // "setupLuts", 1 + superChannel, Integer.TYPE); } } initializeContrast(channel, slice); if (!simple_) { if (tSelector_ != null) { if (tSelector_.getMaximum() <= (1 + frame)) { this.setNumFrames(1 + frame); } } if (position + 1 > getNumPositions()) { setNumPositions(position + 1); } setPosition(position); hyperImage_.setPosition(1 + superChannel, 1 + slice, 1 + frame); } updateAndDraw(simple_ || frame != 0); restartAnimationAfterShowing(animatedFrameIndex, animatedSliceIndex_, framesAnimated, slicesAnimated); if (eng_ != null) { setPreferredScrollbarPositions(); } if (cSelector_ != null) { if (histograms_.getNumberOfChannels() < (1 + superChannel)) { if (histograms_ != null) { histograms_.setupChannelControls(imageCache_); } } } } /** * If animation was running prior to showImage, restarts it with sliders at appropriate positions */ private void restartAnimationAfterShowing(int frame, int slice, boolean framesAnimated, boolean slicesAnimated) { if (framesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame+1); animateFrames(true); } else if (slicesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), slice+1, hyperImage_.getFrame()); animateSlices(true); } } /* * Live/snap should load window contrast settings * MDA should autoscale on first image * Not called when opening a dataset because stored settings are loaded automatically */ private void initializeContrast(final int channel, final int slice) { Runnable autoscaleOrLoadContrast = new Runnable() { public void run() { if (!newDisplay_) { return; } if (simple_) { //Snap/live if (hyperImage_ instanceof MMCompositeImage && ((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } loadSimpleWinContrastWithoutDraw(); } else if (mda_) { //Multi D acquisition IMMImagePlus immImg = ((IMMImagePlus) hyperImage_); if (immImg.getNSlicesUnverified() > 1) { //Z stacks autoscaleOverStackWithoutDraw(hyperImage_, channel, slice, zStackMins_, zStackMaxes_); if (channel != immImg.getNChannelsUnverified() - 1 || slice != immImg.getNSlicesUnverified() - 1) { return; //don't set new display to false until all channels autoscaled } } else { //No z stacks if (channel +1 != getNumChannels()) return; autoscaleWithoutDraw(); } } else //Acquire button if (hyperImage_ instanceof MMCompositeImage) { if (((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } autoscaleWithoutDraw(); } else { autoscaleWithoutDraw(); // else do nothing because contrast automatically loaded from cache } newDisplay_ = false; } }; if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(autoscaleOrLoadContrast); } else { autoscaleOrLoadContrast.run(); } } private void loadSimpleWinContrastWithoutDraw() { int n = getImageCache().getNumChannels(); ContrastSettings c; for (int i = 0; i < n; i++) { c = MMStudioMainFrame.getInstance().loadSimpleContrastSettigns(getImageCache().getPixelType(), i); histograms_.setChannelContrast(i, c.min, c.max, c.gamma); } histograms_.applyLUTToImage(); } private void autoscaleWithoutDraw() { if (histograms_ != null) { histograms_.calcAndDisplayHistAndStats(true); histograms_.autostretch(); histograms_.applyLUTToImage(); } } private void autoscaleOverStackWithoutDraw(ImagePlus img, int channel, int slice, HashMap<Integer, Integer> mins, HashMap<Integer, Integer> maxes) { int nChannels = ((VirtualAcquisitionDisplay.IMMImagePlus) img).getNChannelsUnverified(); int bytes = img.getBytesPerPixel(); int pixMin, pixMax; if (mins.containsKey(channel)) { pixMin = mins.get(channel); pixMax = maxes.get(channel); } else { pixMax = 0; pixMin = (int) (Math.pow(2, 8 * bytes) - 1); } int flatIndex = 1 + channel + slice * nChannels; if (bytes == 2) { short[] pixels = (short[]) img.getStack().getPixels(flatIndex); for (short value : pixels) { if (value < pixMin) { pixMin = value; } if (value > pixMax) { pixMax = value; } } } else if (bytes == 1) { byte[] pixels = (byte[]) img.getStack().getPixels(flatIndex); for (byte value : pixels) { if (value < pixMin) { pixMin = value; } if (value > pixMax) { pixMax = value; } } } //autoscale the channel histograms_.setChannelContrast(channel, pixMin, pixMax, 1.0); histograms_.applyLUTToImage(); mins.put(channel, pixMin); maxes.put(channel, pixMax); } private void setPreferredScrollbarPositions() { if (preferredPositionTimer_ == null) { preferredPositionTimer_ = new Timer(250, new ActionListener() { public void actionPerformed(ActionEvent e) { int c = preferredChannel_ == -1 ? hyperImage_.getChannel() : preferredChannel_; int s = preferredSlice_ == -1 ? hyperImage_.getSlice() : preferredSlice_; hyperImage_.setPosition(c, zAnimated_ ? hyperImage_.getSlice() : s ,hyperImage_.getFrame()); if (pSelector_ != null && preferredPosition_ > -1) { if (eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_CHANNEL_SLICE && eng_.getAcqOrderMode() != AcqOrderMode.POS_TIME_SLICE_CHANNEL) { setPosition(preferredPosition_); } } preferredPositionTimer_.stop(); } }); } if (preferredPositionTimer_.isRunning()) { preferredPositionTimer_.restart(); } else { preferredPositionTimer_.start(); } } private void updatePosition(int p) { if (simple_) { return; } virtualStack_.setPositionIndex(p); if (!hyperImage_.isComposite()) { Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice()); hyperImage_.getProcessor().setPixels(pixels); } else { CompositeImage ci = (CompositeImage) hyperImage_; if (ci.getMode() == CompositeImage.COMPOSITE) { for (int i = 0; i < ((MMCompositeImage) ci).getNChannelsUnverified(); i++) { //Dont need to set pixels if processor is null because it will get them from stack automatically if (ci.getProcessor(i + 1) != null) ci.getProcessor(i + 1).setPixels(virtualStack_.getPixels(ci.getCurrentSlice() - ci.getChannel() + i + 1)); } } ci.getProcessor().setPixels(virtualStack_.getPixels(hyperImage_.getCurrentSlice())); } //need to call this even though updateAndDraw also calls it to get autostretch to work properly imageChangedUpdate(); updateAndDraw(); } public void setPosition(int p) { if (simple_) { return; } pSelector_.setValue(p); } public void setSliceIndex(int i) { if (simple_) { return; } final int f = hyperImage_.getFrame(); final int c = hyperImage_.getChannel(); hyperImage_.setPosition(c, i + 1, f); } public int getSliceIndex() { return hyperImage_.getSlice() - 1; } boolean pause() { if (eng_ != null) { if (eng_.isPaused()) { eng_.setPause(false); } else { eng_.setPause(true); } updateWindowTitleAndStatus(); return (eng_.isPaused()); } return false; } boolean abort() { if (eng_ != null) { if (eng_.abortRequest()) { updateWindowTitleAndStatus(); return true; } } return false; } public boolean acquisitionIsRunning() { if (eng_ != null) { return eng_.isAcquisitionRunning(); } else { return false; } } public long getNextWakeTime() { return eng_.getNextWakeTime(); } public boolean abortRequested() { if (eng_ != null) { return eng_.abortRequested(); } else { return false; } } private boolean isPaused() { if (eng_ != null) { return eng_.isPaused(); } else { return false; } } public void albumChanged() { albumSaved_ = false; } private Class createSaveTypePopup() { if (saveTypePopup_ != null) { saveTypePopup_.setVisible(false); saveTypePopup_ = null; } final JPopupMenu menu = new JPopupMenu(); saveTypePopup_ = menu; JMenuItem single = new JMenuItem("Save as single-image files"); JMenuItem multi = new JMenuItem("Save as multi-image files"); JMenuItem cancel = new JMenuItem("Cancel"); menu.add(single); menu.add(multi); menu.addSeparator(); menu.add(cancel); final AtomicInteger ai = new AtomicInteger(-1); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ai.set(0); } }); single.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ai.set(1); } }); multi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ai.set(2); } }); MouseListener highlighter = new MouseListener() { public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { ((JMenuItem) e.getComponent()).setArmed(true); } public void mouseExited(MouseEvent e) { ((JMenuItem) e.getComponent()).setArmed(false); } }; single.addMouseListener(highlighter); multi.addMouseListener(highlighter); cancel.addMouseListener(highlighter); Point mouseLocation = MouseInfo.getPointerInfo().getLocation(); menu.show(null, mouseLocation.x, mouseLocation.y); while (ai.get() == -1) { try { Thread.sleep(10); } catch (InterruptedException ex) {} if (!menu.isVisible()) { return null; } } menu.setVisible(false); saveTypePopup_ = null; if (ai.get() == 0) { return null; } else if (ai.get() == 1) { return TaggedImageStorageDiskDefault.class; } else { return TaggedImageStorageMultipageTiff.class; } } boolean saveAs() { return saveAs(null,true); } boolean saveAs(boolean pointToNewStorage) { return saveAs(null, pointToNewStorage); } private boolean saveAs(Class storageClass, boolean pointToNewStorage) { if (eng_ != null && eng_.isAcquisitionRunning()) { JOptionPane.showMessageDialog(null, "Data can not be saved while acquisition is running."); return false; } if (storageClass == null) { storageClass = createSaveTypePopup(); } if (storageClass == null) { return false; } String prefix; String root; for (;;) { File f = FileDialogs.save(hyperImage_.getWindow(), "Please choose a location for the data set", MMStudioMainFrame.MM_DATA_SET); if (f == null) // Canceled. { return false; } prefix = f.getName(); root = new File(f.getParent()).getAbsolutePath(); if (f.exists()) { ReportingUtils.showMessage(prefix + " is write only! Please choose another name."); } else { break; } } try { TaggedImageStorage newFileManager = (TaggedImageStorage) storageClass.getConstructor( String.class, Boolean.class, JSONObject.class).newInstance( root + "/" + prefix, true, getSummaryMetadata()); if (pointToNewStorage) { albumSaved_ = true; } imageCache_.saveAs(newFileManager, pointToNewStorage); } catch (Exception ex) { ReportingUtils.showError("Failed to save file"); } MMStudioMainFrame.getInstance().setAcqDirectory(root); updateWindowTitleAndStatus(); return true; } final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) { MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack, this); FileInfo fi = new FileInfo(); fi.width = virtualStack.getWidth(); fi.height = virtualStack.getHeight(); fi.fileName = virtualStack.getDirectory(); fi.url = null; img.setFileInfo(fi); return img; } final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices, int frames, final AcquisitionVirtualStack virtualStack, DisplayControls hc) { final ImagePlus hyperImage; mmIP.setNChannelsUnverified(channels); mmIP.setNFramesUnverified(frames); mmIP.setNSlicesUnverified(slices); if (channels > 1) { hyperImage = new MMCompositeImage(mmIP, CompositeImage.COMPOSITE); hyperImage.setOpenAsHyperStack(true); } else { hyperImage = mmIP; mmIP.setOpenAsHyperStack(true); } return hyperImage; } public void liveModeEnabled(boolean enabled) { if (simple_) { controls_.acquiringImagesUpdate(enabled); } } private void createWindow() { final DisplayWindow win = new DisplayWindow(hyperImage_); win.getCanvas().addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent me) { } //used to store preferred zoom public void mousePressed(MouseEvent me) { if (Toolbar.getToolId() == 11) {//zoom tool selected storeWindowSizeAfterZoom(win); } updateWindowTitleAndStatus(); } //updates the histogram after an ROI is drawn public void mouseReleased(MouseEvent me) { hyperImage_.updateAndDraw(); } public void mouseEntered(MouseEvent me) { } public void mouseExited(MouseEvent me) { } }); win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor()); MMStudioMainFrame.getInstance().addMMBackgroundListener(win); win.add(controls_); win.pack(); if (simple_) { win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0), prefs_.getInt(SIMPLE_WIN_Y, 0)); } //Set magnification zoomToPreferredSize(win); mdPanel_.displayChanged(win); imageChangedUpdate(); } private int getWinLength(ImageWindow win) { return (int) Math.sqrt(win.getSize().width * win.getSize().height); } public void storeWindowSizeAfterZoom(ImageWindow win) { if (simple_) { snapWinMag_ = win.getCanvas().getMagnification(); } } private void zoomToPreferredSize(DisplayWindow win) { Point location = win.getLocation(); win.setLocation(new Point(0,0)); double mag; if (simple_ && snapWinMag_ != -1) { mag = snapWinMag_; } else { mag = MMStudioMainFrame.getInstance().getPreferredWindowMag(); } ImageCanvas canvas = win.getCanvas(); if (mag < canvas.getMagnification()) { while (mag < canvas.getMagnification()) { canvas.zoomOut(canvas.getWidth() / 2, canvas.getHeight() / 2); } } else if (mag > canvas.getMagnification()) { while (mag > canvas.getMagnification()) { canvas.zoomIn(canvas.getWidth() / 2, canvas.getHeight() / 2); } } //Make sure the window is fully on the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Point newLocation = new Point(location.x,location.y); if (newLocation.x + win.getWidth() > screenSize.width && win.getWidth() < screenSize.width) { newLocation.x = screenSize.width - win.getWidth(); } if (newLocation.y + win.getHeight() > screenSize.height && win.getHeight() < screenSize.height) { newLocation.y = screenSize.height - win.getHeight(); } win.setLocation(newLocation); } private ScrollbarWithLabel getSelector(String label) { // label should be "t", "z", or "c" ScrollbarWithLabel selector = null; ImageWindow win = hyperImage_.getWindow(); int slices = ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); int frames = ((IMMImagePlus) hyperImage_).getNFramesUnverified(); int channels = ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); if (win instanceof StackWindow) { try { //ImageJ bug workaround if (frames > 1 && slices == 1 && channels == 1 && label.equals("t")) { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector"); } else { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector"); } } catch (NoSuchFieldException ex) { selector = null; ReportingUtils.logError(ex); } } //replace default icon with custom one if (selector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( selector, ScrollbarWithLabel.class, "icon"); selector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } ScrollbarIcon newIcon = new ScrollbarIcon(label.charAt(0), this); if (label.equals("z")) { zIcon_ = newIcon; } else if (label.equals("t")) { tIcon_ = newIcon; } else if (label.equals("c")) { cIcon_ = newIcon; } selector.add(newIcon, BorderLayout.WEST); selector.invalidate(); selector.validate(); } return selector; } private ScrollbarWithLabel createPositionScrollbar() { final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') { @Override public void setValue(int v) { if (this.getValue() != v) { super.setValue(v); updatePosition(v); } } }; // prevents scroll bar from blinking on Windows: pSelector.setFocusable(false); pSelector.setUnitIncrement(1); pSelector.setBlockIncrement(1); pSelector.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { updatePosition(pSelector.getValue()); preferredPosition_ = pSelector_.getValue(); } }); if (pSelector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( pSelector, ScrollbarWithLabel.class, "icon"); pSelector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } pIcon_ = new ScrollbarIcon('p', this); pSelector.add(pIcon_, BorderLayout.WEST); pSelector.invalidate(); pSelector.validate(); } return pSelector; } public JSONObject getCurrentMetadata() { try { if (hyperImage_ != null) { TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getChannel()-1, hyperImage_.getSlice()-1, hyperImage_.getFrame()-1); if (image != null) { return image.tags; } else { return null; } } else { return null; } } catch (NullPointerException ex) { return null; } } public int getCurrentPosition() { return virtualStack_.getPositionIndex(); } public int getNumSlices() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); } public int getNumFrames() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNFramesUnverified(); } public int getNumPositions() { if (simple_) { return 1; } return pSelector_.getMaximum(); } public ImagePlus getImagePlus() { return hyperImage_; } public ImageCache getImageCache() { return imageCache_; } public ImagePlus getImagePlus(int position) { ImagePlus iP = new ImagePlus(); iP.setStack(virtualStack_); iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames()); iP.setFileInfo(hyperImage_.getFileInfo()); return iP; } public void setComment(String comment) throws MMScriptException { try { getSummaryMetadata().put("Comment", comment); } catch (Exception ex) { ReportingUtils.logError(ex); } } public final JSONObject getSummaryMetadata() { return imageCache_.getSummaryMetadata(); } /* public final JSONObject getImageMetadata(int channel, int slice, int frame, int position) { return imageCache_.getImageTags(channel, slice, frame, position); } */ public void close() { if (hyperImage_ != null) { hyperImage_.getWindow().windowClosing(null); hyperImage_.close(); } } public synchronized boolean windowClosed() { if (hyperImage_ != null) { ImageWindow win = hyperImage_.getWindow(); return (win == null || win.isClosed()); } return true; } public void showFolder() { if (isDiskCached()) { try { File location = new File(imageCache_.getDiskLocation()); if (JavaUtils.isWindows()) { Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath()); } else if (JavaUtils.isMac()) { if (!location.isDirectory()) { location = location.getParentFile(); } Runtime.getRuntime().exec("open " + location.getAbsolutePath()); } } catch (IOException ex) { ReportingUtils.logError(ex); } } } public void setPlaybackFPS(double fps) { framesPerSec_ = fps; if (zAnimated_) { animateSlices(false); animateSlices(true); } else if (tAnimated_) { animateFrames(false); animateFrames(true); } } public double getPlaybackFPS() { return framesPerSec_; } public boolean isZAnimated() { return zAnimated_; } public boolean isTAnimated() { return tAnimated_; } public boolean isAnimated() { return isTAnimated() || isZAnimated(); } public String getSummaryComment() { return imageCache_.getComment(); } public void setSummaryComment(String comment) { imageCache_.setComment(comment); } void setImageComment(String comment) { imageCache_.setImageComment(comment, getCurrentMetadata()); } String getImageComment() { try { return imageCache_.getImageComment(getCurrentMetadata()); } catch (NullPointerException ex) { return ""; } } public boolean isDiskCached() { ImageCache imageCache = imageCache_; if (imageCache == null) { return false; } else { return imageCache.getDiskLocation() != null; } } public void show() { if (hyperImage_ == null) { try { GUIUtils.invokeAndWait(new Runnable() { public void run() { startup(null); } }); } catch (Exception ex) { ReportingUtils.logError(ex); } } hyperImage_.show(); hyperImage_.getWindow().toFront(); } public int getNumChannels() { return ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); } public int getNumGrayChannels() { return getNumChannels(); } public void setWindowTitle(String name) { name_ = name; updateWindowTitleAndStatus(); } public boolean isSimpleDisplay() { return simple_; } public void displayStatusLine(String status) { controls_.setStatusLabel(status); } public void setChannelContrast(int channelIndex, int min, int max, double gamma) { histograms_.setChannelContrast(channelIndex, min, max, gamma); histograms_.applyLUTToImage(); drawWithoutUpdate(); } public void updateChannelNamesAndColors() { if (histograms_ != null && histograms_ instanceof MultiChannelHistograms) { ((MultiChannelHistograms) histograms_).updateChannelNamesAndColors(); } } public void setChannelHistogramDisplayMax(int channelIndex, int histMax) { histograms_.setChannelHistogramDisplayMax(channelIndex, histMax); } /* * called just before image is drawn. Notifies metadata panel to update * metadata or comments if this display is the active window. Notifies histograms * that image is change to create appropriate LUTs and to draw themselves if this * is the active window */ private void imageChangedUpdate() { if (histograms_ != null) { histograms_.imageChanged(); } if (isActiveDisplay()) { mdPanel_.imageChangedUpdate(this); } imageChangedWindowUpdate(); //used to update status line } public boolean isActiveDisplay() { if (hyperImage_ == null || hyperImage_.getWindow() == null) return false; if (hyperImage_.getWindow() == mdPanel_.getCurrentWindow() ) return true; return false; } public void drawWithoutUpdate() { if (hyperImage_ != null) { ((IMMImagePlus) hyperImage_).drawWithoutUpdate(); } } private void makeHistograms() { if (getNumChannels() == 1 ) histograms_ = new SingleChannelHistogram(this); else histograms_ = new MultiChannelHistograms(this); } public Histograms getHistograms() { return histograms_; } public HistogramControlsState getHistogramControlsState() { return histogramControlsState_; } public void disableAutoStretchCheckBox() { if (isActiveDisplay() ) { mdPanel_.getContrastPanel().disableAutostretch(); } else { histogramControlsState_.autostretch = false; } } /* * used to store contrast settings for snap live window */ private void saveSimpleWinSettings() { ImageCache cache = getImageCache(); String pixelType = cache.getPixelType(); int numCh = cache.getNumChannels(); for (int i = 0; i < numCh; i++) { int min = cache.getChannelMin(i); int max = cache.getChannelMax(i); double gamma = cache.getChannelGamma(i); MMStudioMainFrame.getInstance().saveSimpleContrastSettings(new ContrastSettings(min, max, gamma), i, pixelType); } } public ContrastSettings getChannelContrastSettings(int channel) { return histograms_.getChannelContrastSettings(channel); } public class DisplayWindow extends StackWindow { private boolean windowClosingDone_ = false; private boolean closed_ = false; public DisplayWindow(ImagePlus ip) { super(ip); } @Override public boolean close() { windowClosing(null); return closed_; } @Override public void windowClosing(WindowEvent e) { if (windowClosingDone_) { return; } if (eng_ != null && eng_.isAcquisitionRunning()) { if (!abort()) { return; } } if (imageCache_.getDiskLocation() == null && promptToSave_ && !albumSaved_) { String[] options = {"Save single","Save multi","No","Cancel"}; int result = JOptionPane.showOptionDialog(this, "This data set has not yet been saved. " + "Do you want to save it?\nData can be saved as single-image files or multi-image files.", "Micro-Manager",JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == 0) { if (!saveAs(TaggedImageStorageDiskDefault.class, true)) { return; } } else if (result == 1) { if (!saveAs(TaggedImageStorageMultipageTiff.class, true)) { return; } } else if (result == 3) { return; } } if (simple_ && hyperImage_ != null && hyperImage_.getWindow() != null && hyperImage_.getWindow().getLocation() != null) { Point loc = hyperImage_.getWindow().getLocation(); prefs_.putInt(SIMPLE_WIN_X, loc.x); prefs_.putInt(SIMPLE_WIN_Y, loc.y); saveSimpleWinSettings(); } if (imageCache_ != null) { imageCache_.close(); } removeMeFromAcquisitionManager(MMStudioMainFrame.getInstance()); if (!closed_) { try { super.close(); } catch (NullPointerException ex) { ReportingUtils.showError(ex, "Null pointer error in ImageJ code while closing window"); } } //Call this because for some reason WindowManager doesnt always fire mdPanel_.displayChanged(null); zAnimationTimer_.cancel(); tAnimationTimer_.cancel(); super.windowClosing(e); MMStudioMainFrame.getInstance().removeMMBackgroundListener(this); windowClosingDone_ = true; closed_ = true; } /* * Removes the VirtualAcquisitionDisplay from the Acquisition Manager. */ private void removeMeFromAcquisitionManager(MMStudioMainFrame gui) { for (String name : gui.getAcquisitionNames()) { try { if (gui.getAcquisition(name).getAcquisitionWindow() == VirtualAcquisitionDisplay.this) { gui.closeAcquisition(name); } } catch (Exception ex) { ReportingUtils.logError(ex); } } } @Override public void windowClosed(WindowEvent E) { try { // NS: I do not know why this line was here. It causes problems since the windowClosing // function now will often run twice //this.windowClosing(E); super.windowClosed(E); } catch (NullPointerException ex) { ReportingUtils.showError(ex, "Null pointer error in ImageJ code while closing window"); } } @Override public void windowActivated(WindowEvent e) { if (!isClosed()) { super.windowActivated(e); } } @Override public void setAnimate(boolean b) { if (((IMMImagePlus) hyperImage_).getNFramesUnverified() > 1) { animateFrames(b); } else { animateSlices(b); } } @Override public boolean getAnimate() { return isAnimated(); } }; }
true
true
private void startup(JSONObject firstImageMetadata) { // EDTProfiler edtp = new EDTProfiler(); mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 1; int width = 0; int height = 0; int numComponents = 1; try { if (firstImageMetadata != null) { width = MDUtils.getWidth(firstImageMetadata); height = MDUtils.getHeight(firstImageMetadata); } else { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); } numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); int imageChannelIndex; try { imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata); } catch (Exception e) { imageChannelIndex = -1; } numChannels = Math.max(1 + imageChannelIndex, Math.max(summaryMetadata.getInt("Channels"), 1)); numPositions = Math.max(summaryMetadata.getInt("Positions"), 1); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { if (firstImageMetadata != null) { type = MDUtils.getSingleChannelType(firstImageMetadata); } else { type = MDUtils.getSingleChannelType(summaryMetadata); } } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache_, numGrayChannels * numSlices * numFrames, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } if (simple_) { controls_ = new SimpleWindowControls(this); } else { controls_ = new HyperstackControls(this); } hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_), numGrayChannels, numSlices, numFrames, virtualStack_, controls_); applyPixelSizeCalibration(hyperImage_); histogramControlsState_ = mdPanel_.getContrastPanel().createDefaultControlsState(); makeHistograms(); createWindow(); //Make sure contrast panel sets up correctly here windowToFront(); cSelector_ = getSelector("c"); if (!simple_) { tSelector_ = getSelector("t"); zSelector_ = getSelector("z"); if (zSelector_ != null) { zSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredSlice_ = zSelector_.getValue(); } }); } if (cSelector_ != null) { cSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredChannel_ = cSelector_.getValue(); } }); } if (imageCache_.lastAcquiredFrame() > 1) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } configureAnimationControls(); setNumPositions(numPositions); } //Load contrast settigns if opening datset if (imageCache_.isFinished()) { } updateAndDraw(false); updateWindowTitleAndStatus(); forcePainting(); }
private void startup(JSONObject firstImageMetadata) { // EDTProfiler edtp = new EDTProfiler(); mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 1; int width = 0; int height = 0; int numComponents = 1; try { if (firstImageMetadata != null) { width = MDUtils.getWidth(firstImageMetadata); height = MDUtils.getHeight(firstImageMetadata); } else { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); } numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); int imageChannelIndex; try { imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata); } catch (Exception e) { imageChannelIndex = -1; } numChannels = Math.max(1 + imageChannelIndex, Math.max(summaryMetadata.getInt("Channels"), 1)); numPositions = Math.max(summaryMetadata.getInt("Positions"), 1); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { if (firstImageMetadata != null) { type = MDUtils.getSingleChannelType(firstImageMetadata); } else { type = MDUtils.getSingleChannelType(summaryMetadata); } } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache_, numGrayChannels * numSlices * numFrames, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } if (simple_) { controls_ = new SimpleWindowControls(this); } else { controls_ = new HyperstackControls(this); } hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_), numGrayChannels, numSlices, numFrames, virtualStack_, controls_); applyPixelSizeCalibration(hyperImage_); histogramControlsState_ = mdPanel_.getContrastPanel().createDefaultControlsState(); makeHistograms(); createWindow(); //Make sure contrast panel sets up correctly here windowToFront(); cSelector_ = getSelector("c"); if (!simple_) { tSelector_ = getSelector("t"); zSelector_ = getSelector("z"); if (zSelector_ != null) { zSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredSlice_ = zSelector_.getValue(); } }); } if (cSelector_ != null) { cSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredChannel_ = cSelector_.getValue(); } }); } if (imageCache_.lastAcquiredFrame() > 0) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } configureAnimationControls(); setNumPositions(numPositions); } //Load contrast settigns if opening datset if (imageCache_.isFinished()) { } updateAndDraw(false); updateWindowTitleAndStatus(); forcePainting(); }
diff --git a/src/main/java/in/mDev/MiracleM4n/mChatSuite/api/Parser.java b/src/main/java/in/mDev/MiracleM4n/mChatSuite/api/Parser.java index 13f559e..2071c78 100644 --- a/src/main/java/in/mDev/MiracleM4n/mChatSuite/api/Parser.java +++ b/src/main/java/in/mDev/MiracleM4n/mChatSuite/api/Parser.java @@ -1,446 +1,446 @@ package in.mDev.MiracleM4n.mChatSuite.api; import com.herocraftonline.heroes.characters.Hero; import com.herocraftonline.heroes.characters.classes.HeroClass; import com.herocraftonline.heroes.util.Messaging; import in.mDev.MiracleM4n.mChatSuite.mChatSuite; import in.mDev.MiracleM4n.mChatSuite.types.InfoType; import in.mDev.MiracleM4n.mChatSuite.types.LocaleType; import in.mDev.MiracleM4n.mChatSuite.util.Messanger; import org.bukkit.entity.Player; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Parser { mChatSuite plugin; public Parser(mChatSuite instance) { plugin = instance; } /** * Core Formatting * @param pName Name of Player being reflected upon. * @param world Player's World. * @param msg Message being displayed. * @param format Resulting Format. * @return Formatted Message. */ public String parseMessage(String pName, String world, String msg, String format) { Object prefix = plugin.getReader().getRawPrefix(pName, InfoType.USER, world); Object suffix = plugin.getReader().getRawSuffix(pName, InfoType.USER, world); Object group = plugin.getReader().getRawGroup(pName, InfoType.USER, world); String vI = plugin.varIndicator; if (msg == null) msg = ""; if (prefix == null) prefix = ""; if (suffix == null) suffix = ""; if (group == null) group = ""; // Heroes Vars String hSClass = ""; String hClass = ""; String hHealth = ""; String hHBar = ""; String hMana = ""; String hMBar = ""; String hParty = ""; String hMastered = ""; String hLevel = ""; String hSLevel = ""; String hExp = ""; String hSExp = ""; String hEBar = ""; String hSEBar = ""; // Location Double locX = (double) randomNumber(-100, 100); Double locY = (double) randomNumber(-100, 100); Double locZ = (double) randomNumber(-100, 100); String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ); // Health String healthbar = ""; String health = String.valueOf(randomNumber(1, 20)); // World String pWorld = ""; // 1.8 Vars String hungerLevel = String.valueOf(randomNumber(0, 20)); String hungerBar = plugin.getAPI().createBasicBar(randomNumber(0, 20), 20, 10); String level = String.valueOf(randomNumber(1, 2)); String exp = String.valueOf(randomNumber(0, 200))+ "/" + ((randomNumber(1, 2) + 1) * 10); String expBar = plugin.getAPI().createBasicBar(randomNumber(0, 200), ((randomNumber(1, 2) + 1) * 10), 10); String tExp = String.valueOf(randomNumber(0, 300)); String gMode = String.valueOf(randomNumber(0, 1)); // Time Var Date now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat(plugin.dateFormat); String time = dateFormat.format(now); // Display Name String dName = pName; // Chat Distance Type String dType = ""; if (plugin.isShouting.get(pName) != null && plugin.isShouting.get(pName)) { dType = plugin.getLocale().getOption(LocaleType.FORMAT_SHOUT); } else if (plugin.chatDistance > 0) { dType = plugin.getLocale().getOption(LocaleType.FORMAT_LOCAL); } // Chat Distance Type String sType = ""; if (plugin.isSpying.get(pName) != null && plugin.isSpying.get(pName)) sType = plugin.getLocale().getOption(LocaleType.FORMAT_SPY); // Player Object Stuff if (plugin.getServer().getPlayer(pName) != null) { Player player = plugin.getServer().getPlayer(pName); // Location locX = player.getLocation().getX(); locY = player.getLocation().getY(); locZ = player.getLocation().getZ(); loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ); // Health healthbar = plugin.getAPI().createHealthBar(player); health = String.valueOf(player.getHealth()); // World pWorld = player.getWorld().getName(); // 1.8 Vars hungerLevel = String.valueOf(player.getFoodLevel()); hungerBar = plugin.getAPI().createBasicBar(player.getFoodLevel(), 20, 10); level = String.valueOf(player.getLevel()); exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10); expBar = plugin.getAPI().createBasicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10); tExp = String.valueOf(player.getTotalExperience()); gMode = ""; if (player.getGameMode() != null && player.getGameMode().name() != null) gMode = player.getGameMode().name(); // Display Name dName = player.getDisplayName(); // Initialize Heroes Vars if (plugin.heroesB) { Hero hero = plugin.heroes.getCharacterManager().getHero(player); HeroClass heroClass = hero.getHeroClass(); HeroClass heroSClass = hero.getSecondClass(); int hL = hero.getLevel(); int hSL = hero.getLevel(heroSClass); double hE = hero.getExperience(heroClass); double hSE = hero.getExperience(heroSClass); hClass = hero.getHeroClass().getName(); hHealth = String.valueOf(hero.getHealth()); hHBar = Messaging.createHealthBar(hero.getHealth(), hero.getMaxHealth()); hMana = String.valueOf(hero.getMana()); hLevel = String.valueOf(hL); hExp = String.valueOf(hE); hEBar = Messaging.createExperienceBar(hero, heroClass); Integer hMMana = hero.getMaxMana(); if (hMMana != null) hMBar = Messaging.createManaBar(hero.getMana(), hero.getMaxMana()); if (hero.getParty() != null) hParty = hero.getParty().toString(); if (heroSClass != null) { hSClass = heroSClass.getName(); hSLevel = String.valueOf(hSL); hSExp = String.valueOf(hSE); hSEBar = Messaging.createExperienceBar(hero, heroSClass); } if ((hero.isMaster(heroClass)) && (heroSClass == null || hero.isMaster(heroSClass))) hMastered = plugin.hMasterT; else hMastered = plugin.hMasterF; } } String formatAll = parseVars(format, pName, world); msg = msg.replaceAll("%", "%%"); formatAll = formatAll.replaceAll("%", "%%"); if (plugin.cLockRange > 0) msg = fixCaps(msg, plugin.cLockRange); if (formatAll == null) return msg; if (plugin.getAPI().checkPermissions(pName, world, "mchat.coloredchat")) msg = Messanger.addColour(msg); if (!plugin.getAPI().checkPermissions(pName, world, "mchat.censorbypass")) msg = replaceCensoredWords(msg); TreeMap<String, Object> fVarMap = new TreeMap<String, Object>(); TreeMap<String, Object> rVarMap = new TreeMap<String, Object>(); TreeMap<String, Object> lVarMap = new TreeMap<String, Object>(); addVar(fVarMap, vI + "mnameformat," + vI + "mnf", plugin.nameFormat); addVar(fVarMap, vI + "healthbar," + vI + "hb", healthbar); addVar(rVarMap, vI + "distancetype," + vI + "dtype", dType); addVar(rVarMap, vI + "displayname," + vI + "dname," + vI + "dn", dName); addVar(rVarMap, vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb", expBar); addVar(rVarMap, vI + "experience," + vI + "exp", exp); addVar(rVarMap, vI + "gamemode," + vI + "gm", gMode); addVar(rVarMap, vI + "group," + vI + "g", group); addVar(rVarMap, vI + "hungerbar," + vI + "hub", hungerBar); addVar(rVarMap, vI + "hunger", hungerLevel); addVar(rVarMap, vI + "health," + vI + "h", health); addVar(rVarMap, vI + "location," + vI + "loc", loc); addVar(rVarMap, vI + "level," + vI + "l", level); addVar(rVarMap, vI + "mname," + vI + "mn", plugin.getReader().getMName(pName)); addVar(rVarMap, vI + "pname," + vI + "n", pName); addVar(rVarMap, vI + "prefix," + vI + "p", prefix); addVar(rVarMap, vI + "spying," + vI + "spy", sType); addVar(rVarMap, vI + "suffix," + vI + "s", suffix); addVar(rVarMap, vI + "totalexp," + vI + "texp," + vI + "te", tExp); addVar(rVarMap, vI + "time," + vI + "t", time); addVar(rVarMap, vI + "world," + vI + "w", pWorld); addVar(rVarMap, vI + "Groupname," + vI + "Gname," + vI + "G", plugin.getReader().getGroupName(group.toString())); addVar(rVarMap, vI + "HClass," + vI + "HC", hClass); addVar(rVarMap, vI + "HExp," + vI + "HEx", hExp); addVar(rVarMap, vI + "HEBar," + vI + "HEb", hEBar); addVar(rVarMap, vI + "HHBar," + vI + "HHB", hHBar); addVar(rVarMap, vI + "HHealth," + vI + "HH", hHealth); addVar(rVarMap, vI + "HLevel," + vI + "HL", hLevel); addVar(rVarMap, vI + "HMastered," + vI + "HMa", hMastered); addVar(rVarMap, vI + "HMana," + vI + "HMn", hMana); addVar(rVarMap, vI + "HMBar," + vI + "HMb", hMBar); addVar(rVarMap, vI + "HParty," + vI + "HPa", hParty); addVar(rVarMap, vI + "HSecClass," + vI + "HSC", hSClass); addVar(rVarMap, vI + "HSecExp," + vI + "HSEx", hSExp); addVar(rVarMap, vI + "HSecEBar," + vI + "HSEb", hSEBar); addVar(rVarMap, vI + "HSecLevel," + vI + "HSL", hSLevel); addVar(rVarMap, vI + "Worldname," + vI + "Wname," + vI + "W", plugin.getReader().getWorldName(pWorld)); addVar(lVarMap, vI + "message," + vI + "msg," + vI + "m", msg); formatAll = replaceCustVars(pName, formatAll); - formatAll = replaceVars(formatAll, fVarMap.descendingMap(), true); - formatAll = replaceVars(formatAll, rVarMap.descendingMap(), true); + formatAll = Messanger.addColour(replaceVars(formatAll, fVarMap.descendingMap(), true)); + formatAll = Messanger.addColour(replaceVars(formatAll, rVarMap.descendingMap(), true)); formatAll = replaceVars(formatAll, lVarMap.descendingMap(), false); return formatAll; } /** * Chat Formatting * @param pName Name of Player being reflected upon. * @param world Name of Player's World. * @param msg Message being displayed. * @return Formatted Chat Message. */ public String parseChatMessage(String pName, String world, String msg) { return parseMessage(pName, world, msg, plugin.chatFormat); } /** * Player Name Formatting * @param pName Name of Player being reflected upon. * @param world Name of Player's World. * @return Formatted Player Name. */ public String parsePlayerName(String pName, String world) { return parseMessage(pName, world, "", plugin.nameFormat); } /** * Event Message Formatting * @param pName Name of Player being reflected upon. * @param world Name of Player's World. * @return Formatted Event Message. */ public String parseEventName(String pName, String world) { return parseMessage(pName, world, "", plugin.eventFormat); } /** * TabbedList Formatting * @param pName Name of Player being reflected upon. * @param world Name of Player's World. * @return Formatted TabbedList Name. */ public String parseTabbedList(String pName, String world) { return parseMessage(pName, world, "", plugin.tabbedListFormat); } /** * ListCommand Formatting * @param pName Name of Player being reflected upon. * @param world Name of Player's World. * @return Formatted ListCommand Name. */ public String parseListCmd(String pName, String world) { return parseMessage(pName, world, "", plugin.listCmdFormat); } /** * Me Formatting * @param pName Name of Player being reflected upon. * @param world Name of Player's World. * @param msg Message being displayed. * @return Formatted Me Message. */ public String parseMe(String pName, String world, String msg) { return parseMessage(pName, world, msg, plugin.meFormat); } // Misc Stuff private TreeMap<String, Object> addVar(TreeMap<String, Object> map, String keys, Object value) { if (keys.contains(",")) for (String s : keys.split(",")) { if (s == null || value == null) continue; map.put(s, value); } else if (value != null) map.put(keys, value); return map; } private String fixCaps(String format, Integer range) { if (range < 1) return format; Pattern pattern = Pattern.compile("([A-Z]{" + range + ",300})"); Matcher matcher = pattern.matcher(format); StringBuffer sb = new StringBuffer(); while (matcher.find()) matcher.appendReplacement(sb, Matcher.quoteReplacement(matcher.group().toLowerCase())); matcher.appendTail(sb); format = sb.toString(); return format; } private String parseVars(String format, String pName, String world) { String vI = "\\" + plugin.varIndicator; Pattern pattern = Pattern.compile(vI + "<(.*?)>"); Matcher matcher = pattern.matcher(format); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String var = plugin.getReader().getRawInfo(pName, InfoType.USER, world, matcher.group(1)).toString(); matcher.appendReplacement(sb, Matcher.quoteReplacement(var)); } matcher.appendTail(sb); return sb.toString(); } private String replaceVars(String format, Map<String, Object> map, Boolean doColour) { for (Map.Entry<String, Object> entry : map.entrySet()) { String value = entry.getValue().toString(); if (doColour) value = Messanger.addColour(value); format = format.replace(entry.getKey(), value); } return format; } private String replaceCustVars(String pName, String format) { SortedMap<String, String> varMap = plugin.cVarMap.descendingMap(); for (Map.Entry<String, String> entry : varMap.entrySet()) { String pKey = plugin.cusVarIndicator + entry.getKey().replace(pName + "|", ""); String value = entry.getValue(); if (format.contains(pKey)) format = format.replace(pKey, Messanger.addColour(value)); } for (Map.Entry<String, String> entry : varMap.entrySet()) { String gKey = plugin.cusVarIndicator + entry.getKey().replace("%^global^%|", ""); String value = entry.getValue(); if (format.contains(gKey)) format = format.replace(gKey, Messanger.addColour(value)); } return format; } private String replaceCensoredWords(String msg) { if (plugin.useIPRestrict) msg = replacer(msg, "([0-9]{1,3}\\.){3}([0-9]{1,3})", "*.*.*.*"); for (Map.Entry<String, Object> entry : plugin.censor.getValues(false).entrySet()) { String val = entry.getValue().toString(); msg = replacer(msg, "(?i)" + entry.getKey(), val); } return msg; } private String replacer(String msg, String regex, String replacement) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(msg); StringBuffer sb = new StringBuffer(); while (matcher.find()) matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement)); matcher.appendTail(sb); msg = sb.toString(); return msg; } private Integer randomNumber(Integer minValue, Integer maxValue) { Random random = new Random(); return random.nextInt(maxValue - minValue + 1) + minValue; } }
true
true
public String parseMessage(String pName, String world, String msg, String format) { Object prefix = plugin.getReader().getRawPrefix(pName, InfoType.USER, world); Object suffix = plugin.getReader().getRawSuffix(pName, InfoType.USER, world); Object group = plugin.getReader().getRawGroup(pName, InfoType.USER, world); String vI = plugin.varIndicator; if (msg == null) msg = ""; if (prefix == null) prefix = ""; if (suffix == null) suffix = ""; if (group == null) group = ""; // Heroes Vars String hSClass = ""; String hClass = ""; String hHealth = ""; String hHBar = ""; String hMana = ""; String hMBar = ""; String hParty = ""; String hMastered = ""; String hLevel = ""; String hSLevel = ""; String hExp = ""; String hSExp = ""; String hEBar = ""; String hSEBar = ""; // Location Double locX = (double) randomNumber(-100, 100); Double locY = (double) randomNumber(-100, 100); Double locZ = (double) randomNumber(-100, 100); String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ); // Health String healthbar = ""; String health = String.valueOf(randomNumber(1, 20)); // World String pWorld = ""; // 1.8 Vars String hungerLevel = String.valueOf(randomNumber(0, 20)); String hungerBar = plugin.getAPI().createBasicBar(randomNumber(0, 20), 20, 10); String level = String.valueOf(randomNumber(1, 2)); String exp = String.valueOf(randomNumber(0, 200))+ "/" + ((randomNumber(1, 2) + 1) * 10); String expBar = plugin.getAPI().createBasicBar(randomNumber(0, 200), ((randomNumber(1, 2) + 1) * 10), 10); String tExp = String.valueOf(randomNumber(0, 300)); String gMode = String.valueOf(randomNumber(0, 1)); // Time Var Date now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat(plugin.dateFormat); String time = dateFormat.format(now); // Display Name String dName = pName; // Chat Distance Type String dType = ""; if (plugin.isShouting.get(pName) != null && plugin.isShouting.get(pName)) { dType = plugin.getLocale().getOption(LocaleType.FORMAT_SHOUT); } else if (plugin.chatDistance > 0) { dType = plugin.getLocale().getOption(LocaleType.FORMAT_LOCAL); } // Chat Distance Type String sType = ""; if (plugin.isSpying.get(pName) != null && plugin.isSpying.get(pName)) sType = plugin.getLocale().getOption(LocaleType.FORMAT_SPY); // Player Object Stuff if (plugin.getServer().getPlayer(pName) != null) { Player player = plugin.getServer().getPlayer(pName); // Location locX = player.getLocation().getX(); locY = player.getLocation().getY(); locZ = player.getLocation().getZ(); loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ); // Health healthbar = plugin.getAPI().createHealthBar(player); health = String.valueOf(player.getHealth()); // World pWorld = player.getWorld().getName(); // 1.8 Vars hungerLevel = String.valueOf(player.getFoodLevel()); hungerBar = plugin.getAPI().createBasicBar(player.getFoodLevel(), 20, 10); level = String.valueOf(player.getLevel()); exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10); expBar = plugin.getAPI().createBasicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10); tExp = String.valueOf(player.getTotalExperience()); gMode = ""; if (player.getGameMode() != null && player.getGameMode().name() != null) gMode = player.getGameMode().name(); // Display Name dName = player.getDisplayName(); // Initialize Heroes Vars if (plugin.heroesB) { Hero hero = plugin.heroes.getCharacterManager().getHero(player); HeroClass heroClass = hero.getHeroClass(); HeroClass heroSClass = hero.getSecondClass(); int hL = hero.getLevel(); int hSL = hero.getLevel(heroSClass); double hE = hero.getExperience(heroClass); double hSE = hero.getExperience(heroSClass); hClass = hero.getHeroClass().getName(); hHealth = String.valueOf(hero.getHealth()); hHBar = Messaging.createHealthBar(hero.getHealth(), hero.getMaxHealth()); hMana = String.valueOf(hero.getMana()); hLevel = String.valueOf(hL); hExp = String.valueOf(hE); hEBar = Messaging.createExperienceBar(hero, heroClass); Integer hMMana = hero.getMaxMana(); if (hMMana != null) hMBar = Messaging.createManaBar(hero.getMana(), hero.getMaxMana()); if (hero.getParty() != null) hParty = hero.getParty().toString(); if (heroSClass != null) { hSClass = heroSClass.getName(); hSLevel = String.valueOf(hSL); hSExp = String.valueOf(hSE); hSEBar = Messaging.createExperienceBar(hero, heroSClass); } if ((hero.isMaster(heroClass)) && (heroSClass == null || hero.isMaster(heroSClass))) hMastered = plugin.hMasterT; else hMastered = plugin.hMasterF; } } String formatAll = parseVars(format, pName, world); msg = msg.replaceAll("%", "%%"); formatAll = formatAll.replaceAll("%", "%%"); if (plugin.cLockRange > 0) msg = fixCaps(msg, plugin.cLockRange); if (formatAll == null) return msg; if (plugin.getAPI().checkPermissions(pName, world, "mchat.coloredchat")) msg = Messanger.addColour(msg); if (!plugin.getAPI().checkPermissions(pName, world, "mchat.censorbypass")) msg = replaceCensoredWords(msg); TreeMap<String, Object> fVarMap = new TreeMap<String, Object>(); TreeMap<String, Object> rVarMap = new TreeMap<String, Object>(); TreeMap<String, Object> lVarMap = new TreeMap<String, Object>(); addVar(fVarMap, vI + "mnameformat," + vI + "mnf", plugin.nameFormat); addVar(fVarMap, vI + "healthbar," + vI + "hb", healthbar); addVar(rVarMap, vI + "distancetype," + vI + "dtype", dType); addVar(rVarMap, vI + "displayname," + vI + "dname," + vI + "dn", dName); addVar(rVarMap, vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb", expBar); addVar(rVarMap, vI + "experience," + vI + "exp", exp); addVar(rVarMap, vI + "gamemode," + vI + "gm", gMode); addVar(rVarMap, vI + "group," + vI + "g", group); addVar(rVarMap, vI + "hungerbar," + vI + "hub", hungerBar); addVar(rVarMap, vI + "hunger", hungerLevel); addVar(rVarMap, vI + "health," + vI + "h", health); addVar(rVarMap, vI + "location," + vI + "loc", loc); addVar(rVarMap, vI + "level," + vI + "l", level); addVar(rVarMap, vI + "mname," + vI + "mn", plugin.getReader().getMName(pName)); addVar(rVarMap, vI + "pname," + vI + "n", pName); addVar(rVarMap, vI + "prefix," + vI + "p", prefix); addVar(rVarMap, vI + "spying," + vI + "spy", sType); addVar(rVarMap, vI + "suffix," + vI + "s", suffix); addVar(rVarMap, vI + "totalexp," + vI + "texp," + vI + "te", tExp); addVar(rVarMap, vI + "time," + vI + "t", time); addVar(rVarMap, vI + "world," + vI + "w", pWorld); addVar(rVarMap, vI + "Groupname," + vI + "Gname," + vI + "G", plugin.getReader().getGroupName(group.toString())); addVar(rVarMap, vI + "HClass," + vI + "HC", hClass); addVar(rVarMap, vI + "HExp," + vI + "HEx", hExp); addVar(rVarMap, vI + "HEBar," + vI + "HEb", hEBar); addVar(rVarMap, vI + "HHBar," + vI + "HHB", hHBar); addVar(rVarMap, vI + "HHealth," + vI + "HH", hHealth); addVar(rVarMap, vI + "HLevel," + vI + "HL", hLevel); addVar(rVarMap, vI + "HMastered," + vI + "HMa", hMastered); addVar(rVarMap, vI + "HMana," + vI + "HMn", hMana); addVar(rVarMap, vI + "HMBar," + vI + "HMb", hMBar); addVar(rVarMap, vI + "HParty," + vI + "HPa", hParty); addVar(rVarMap, vI + "HSecClass," + vI + "HSC", hSClass); addVar(rVarMap, vI + "HSecExp," + vI + "HSEx", hSExp); addVar(rVarMap, vI + "HSecEBar," + vI + "HSEb", hSEBar); addVar(rVarMap, vI + "HSecLevel," + vI + "HSL", hSLevel); addVar(rVarMap, vI + "Worldname," + vI + "Wname," + vI + "W", plugin.getReader().getWorldName(pWorld)); addVar(lVarMap, vI + "message," + vI + "msg," + vI + "m", msg); formatAll = replaceCustVars(pName, formatAll); formatAll = replaceVars(formatAll, fVarMap.descendingMap(), true); formatAll = replaceVars(formatAll, rVarMap.descendingMap(), true); formatAll = replaceVars(formatAll, lVarMap.descendingMap(), false); return formatAll; }
public String parseMessage(String pName, String world, String msg, String format) { Object prefix = plugin.getReader().getRawPrefix(pName, InfoType.USER, world); Object suffix = plugin.getReader().getRawSuffix(pName, InfoType.USER, world); Object group = plugin.getReader().getRawGroup(pName, InfoType.USER, world); String vI = plugin.varIndicator; if (msg == null) msg = ""; if (prefix == null) prefix = ""; if (suffix == null) suffix = ""; if (group == null) group = ""; // Heroes Vars String hSClass = ""; String hClass = ""; String hHealth = ""; String hHBar = ""; String hMana = ""; String hMBar = ""; String hParty = ""; String hMastered = ""; String hLevel = ""; String hSLevel = ""; String hExp = ""; String hSExp = ""; String hEBar = ""; String hSEBar = ""; // Location Double locX = (double) randomNumber(-100, 100); Double locY = (double) randomNumber(-100, 100); Double locZ = (double) randomNumber(-100, 100); String loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ); // Health String healthbar = ""; String health = String.valueOf(randomNumber(1, 20)); // World String pWorld = ""; // 1.8 Vars String hungerLevel = String.valueOf(randomNumber(0, 20)); String hungerBar = plugin.getAPI().createBasicBar(randomNumber(0, 20), 20, 10); String level = String.valueOf(randomNumber(1, 2)); String exp = String.valueOf(randomNumber(0, 200))+ "/" + ((randomNumber(1, 2) + 1) * 10); String expBar = plugin.getAPI().createBasicBar(randomNumber(0, 200), ((randomNumber(1, 2) + 1) * 10), 10); String tExp = String.valueOf(randomNumber(0, 300)); String gMode = String.valueOf(randomNumber(0, 1)); // Time Var Date now = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat(plugin.dateFormat); String time = dateFormat.format(now); // Display Name String dName = pName; // Chat Distance Type String dType = ""; if (plugin.isShouting.get(pName) != null && plugin.isShouting.get(pName)) { dType = plugin.getLocale().getOption(LocaleType.FORMAT_SHOUT); } else if (plugin.chatDistance > 0) { dType = plugin.getLocale().getOption(LocaleType.FORMAT_LOCAL); } // Chat Distance Type String sType = ""; if (plugin.isSpying.get(pName) != null && plugin.isSpying.get(pName)) sType = plugin.getLocale().getOption(LocaleType.FORMAT_SPY); // Player Object Stuff if (plugin.getServer().getPlayer(pName) != null) { Player player = plugin.getServer().getPlayer(pName); // Location locX = player.getLocation().getX(); locY = player.getLocation().getY(); locZ = player.getLocation().getZ(); loc = ("X: " + locX + ", " + "Y: " + locY + ", " + "Z: " + locZ); // Health healthbar = plugin.getAPI().createHealthBar(player); health = String.valueOf(player.getHealth()); // World pWorld = player.getWorld().getName(); // 1.8 Vars hungerLevel = String.valueOf(player.getFoodLevel()); hungerBar = plugin.getAPI().createBasicBar(player.getFoodLevel(), 20, 10); level = String.valueOf(player.getLevel()); exp = String.valueOf(player.getExp()) + "/" + ((player.getLevel() + 1) * 10); expBar = plugin.getAPI().createBasicBar(player.getExp(), ((player.getLevel() + 1) * 10), 10); tExp = String.valueOf(player.getTotalExperience()); gMode = ""; if (player.getGameMode() != null && player.getGameMode().name() != null) gMode = player.getGameMode().name(); // Display Name dName = player.getDisplayName(); // Initialize Heroes Vars if (plugin.heroesB) { Hero hero = plugin.heroes.getCharacterManager().getHero(player); HeroClass heroClass = hero.getHeroClass(); HeroClass heroSClass = hero.getSecondClass(); int hL = hero.getLevel(); int hSL = hero.getLevel(heroSClass); double hE = hero.getExperience(heroClass); double hSE = hero.getExperience(heroSClass); hClass = hero.getHeroClass().getName(); hHealth = String.valueOf(hero.getHealth()); hHBar = Messaging.createHealthBar(hero.getHealth(), hero.getMaxHealth()); hMana = String.valueOf(hero.getMana()); hLevel = String.valueOf(hL); hExp = String.valueOf(hE); hEBar = Messaging.createExperienceBar(hero, heroClass); Integer hMMana = hero.getMaxMana(); if (hMMana != null) hMBar = Messaging.createManaBar(hero.getMana(), hero.getMaxMana()); if (hero.getParty() != null) hParty = hero.getParty().toString(); if (heroSClass != null) { hSClass = heroSClass.getName(); hSLevel = String.valueOf(hSL); hSExp = String.valueOf(hSE); hSEBar = Messaging.createExperienceBar(hero, heroSClass); } if ((hero.isMaster(heroClass)) && (heroSClass == null || hero.isMaster(heroSClass))) hMastered = plugin.hMasterT; else hMastered = plugin.hMasterF; } } String formatAll = parseVars(format, pName, world); msg = msg.replaceAll("%", "%%"); formatAll = formatAll.replaceAll("%", "%%"); if (plugin.cLockRange > 0) msg = fixCaps(msg, plugin.cLockRange); if (formatAll == null) return msg; if (plugin.getAPI().checkPermissions(pName, world, "mchat.coloredchat")) msg = Messanger.addColour(msg); if (!plugin.getAPI().checkPermissions(pName, world, "mchat.censorbypass")) msg = replaceCensoredWords(msg); TreeMap<String, Object> fVarMap = new TreeMap<String, Object>(); TreeMap<String, Object> rVarMap = new TreeMap<String, Object>(); TreeMap<String, Object> lVarMap = new TreeMap<String, Object>(); addVar(fVarMap, vI + "mnameformat," + vI + "mnf", plugin.nameFormat); addVar(fVarMap, vI + "healthbar," + vI + "hb", healthbar); addVar(rVarMap, vI + "distancetype," + vI + "dtype", dType); addVar(rVarMap, vI + "displayname," + vI + "dname," + vI + "dn", dName); addVar(rVarMap, vI + "experiencebar," + vI + "expb," + vI + "ebar," + vI + "eb", expBar); addVar(rVarMap, vI + "experience," + vI + "exp", exp); addVar(rVarMap, vI + "gamemode," + vI + "gm", gMode); addVar(rVarMap, vI + "group," + vI + "g", group); addVar(rVarMap, vI + "hungerbar," + vI + "hub", hungerBar); addVar(rVarMap, vI + "hunger", hungerLevel); addVar(rVarMap, vI + "health," + vI + "h", health); addVar(rVarMap, vI + "location," + vI + "loc", loc); addVar(rVarMap, vI + "level," + vI + "l", level); addVar(rVarMap, vI + "mname," + vI + "mn", plugin.getReader().getMName(pName)); addVar(rVarMap, vI + "pname," + vI + "n", pName); addVar(rVarMap, vI + "prefix," + vI + "p", prefix); addVar(rVarMap, vI + "spying," + vI + "spy", sType); addVar(rVarMap, vI + "suffix," + vI + "s", suffix); addVar(rVarMap, vI + "totalexp," + vI + "texp," + vI + "te", tExp); addVar(rVarMap, vI + "time," + vI + "t", time); addVar(rVarMap, vI + "world," + vI + "w", pWorld); addVar(rVarMap, vI + "Groupname," + vI + "Gname," + vI + "G", plugin.getReader().getGroupName(group.toString())); addVar(rVarMap, vI + "HClass," + vI + "HC", hClass); addVar(rVarMap, vI + "HExp," + vI + "HEx", hExp); addVar(rVarMap, vI + "HEBar," + vI + "HEb", hEBar); addVar(rVarMap, vI + "HHBar," + vI + "HHB", hHBar); addVar(rVarMap, vI + "HHealth," + vI + "HH", hHealth); addVar(rVarMap, vI + "HLevel," + vI + "HL", hLevel); addVar(rVarMap, vI + "HMastered," + vI + "HMa", hMastered); addVar(rVarMap, vI + "HMana," + vI + "HMn", hMana); addVar(rVarMap, vI + "HMBar," + vI + "HMb", hMBar); addVar(rVarMap, vI + "HParty," + vI + "HPa", hParty); addVar(rVarMap, vI + "HSecClass," + vI + "HSC", hSClass); addVar(rVarMap, vI + "HSecExp," + vI + "HSEx", hSExp); addVar(rVarMap, vI + "HSecEBar," + vI + "HSEb", hSEBar); addVar(rVarMap, vI + "HSecLevel," + vI + "HSL", hSLevel); addVar(rVarMap, vI + "Worldname," + vI + "Wname," + vI + "W", plugin.getReader().getWorldName(pWorld)); addVar(lVarMap, vI + "message," + vI + "msg," + vI + "m", msg); formatAll = replaceCustVars(pName, formatAll); formatAll = Messanger.addColour(replaceVars(formatAll, fVarMap.descendingMap(), true)); formatAll = Messanger.addColour(replaceVars(formatAll, rVarMap.descendingMap(), true)); formatAll = replaceVars(formatAll, lVarMap.descendingMap(), false); return formatAll; }
diff --git a/src/spp/pakpos/controllers/ExplorerTask.java b/src/spp/pakpos/controllers/ExplorerTask.java index 01a5700..80fcf9d 100644 --- a/src/spp/pakpos/controllers/ExplorerTask.java +++ b/src/spp/pakpos/controllers/ExplorerTask.java @@ -1,63 +1,62 @@ package spp.pakpos.controllers; import java.util.ArrayList; import spp.pakpos.PakPos; import spp.pakpos.models.PakPosPath; import spp.pakpos.models.Path; import spp.pakpos.models.PosArea; public class ExplorerTask implements Runnable { private ArrayList<Integer> visitedNodes; private int node; private int totalDistance; public ExplorerTask(ArrayList<Integer> visited, int currentNode, int distance){ visitedNodes = visited; node = currentNode; totalDistance = distance; } @Override public void run() { int inc = PakPos.threadCount.incrementAndGet(); System.out.println(Thread.currentThread().getName() + " is starting: " + inc); if (!PakPos.isVisited(visitedNodes, node)){ visitedNodes.add(node); System.out.println(Thread.currentThread().getName() + ": " +visitedNodes.toString()); System.out.println(Thread.currentThread().getName() + ": " + PakPos.isArrive(node) + ": " + node); if (PakPos.isArrive(node)){ Path validOne = new Path(visitedNodes, totalDistance); PakPosPath.savePath(validOne); System.out.println(Thread.currentThread().getName() + " has saved its works, " + validOne.toString()); } else { ArrayList<Integer> neighbours = PosArea.getNeighbours(node); System.out.println(Thread.currentThread().getName() + " detects neighbour " + neighbours.toString()); for (int i=0; i<neighbours.size(); i++){ System.out.println(Thread.currentThread().getName() + " is checking "); System.out.println(Thread.currentThread().getName() + ": " + neighbours.get(i) + ", " + PosArea.isNeighbour(neighbours.get(i))); if (PosArea.isNeighbour(neighbours.get(i))){ System.out.println(Thread.currentThread().getName() + " is spawning new thread"); // Spawn new thread PakPos.addTask( new ExplorerTask(new ArrayList<Integer>(visitedNodes), i, totalDistance + neighbours.get(i)) ); } else { System.out.println(Thread.currentThread().getName() + " detects invalid neighbour"); } } } } else { System.out.println(Thread.currentThread().getName() + " hit visited node"); } System.out.println(Thread.currentThread().getName() + " has done: " + PakPos.threadCount.decrementAndGet()); if (PakPos.threadCount.get() == 0){ System.out.println(Thread.currentThread().getName() + " is trying to shutdown the pool"); PakPos.threadPool.shutdownNow(); - Thread.currentThread().yield(); } } }
true
true
public void run() { int inc = PakPos.threadCount.incrementAndGet(); System.out.println(Thread.currentThread().getName() + " is starting: " + inc); if (!PakPos.isVisited(visitedNodes, node)){ visitedNodes.add(node); System.out.println(Thread.currentThread().getName() + ": " +visitedNodes.toString()); System.out.println(Thread.currentThread().getName() + ": " + PakPos.isArrive(node) + ": " + node); if (PakPos.isArrive(node)){ Path validOne = new Path(visitedNodes, totalDistance); PakPosPath.savePath(validOne); System.out.println(Thread.currentThread().getName() + " has saved its works, " + validOne.toString()); } else { ArrayList<Integer> neighbours = PosArea.getNeighbours(node); System.out.println(Thread.currentThread().getName() + " detects neighbour " + neighbours.toString()); for (int i=0; i<neighbours.size(); i++){ System.out.println(Thread.currentThread().getName() + " is checking "); System.out.println(Thread.currentThread().getName() + ": " + neighbours.get(i) + ", " + PosArea.isNeighbour(neighbours.get(i))); if (PosArea.isNeighbour(neighbours.get(i))){ System.out.println(Thread.currentThread().getName() + " is spawning new thread"); // Spawn new thread PakPos.addTask( new ExplorerTask(new ArrayList<Integer>(visitedNodes), i, totalDistance + neighbours.get(i)) ); } else { System.out.println(Thread.currentThread().getName() + " detects invalid neighbour"); } } } } else { System.out.println(Thread.currentThread().getName() + " hit visited node"); } System.out.println(Thread.currentThread().getName() + " has done: " + PakPos.threadCount.decrementAndGet()); if (PakPos.threadCount.get() == 0){ System.out.println(Thread.currentThread().getName() + " is trying to shutdown the pool"); PakPos.threadPool.shutdownNow(); Thread.currentThread().yield(); } }
public void run() { int inc = PakPos.threadCount.incrementAndGet(); System.out.println(Thread.currentThread().getName() + " is starting: " + inc); if (!PakPos.isVisited(visitedNodes, node)){ visitedNodes.add(node); System.out.println(Thread.currentThread().getName() + ": " +visitedNodes.toString()); System.out.println(Thread.currentThread().getName() + ": " + PakPos.isArrive(node) + ": " + node); if (PakPos.isArrive(node)){ Path validOne = new Path(visitedNodes, totalDistance); PakPosPath.savePath(validOne); System.out.println(Thread.currentThread().getName() + " has saved its works, " + validOne.toString()); } else { ArrayList<Integer> neighbours = PosArea.getNeighbours(node); System.out.println(Thread.currentThread().getName() + " detects neighbour " + neighbours.toString()); for (int i=0; i<neighbours.size(); i++){ System.out.println(Thread.currentThread().getName() + " is checking "); System.out.println(Thread.currentThread().getName() + ": " + neighbours.get(i) + ", " + PosArea.isNeighbour(neighbours.get(i))); if (PosArea.isNeighbour(neighbours.get(i))){ System.out.println(Thread.currentThread().getName() + " is spawning new thread"); // Spawn new thread PakPos.addTask( new ExplorerTask(new ArrayList<Integer>(visitedNodes), i, totalDistance + neighbours.get(i)) ); } else { System.out.println(Thread.currentThread().getName() + " detects invalid neighbour"); } } } } else { System.out.println(Thread.currentThread().getName() + " hit visited node"); } System.out.println(Thread.currentThread().getName() + " has done: " + PakPos.threadCount.decrementAndGet()); if (PakPos.threadCount.get() == 0){ System.out.println(Thread.currentThread().getName() + " is trying to shutdown the pool"); PakPos.threadPool.shutdownNow(); } }
diff --git a/fog.eclipse/src/de/tuilmenau/ics/fog/eclipse/GraphViewer.java b/fog.eclipse/src/de/tuilmenau/ics/fog/eclipse/GraphViewer.java index 4d6ebcfd..36ccf757 100644 --- a/fog.eclipse/src/de/tuilmenau/ics/fog/eclipse/GraphViewer.java +++ b/fog.eclipse/src/de/tuilmenau/ics/fog/eclipse/GraphViewer.java @@ -1,898 +1,898 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator - Eclipse * Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau. * * 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 de.tuilmenau.ics.fog.eclipse; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Image; import java.awt.Menu; import java.awt.MenuItem; import java.awt.Paint; import java.awt.PopupMenu; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.rmi.RemoteException; import java.util.HashMap; import java.util.Observable; import java.util.Observer; import java.util.Set; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.UIManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.plugin.AbstractUIPlugin; import de.tuilmenau.ics.fog.Config; import de.tuilmenau.ics.fog.IController; import de.tuilmenau.ics.fog.eclipse.ui.Activator; import de.tuilmenau.ics.fog.eclipse.utils.SWTAWTConverter; import de.tuilmenau.ics.fog.routing.simulated.PartialRoutingService; import de.tuilmenau.ics.fog.routing.simulated.RemoteRoutingService; import de.tuilmenau.ics.fog.routing.simulated.RoutingServiceAddress; import de.tuilmenau.ics.fog.topology.Breakable; import de.tuilmenau.ics.fog.topology.Breakable.Status; import de.tuilmenau.ics.fog.topology.ILowerLayer; import de.tuilmenau.ics.fog.topology.NetworkInterface; import de.tuilmenau.ics.fog.topology.Node; import de.tuilmenau.ics.fog.transfer.DummyForwardingElement; import de.tuilmenau.ics.fog.transfer.Gate; import de.tuilmenau.ics.fog.transfer.forwardingNodes.GateContainer; import de.tuilmenau.ics.fog.transfer.gates.AbstractGate; import de.tuilmenau.ics.fog.ui.Decoration; import de.tuilmenau.ics.fog.ui.Decorator; import de.tuilmenau.ics.fog.ui.Logging; import de.tuilmenau.ics.fog.ui.Marker; import de.tuilmenau.ics.fog.ui.MarkerContainer; import de.tuilmenau.ics.fog.ui.PacketLogger; import de.tuilmenau.ics.graph.RoutableGraph; import de.tuilmenau.ics.graph.Transformer; import edu.uci.ics.jung.algorithms.layout.GraphElementAccessor; import edu.uci.ics.jung.algorithms.layout.Layout; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.ObservableGraph; import edu.uci.ics.jung.graph.event.GraphEvent; import edu.uci.ics.jung.graph.event.GraphEventListener; import edu.uci.ics.jung.graph.util.Context; import edu.uci.ics.jung.graph.util.EdgeIndexFunction; import edu.uci.ics.jung.visualization.renderers.DefaultEdgeLabelRenderer; import edu.uci.ics.jung.visualization.renderers.EdgeLabelRenderer; import edu.uci.ics.jung.visualization.FourPassImageShaper; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.RenderContext; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.DefaultModalGraphMouse; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.decorators.AbstractEdgeShapeTransformer; import edu.uci.ics.jung.visualization.decorators.EdgeShape.IndexedRendering; import edu.uci.ics.jung.visualization.renderers.BasicVertexLabelRenderer; import edu.uci.ics.jung.visualization.renderers.Renderer; import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position; import edu.uci.ics.jung.visualization.transform.shape.GraphicsDecorator; /** * Class for displaying a graph in an AWT window. * * @param <NodeObject> Class for the vertices objects of the graph * @param <LinkObject> Class for the edge objects of the graph */ public class GraphViewer<NodeObject, LinkObject> implements Observer, Runnable { // scaling factor for lines: useful for enlarging lines for presentations private final static float SCALE_FACTOR = 1.0f; private final static float VERTEX_STROKE_NORMAL = 1.0f *SCALE_FACTOR; private final static float VERTEX_STROKE_ADD_MAX_MSG = 4.0f; private final static float EDGE_STROKE_NORMAL = 1.0f *SCALE_FACTOR; private final static float EDGE_STROKE_LOGICAL = 0.5f *SCALE_FACTOR; private final static float EDGE_STROKE_GATE = 1.5f *SCALE_FACTOR; public static final int VERTEX_RECTANGLE_HEIGHT = 20; public static final int VERTEX_LABEL_CHAR_WIDTH = 7; public static final int VERTEX_LABEL_ADD_WIDTH = 10; public static final String DEFAULT_DECORATION = "Default"; /** * Font sizes for text; -1=default */ public static final int VERTEX_FONT_SIZE = -1; public static final int EDGE_FONT_SIZE = -1; private final static int MAX_NUMBER_MSG_GATE = 1; private final static float EDGE_STROKE_GATE_ADD_MAX_MSG = 1.0f; private static Color DEFAULT_VERTEX_COLOR = new Color(0f, 0f, 0f, 0.5f); private static Color DEFAULT_EDGE_COLOR = Color.BLACK; private static Color ERROR_EDGE_COLOR = Color.ORANGE; private static Color MULTIPLE_MARKING_COLOR = Color.RED; public GraphViewer(IController pController) { mController = pController; } public Component getComponent() { return mViewer; } public void init(RoutableGraph<NodeObject, LinkObject> pGraph) { mViewUpdateRunning = false; createGraphView(pGraph.getGraphForGUI()); createInteraction(); pGraph.addObserver(this); } @Override public void update(Observable observable, Object parameter) { synchronized (this) { // if it is already running: do not proceed if(mViewUpdateRunning) { return; } mViewUpdateRunning = true; } if(EventQueue.isDispatchThread()) { run(); } else { // switch to AWT event queue EventQueue.invokeLater(this); } } @Override public void run() { mViewer.updateUI(); synchronized (this) { mViewUpdateRunning = false; } } /** * Calculated a load value [0, 1] for an element. According to this * value, the GUI can highlight the element. * * @param obj Element to calculate the load for * @return load value [0, 1] OR negative if no load can be calculated */ protected static float getLoadLevel(Object obj) { PacketLogger log = PacketLogger.getLogger(obj); if(log != null) { return ((float)log.size()/(float)log.getMaxSize()); } if(obj instanceof Gate) { return Math.min(1.0f, (float)((Gate) obj).getNumberMessages(false)/(float)MAX_NUMBER_MSG_GATE); } return -1; } public class BentLine<V,E> extends AbstractEdgeShapeTransformer<V,E> implements IndexedRendering<V,E> { /** * singleton instance of the BentLine shape */ private GeneralPath instance = new GeneralPath(); protected EdgeIndexFunction<V,E> parallelEdgeIndexFunction; public void setEdgeIndexFunction(EdgeIndexFunction<V,E> parallelEdgeIndexFunction) { this.parallelEdgeIndexFunction = parallelEdgeIndexFunction; // loop.setEdgeIndexFunction(parallelEdgeIndexFunction); } /** * @return the parallelEdgeIndexFunction */ public EdgeIndexFunction<V, E> getEdgeIndexFunction() { return parallelEdgeIndexFunction; } /** * Get the shape for this edge, returning either the * shared instance or, in the case of self-loop edges, the * Loop shared instance. */ public Shape transform(Context<Graph<V,E>,E> context) { E e = context.element; instance.reset(); instance.moveTo(0.0f, 0.0f); if(e instanceof NetworkInterface) { NetworkInterface ni = (NetworkInterface) e; PacketLogger log = PacketLogger.getLogger(ni.getBus()); if(log != null) { int parts = log.size() +1; float dist = 1.0f / (float) parts; for(int i=0; i<parts; i++) { instance.lineTo(i*dist, 0.0f); instance.lineTo(i*dist, 1.0f); instance.lineTo(i*dist, -1.0f); instance.moveTo(i*dist, 0.0f); } } } instance.lineTo(1.0f, 0.0f); return instance; } } public class vertexLabelRenderer extends BasicVertexLabelRenderer<NodeObject, LinkObject> { // the space between vertex shape and label final double tLabelOffset = 10; final Color labelBackgroundColor = new Color(255,255,128); public Component prepareRenderer(RenderContext<NodeObject,LinkObject> pRc, EdgeLabelRenderer pGraphLabelRenderer, Object pValue, boolean pIsSelected, NodeObject pNode) { return pRc.getVertexLabelRenderer().<NodeObject>getVertexLabelRendererComponent(pRc.getScreenDevice(), pValue, pRc.getVertexFontTransformer().transform(pNode), pIsSelected, pNode); } public void labelVertex(RenderContext<NodeObject, LinkObject> pRc, Layout<NodeObject, LinkObject> pLayout, NodeObject pNode, String pLabel) { GraphicsDecorator tGraphicsDecorator = pRc.getGraphicsContext(); Shape tShape = pRc.getVertexShapeTransformer().transform(pNode); Point2D tNodePos = pLayout.transform(pNode); tNodePos = pRc.getMultiLayerTransformer().transform(Layer.LAYOUT, tNodePos); // does the node itself contain decoration information? if(pNode instanceof Decorator) { String tExplicitLabel = ((Decorator) pNode).getText(); if(tExplicitLabel != null) { pLabel = tExplicitLabel; } } // is there a decoration container with some additional information? if(mDecoration != null) { Decorator tDec = mDecoration.getDecorator(pNode); if(tDec != null) { String tAddLabel = tDec.getText(); if(tAddLabel != null) { pLabel += " " +tAddLabel; } } } Component tComponent = prepareRenderer(pRc, pRc.getEdgeLabelRenderer(), (Object)pLabel, pRc.getPickedVertexState().isPicked(pNode), pNode); Dimension tDimension = tComponent.getPreferredSize(); tDimension.width += VERTEX_LABEL_ADD_WIDTH; int tPosX = (int) (tNodePos.getX() - (tDimension.width - VERTEX_LABEL_ADD_WIDTH)/ 2); int tPosY = (int) (tNodePos.getY() - tDimension.height / 2); Rectangle tShapeBound = tShape.getBounds(); if (tShapeBound.getHeight() != VERTEX_RECTANGLE_HEIGHT) { tPosY += tLabelOffset + tShapeBound.getHeight() / 2; //picture for hosts is special -> use an additional offset if (pNode instanceof Node) tPosX += 4; } // finally draw the label component tGraphicsDecorator.draw(tComponent, pRc.getRendererPane(), tPosX, tPosY, tDimension.width, tDimension.height, true); } } private Image loadImageFor(Object pObj) { if(pObj instanceof DummyForwardingElement) { pObj = ((DummyForwardingElement) pObj).getObject(); } String imageName = pObj.getClass().getCanonicalName() +".gif"; // is there a different name given by a decorator? if(pObj instanceof Decorator) { String decorationImageName = ((Decorator) pObj).getImageName(); if(decorationImageName != null) imageName = decorationImageName; } else { if(mDecoration != null) { Decorator decorator = mDecoration.getDecorator(pObj); if(decorator != null) { String decorationImageName = decorator.getImageName(); if(decorationImageName != null) { imageName = decorationImageName; } } } } return loadImage(imageName); } private Image loadImage(String pFile) { BufferedImage tImage = mIcons.get(pFile); if(tImage == null) { if(!mIcons.containsKey(pFile)) { ImageDescriptor tImageDescr = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/" + pFile); if(tImageDescr != null) { tImage = SWTAWTConverter.convertToAWT(tImageDescr.getImageData()); } // if tImage is null, store the null pointer // to indicate that there is no image available mIcons.put(pFile, tImage); } // else: already tried, but stored null pointer } return tImage; } private Icon loadIconFor(Object pObj) { try { Image tImage = loadImageFor(pObj); if(tImage != null) { return new ImageIcon(tImage); } else { return null; } } catch (Exception e) { return null; } } /** * Creates the objects needed for the view. Most of them bases on the * JUNG lib. * * @param pX Width of the window * @param pY Height of the window * @param pGraph Graph, which should be displayed */ private void createGraphView(Graph<NodeObject, LinkObject> pGraph) { ObservableGraph<NodeObject, LinkObject> tObsGraph = new ObservableGraph<NodeObject, LinkObject>(pGraph); tObsGraph.addGraphEventListener(new GraphEventListener<NodeObject, LinkObject>() { public void handleGraphEvent(GraphEvent<NodeObject, LinkObject> pEvent) { updateVisualization(); } }); // create layout mLayout = new edu.uci.ics.jung.algorithms.layout.FRLayout2<NodeObject, LinkObject>(tObsGraph); Shell activeShell = Display.getDefault().getActiveShell(); org.eclipse.swt.graphics.Rectangle tRectangle; if(activeShell != null) { tRectangle = activeShell.getBounds(); } else { tRectangle = new org.eclipse.swt.graphics.Rectangle(0,0, 300,300); } double tWidth = tRectangle.width * 0.4; double tHeight = tRectangle.height*0.4; //Logging.log(this, "Old size was " + tRectangle.width + "x" + tRectangle.height + " while new size will be " + tWidth + "x" + tHeight); mLayout.setSize(new Dimension((int)tWidth, (int)tHeight)); // create viewer mViewer = new VisualizationViewer<NodeObject, LinkObject>(mLayout); mViewer.setDoubleBuffered(true); mViewer.setPreferredSize(new Dimension((int)tWidth, (int)tHeight)); // setting up view of graph itself // Setup up a new vertex to paint transformer... Transformer<NodeObject, Paint> vertexPaint = new Transformer<NodeObject, Paint>() { private final Color colorBlue = new Color(.1f, .3f, 1f); private final Color colorYellow = new Color(1f, 1f, .3f); private final Color colorGreen = new Color(.1f, .9f, .3f); public Paint transform(Object i) { if(i instanceof DummyForwardingElement) { i = ((DummyForwardingElement) i).getObject(); } if (i instanceof AbstractGate) return Color.LIGHT_GRAY; if (i instanceof GateContainer) return colorGreen; if (i instanceof ILowerLayer) return colorYellow; // does the object define its color by itself? if(i instanceof Decorator) { Color decColor = ((Decorator) i).getColor(); if(decColor != null) { return decColor; } } // is there an external decorator for the object? if(mDecoration != null) { Decorator decorator = mDecoration.getDecorator(i); if(decorator != null) { Color decColor = decorator.getColor(); if(decColor != null) { return decColor; } } } if (i instanceof PartialRoutingService) return Color.ORANGE; if (i instanceof RemoteRoutingService) return colorBlue; if (i instanceof RoutingServiceAddress) return colorBlue; return Color.WHITE; } }; Transformer<NodeObject, Shape> vertexShapeTransformer = new Transformer<NodeObject, Shape>() { public Shape transform(NodeObject pObj) { Image tImage = loadImageFor(pObj); if(tImage != null) { Shape tShape = FourPassImageShaper.getShape(tImage); if(tShape.getBounds().getWidth() > 0 && tShape.getBounds().getHeight() > 0) { AffineTransform transform = AffineTransform.getTranslateInstance( - tImage.getWidth(null) / 2, - tImage.getHeight(null) / 2); tShape = transform.createTransformedShape(tShape); return tShape; } } String tLabel = mViewer.getRenderContext().getVertexLabelTransformer().transform(pObj); return new Rectangle( - (tLabel.length() * VERTEX_LABEL_CHAR_WIDTH + VERTEX_LABEL_ADD_WIDTH) / 2, - VERTEX_RECTANGLE_HEIGHT / 2, tLabel.length() * VERTEX_LABEL_CHAR_WIDTH + VERTEX_LABEL_ADD_WIDTH, VERTEX_RECTANGLE_HEIGHT); } }; Transformer<NodeObject, Icon> vertexIconTransformer = new Transformer<NodeObject, Icon>() { public Icon transform(NodeObject pObj) { return loadIconFor(pObj); } }; // Set up a new stroke Transformer for the edges Transformer<NodeObject, Stroke> vertexStrokeTransformer = new Transformer<NodeObject, Stroke>() { private final Stroke normalEdgeStroke = new BasicStroke(VERTEX_STROKE_NORMAL); public Stroke transform(Object pVertex) { float loadLevel = getLoadLevel(pVertex); if(loadLevel > 0) { return new BasicStroke(VERTEX_STROKE_NORMAL +VERTEX_STROKE_ADD_MAX_MSG * loadLevel); } else { return normalEdgeStroke; } } }; Transformer<NodeObject, Paint> vertexDraw = new Transformer<NodeObject, Paint>() { public Paint transform(Object pVertex) { Boolean tBroken = false; if (pVertex instanceof Breakable) { try { tBroken = ((Breakable)pVertex).isBroken() != Status.OK; } catch(RemoteException exc) { tBroken = true; } } if (tBroken) { return Color.RED; } else { Marker[] tMarkers = MarkerContainer.getInstance().get(pVertex); if(tMarkers.length > 0) { if(tMarkers.length > 1) { if(Config.Routing.USE_SPECIAL_MULTIPLE_MARKING_COLOR){ return MULTIPLE_MARKING_COLOR; }else{ return tMarkers[tMarkers.length - 1].getColor(); } } else { return tMarkers[0].getColor(); } } else { // // if the background is colored with a special an R/G/B color, we use white as frame color in order to have readable strings // if(pVertex instanceof IElementDecorator && ((IElementDecorator)pVertex).getDecorationParameter() != null && ((IElementDecorator)pVertex).getDecorationParameter() instanceof IElementDecorator.Color) { // IElementDecorator tDecorator = (IElementDecorator)pVertex; // if(tDecorator.getDecorationParameter() != null){ // return Color.WHITE; // } // } return DEFAULT_VERTEX_COLOR; } } } }; Transformer<LinkObject, Paint> edgeDraw = new Transformer<LinkObject, Paint>() { @Override public Paint transform(LinkObject pLink) { Marker[] tMarkers = MarkerContainer.getInstance().get(pLink); if(tMarkers.length > 0) { if(tMarkers.length > 1) { if(Config.Routing.USE_SPECIAL_MULTIPLE_MARKING_COLOR){ return MULTIPLE_MARKING_COLOR; }else{ return tMarkers[tMarkers.length - 1].getColor(); } } else { return tMarkers[0].getColor(); } } else { if(pLink instanceof Gate) { if(!((Gate)pLink).isOperational()) { return ERROR_EDGE_COLOR; } } return DEFAULT_EDGE_COLOR; } } }; Transformer<NodeObject, String> vertexLabeller = new Transformer<NodeObject, String>() { public String transform(Object s) { String tName = s.toString(); if (s instanceof RemoteRoutingService) { try { tName = ((RemoteRoutingService)s).getName(); } catch (RemoteException e) { // ignore it; we will stick to the previous tName } } return tName; } }; // Set up a new stroke Transformer for the edges Transformer<LinkObject, Stroke> edgeStrokeTransformer = new Transformer<LinkObject, Stroke>() { private final Stroke normalEdgeStroke = new BasicStroke(EDGE_STROKE_NORMAL); private final Stroke logicalEdgeStroke = new BasicStroke(EDGE_STROKE_LOGICAL, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{10.0f}, 0.0f); private final Stroke gateEdgeStroke = new BasicStroke(EDGE_STROKE_GATE); public Stroke transform(Object s) { float loadLevel = getLoadLevel(s); if(loadLevel > 0) { return new BasicStroke(EDGE_STROKE_GATE +EDGE_STROKE_GATE_ADD_MAX_MSG * loadLevel); } else if(s instanceof Gate) { return gateEdgeStroke; } else if(s.toString().regionMatches(0, "routing for", 0, "routing for".length())) { return logicalEdgeStroke; } return normalEdgeStroke; } }; Transformer<LinkObject, String> edgeLabeller = new Transformer<LinkObject, String>() { public String transform(Object edge) { if(edge == null) return "null"; // use StringBuilder in order to boost performance of string creation StringBuilder tName = null; if(edge instanceof Gate) { tName = new StringBuilder(); if(((Gate) edge).getGateID() != null) { tName.append(((Gate) edge).getGateID()); tName.append(" "); } tName.append(edge.getClass().getSimpleName()); tName.append(" ("); tName.append(((Gate) edge).getNumberMessages(false)); tName.append(")"); } else if(edge instanceof NetworkInterface) { - return "LL_" +((NetworkInterface) edge).getLowerLayerID(); + return "";//"LL_" +((NetworkInterface) edge).getLowerLayerID(); } if(tName == null) return edge.toString(); else return tName.toString(); } }; EdgeLabelRenderer edgeLabelRenderer = new DefaultEdgeLabelRenderer(Color.BLACK) { private final Color colorBg = (Color)UIManager.getDefaults().get("Panel.background"); private final Color colorEdgeBackground = new Color(colorBg.getRed(), colorBg.getGreen(), colorBg.getBlue(), 128); @Override public <T> Component getEdgeLabelRendererComponent(JComponent arg0, Object arg1, Font arg2, boolean arg3, T arg4) { Component tRes = super.getEdgeLabelRendererComponent(arg0, arg1, arg2, arg3, arg4); tRes.setBackground(colorEdgeBackground); return tRes; } }; Transformer<LinkObject, Font> edgeFontTransformer = new Transformer<LinkObject, Font>() { public Font transform(LinkObject edge) { if(edge == null) return null; return edgeFont; } private Font edgeFont = new Font("SansSerif", Font.PLAIN, EDGE_FONT_SIZE); }; Transformer<NodeObject, Font> vertexFontTransformer = new Transformer<NodeObject, Font>() { public Font transform(NodeObject vertex) { if(vertex == null) return null; return vertexFont; } private Font vertexFont = new Font("SansSerif", Font.PLAIN, VERTEX_FONT_SIZE); }; mViewer.getRenderContext().setVertexFillPaintTransformer(vertexPaint); mViewer.getRenderContext().setVertexDrawPaintTransformer(vertexDraw); mViewer.getRenderContext().setVertexStrokeTransformer(vertexStrokeTransformer); mViewer.getRenderContext().setVertexShapeTransformer(vertexShapeTransformer); mViewer.getRenderContext().setVertexIconTransformer(vertexIconTransformer); mViewer.getRenderer().setVertexLabelRenderer(new vertexLabelRenderer()); mViewer.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.S); // mViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<NodeObject>()); mViewer.getRenderContext().setVertexLabelTransformer(vertexLabeller); mViewer.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); if(VERTEX_FONT_SIZE > 0) { mViewer.getRenderContext().setVertexFontTransformer(vertexFontTransformer); } // mViewer.getRenderContext().setEdgeShapeTransformer(new BentLine<NodeObject,LinkObject>()); mViewer.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); mViewer.getRenderContext().setEdgeDrawPaintTransformer(edgeDraw); mViewer.getRenderContext().setArrowDrawPaintTransformer(edgeDraw); mViewer.getRenderContext().setArrowFillPaintTransformer(edgeDraw); mViewer.getRenderContext().setEdgeLabelTransformer(edgeLabeller); mViewer.getRenderContext().setEdgeLabelRenderer(edgeLabelRenderer); if(EDGE_FONT_SIZE > 0) { mViewer.getRenderContext().setEdgeFontTransformer(edgeFontTransformer); } } /** * Creating the objects reacting to user input. * In special, the handling of the mouse click events are defined here. */ private void createInteraction() { // Create a graph mouse and add it to the visualization component mMouse = new DefaultModalGraphMouse() { @Override public void mousePressed(MouseEvent pEvent) { super.mousePressed(pEvent); if(pEvent.isPopupTrigger()) { Object pSelection = getSelection(pEvent); PopupMenu popup = new PopupMenu(); mController.fillContextMenu(pSelection, popup); fillStdPopup(popup); // should the popup be displayed? if(popup.getItemCount() > 0) { if(popup.getParent() == null) { pEvent.getComponent().add(popup); } popup.show(pEvent.getComponent(), pEvent.getX(), pEvent.getY()); } } } @Override public void mouseReleased(MouseEvent pEvent) { super.mouseReleased(pEvent); if(pEvent.isPopupTrigger()) { Object pSelection = getSelection(pEvent); PopupMenu popup = new PopupMenu(); mController.fillContextMenu(pSelection, popup); fillStdPopup(popup); // should the popup be displayed? if(popup.getItemCount() > 0) { if(popup.getParent() == null) { pEvent.getComponent().add(popup); } popup.show(pEvent.getComponent(), pEvent.getX(), pEvent.getY()); } } } @Override public void mouseClicked(MouseEvent pEvent) { super.mouseClicked(pEvent); mController.selected(getSelection(pEvent), (pEvent.getButton() == MouseEvent.BUTTON1), pEvent.getClickCount()); } private Object getSelection(MouseEvent pEvent) { // try to get selected node or link GraphElementAccessor<NodeObject, LinkObject> tAccessor = mViewer.getPickSupport(); Object tSelection = tAccessor.getVertex(mLayout, pEvent.getX(), pEvent.getY()); if(tSelection == null) { tSelection = tAccessor.getEdge(mLayout, pEvent.getX(), pEvent.getY()); } if(tSelection instanceof DummyForwardingElement) { tSelection = ((DummyForwardingElement) tSelection).getObject(); } return tSelection; } }; mMouse.setMode(ModalGraphMouse.Mode.PICKING); mViewer.setGraphMouse(mMouse); } private void fillStdPopup(PopupMenu popup) { MenuItem mi; // if already some items listed, separate them from the default if(popup.getItemCount() > 0) { popup.addSeparator(); } mi = new MenuItem("Picking"); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if(mMouse != null) mMouse.setMode(ModalGraphMouse.Mode.PICKING); } }); popup.add(mi); mi = new MenuItem("Transforming"); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(mMouse != null) mMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING); } }); popup.add(mi); // // Add decorator selection menu // Menu decMenu = new Menu("Decoration types"); popup.add(decMenu); mi = new MenuItem("None"); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mDecoration = null; update(null, null); } }); decMenu.add(mi); Set<String> decorationTypes = Decoration.getTypes(); for(String decType : decorationTypes) { mi = new MenuItem(decType); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String decType = e.getActionCommand(); mDecoration = Decoration.getInstance(decType); update(null, null); } }); decMenu.add(mi); } } /** * Will be called by event, if graph changes */ private void updateVisualization() { if((mViewer != null) && (mLayout != null)) { if(mViewer.getModel().getRelaxer() != null) mViewer.getModel().getRelaxer().pause(); mLayout.initialize(); if(mViewer.getModel().getRelaxer() != null) mViewer.getModel().getRelaxer().resume(); mViewer.repaint(); } } public String toString() { return getClass().getSimpleName(); } private Layout<NodeObject, LinkObject> mLayout; private VisualizationViewer<NodeObject, LinkObject> mViewer; private boolean mViewUpdateRunning = false; private IController mController; private Decoration mDecoration = Decoration.getInstance(DEFAULT_DECORATION); private DefaultModalGraphMouse mMouse; private HashMap<String, BufferedImage> mIcons = new HashMap<String, BufferedImage>(); }
true
true
private void createGraphView(Graph<NodeObject, LinkObject> pGraph) { ObservableGraph<NodeObject, LinkObject> tObsGraph = new ObservableGraph<NodeObject, LinkObject>(pGraph); tObsGraph.addGraphEventListener(new GraphEventListener<NodeObject, LinkObject>() { public void handleGraphEvent(GraphEvent<NodeObject, LinkObject> pEvent) { updateVisualization(); } }); // create layout mLayout = new edu.uci.ics.jung.algorithms.layout.FRLayout2<NodeObject, LinkObject>(tObsGraph); Shell activeShell = Display.getDefault().getActiveShell(); org.eclipse.swt.graphics.Rectangle tRectangle; if(activeShell != null) { tRectangle = activeShell.getBounds(); } else { tRectangle = new org.eclipse.swt.graphics.Rectangle(0,0, 300,300); } double tWidth = tRectangle.width * 0.4; double tHeight = tRectangle.height*0.4; //Logging.log(this, "Old size was " + tRectangle.width + "x" + tRectangle.height + " while new size will be " + tWidth + "x" + tHeight); mLayout.setSize(new Dimension((int)tWidth, (int)tHeight)); // create viewer mViewer = new VisualizationViewer<NodeObject, LinkObject>(mLayout); mViewer.setDoubleBuffered(true); mViewer.setPreferredSize(new Dimension((int)tWidth, (int)tHeight)); // setting up view of graph itself // Setup up a new vertex to paint transformer... Transformer<NodeObject, Paint> vertexPaint = new Transformer<NodeObject, Paint>() { private final Color colorBlue = new Color(.1f, .3f, 1f); private final Color colorYellow = new Color(1f, 1f, .3f); private final Color colorGreen = new Color(.1f, .9f, .3f); public Paint transform(Object i) { if(i instanceof DummyForwardingElement) { i = ((DummyForwardingElement) i).getObject(); } if (i instanceof AbstractGate) return Color.LIGHT_GRAY; if (i instanceof GateContainer) return colorGreen; if (i instanceof ILowerLayer) return colorYellow; // does the object define its color by itself? if(i instanceof Decorator) { Color decColor = ((Decorator) i).getColor(); if(decColor != null) { return decColor; } } // is there an external decorator for the object? if(mDecoration != null) { Decorator decorator = mDecoration.getDecorator(i); if(decorator != null) { Color decColor = decorator.getColor(); if(decColor != null) { return decColor; } } } if (i instanceof PartialRoutingService) return Color.ORANGE; if (i instanceof RemoteRoutingService) return colorBlue; if (i instanceof RoutingServiceAddress) return colorBlue; return Color.WHITE; } }; Transformer<NodeObject, Shape> vertexShapeTransformer = new Transformer<NodeObject, Shape>() { public Shape transform(NodeObject pObj) { Image tImage = loadImageFor(pObj); if(tImage != null) { Shape tShape = FourPassImageShaper.getShape(tImage); if(tShape.getBounds().getWidth() > 0 && tShape.getBounds().getHeight() > 0) { AffineTransform transform = AffineTransform.getTranslateInstance( - tImage.getWidth(null) / 2, - tImage.getHeight(null) / 2); tShape = transform.createTransformedShape(tShape); return tShape; } } String tLabel = mViewer.getRenderContext().getVertexLabelTransformer().transform(pObj); return new Rectangle( - (tLabel.length() * VERTEX_LABEL_CHAR_WIDTH + VERTEX_LABEL_ADD_WIDTH) / 2, - VERTEX_RECTANGLE_HEIGHT / 2, tLabel.length() * VERTEX_LABEL_CHAR_WIDTH + VERTEX_LABEL_ADD_WIDTH, VERTEX_RECTANGLE_HEIGHT); } }; Transformer<NodeObject, Icon> vertexIconTransformer = new Transformer<NodeObject, Icon>() { public Icon transform(NodeObject pObj) { return loadIconFor(pObj); } }; // Set up a new stroke Transformer for the edges Transformer<NodeObject, Stroke> vertexStrokeTransformer = new Transformer<NodeObject, Stroke>() { private final Stroke normalEdgeStroke = new BasicStroke(VERTEX_STROKE_NORMAL); public Stroke transform(Object pVertex) { float loadLevel = getLoadLevel(pVertex); if(loadLevel > 0) { return new BasicStroke(VERTEX_STROKE_NORMAL +VERTEX_STROKE_ADD_MAX_MSG * loadLevel); } else { return normalEdgeStroke; } } }; Transformer<NodeObject, Paint> vertexDraw = new Transformer<NodeObject, Paint>() { public Paint transform(Object pVertex) { Boolean tBroken = false; if (pVertex instanceof Breakable) { try { tBroken = ((Breakable)pVertex).isBroken() != Status.OK; } catch(RemoteException exc) { tBroken = true; } } if (tBroken) { return Color.RED; } else { Marker[] tMarkers = MarkerContainer.getInstance().get(pVertex); if(tMarkers.length > 0) { if(tMarkers.length > 1) { if(Config.Routing.USE_SPECIAL_MULTIPLE_MARKING_COLOR){ return MULTIPLE_MARKING_COLOR; }else{ return tMarkers[tMarkers.length - 1].getColor(); } } else { return tMarkers[0].getColor(); } } else { // // if the background is colored with a special an R/G/B color, we use white as frame color in order to have readable strings // if(pVertex instanceof IElementDecorator && ((IElementDecorator)pVertex).getDecorationParameter() != null && ((IElementDecorator)pVertex).getDecorationParameter() instanceof IElementDecorator.Color) { // IElementDecorator tDecorator = (IElementDecorator)pVertex; // if(tDecorator.getDecorationParameter() != null){ // return Color.WHITE; // } // } return DEFAULT_VERTEX_COLOR; } } } }; Transformer<LinkObject, Paint> edgeDraw = new Transformer<LinkObject, Paint>() { @Override public Paint transform(LinkObject pLink) { Marker[] tMarkers = MarkerContainer.getInstance().get(pLink); if(tMarkers.length > 0) { if(tMarkers.length > 1) { if(Config.Routing.USE_SPECIAL_MULTIPLE_MARKING_COLOR){ return MULTIPLE_MARKING_COLOR; }else{ return tMarkers[tMarkers.length - 1].getColor(); } } else { return tMarkers[0].getColor(); } } else { if(pLink instanceof Gate) { if(!((Gate)pLink).isOperational()) { return ERROR_EDGE_COLOR; } } return DEFAULT_EDGE_COLOR; } } }; Transformer<NodeObject, String> vertexLabeller = new Transformer<NodeObject, String>() { public String transform(Object s) { String tName = s.toString(); if (s instanceof RemoteRoutingService) { try { tName = ((RemoteRoutingService)s).getName(); } catch (RemoteException e) { // ignore it; we will stick to the previous tName } } return tName; } }; // Set up a new stroke Transformer for the edges Transformer<LinkObject, Stroke> edgeStrokeTransformer = new Transformer<LinkObject, Stroke>() { private final Stroke normalEdgeStroke = new BasicStroke(EDGE_STROKE_NORMAL); private final Stroke logicalEdgeStroke = new BasicStroke(EDGE_STROKE_LOGICAL, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{10.0f}, 0.0f); private final Stroke gateEdgeStroke = new BasicStroke(EDGE_STROKE_GATE); public Stroke transform(Object s) { float loadLevel = getLoadLevel(s); if(loadLevel > 0) { return new BasicStroke(EDGE_STROKE_GATE +EDGE_STROKE_GATE_ADD_MAX_MSG * loadLevel); } else if(s instanceof Gate) { return gateEdgeStroke; } else if(s.toString().regionMatches(0, "routing for", 0, "routing for".length())) { return logicalEdgeStroke; } return normalEdgeStroke; } }; Transformer<LinkObject, String> edgeLabeller = new Transformer<LinkObject, String>() { public String transform(Object edge) { if(edge == null) return "null"; // use StringBuilder in order to boost performance of string creation StringBuilder tName = null; if(edge instanceof Gate) { tName = new StringBuilder(); if(((Gate) edge).getGateID() != null) { tName.append(((Gate) edge).getGateID()); tName.append(" "); } tName.append(edge.getClass().getSimpleName()); tName.append(" ("); tName.append(((Gate) edge).getNumberMessages(false)); tName.append(")"); } else if(edge instanceof NetworkInterface) { return "LL_" +((NetworkInterface) edge).getLowerLayerID(); } if(tName == null) return edge.toString(); else return tName.toString(); } }; EdgeLabelRenderer edgeLabelRenderer = new DefaultEdgeLabelRenderer(Color.BLACK) { private final Color colorBg = (Color)UIManager.getDefaults().get("Panel.background"); private final Color colorEdgeBackground = new Color(colorBg.getRed(), colorBg.getGreen(), colorBg.getBlue(), 128); @Override public <T> Component getEdgeLabelRendererComponent(JComponent arg0, Object arg1, Font arg2, boolean arg3, T arg4) { Component tRes = super.getEdgeLabelRendererComponent(arg0, arg1, arg2, arg3, arg4); tRes.setBackground(colorEdgeBackground); return tRes; } }; Transformer<LinkObject, Font> edgeFontTransformer = new Transformer<LinkObject, Font>() { public Font transform(LinkObject edge) { if(edge == null) return null; return edgeFont; } private Font edgeFont = new Font("SansSerif", Font.PLAIN, EDGE_FONT_SIZE); }; Transformer<NodeObject, Font> vertexFontTransformer = new Transformer<NodeObject, Font>() { public Font transform(NodeObject vertex) { if(vertex == null) return null; return vertexFont; } private Font vertexFont = new Font("SansSerif", Font.PLAIN, VERTEX_FONT_SIZE); }; mViewer.getRenderContext().setVertexFillPaintTransformer(vertexPaint); mViewer.getRenderContext().setVertexDrawPaintTransformer(vertexDraw); mViewer.getRenderContext().setVertexStrokeTransformer(vertexStrokeTransformer); mViewer.getRenderContext().setVertexShapeTransformer(vertexShapeTransformer); mViewer.getRenderContext().setVertexIconTransformer(vertexIconTransformer); mViewer.getRenderer().setVertexLabelRenderer(new vertexLabelRenderer()); mViewer.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.S); // mViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<NodeObject>()); mViewer.getRenderContext().setVertexLabelTransformer(vertexLabeller); mViewer.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); if(VERTEX_FONT_SIZE > 0) { mViewer.getRenderContext().setVertexFontTransformer(vertexFontTransformer); } // mViewer.getRenderContext().setEdgeShapeTransformer(new BentLine<NodeObject,LinkObject>()); mViewer.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); mViewer.getRenderContext().setEdgeDrawPaintTransformer(edgeDraw); mViewer.getRenderContext().setArrowDrawPaintTransformer(edgeDraw); mViewer.getRenderContext().setArrowFillPaintTransformer(edgeDraw); mViewer.getRenderContext().setEdgeLabelTransformer(edgeLabeller); mViewer.getRenderContext().setEdgeLabelRenderer(edgeLabelRenderer); if(EDGE_FONT_SIZE > 0) { mViewer.getRenderContext().setEdgeFontTransformer(edgeFontTransformer); } }
private void createGraphView(Graph<NodeObject, LinkObject> pGraph) { ObservableGraph<NodeObject, LinkObject> tObsGraph = new ObservableGraph<NodeObject, LinkObject>(pGraph); tObsGraph.addGraphEventListener(new GraphEventListener<NodeObject, LinkObject>() { public void handleGraphEvent(GraphEvent<NodeObject, LinkObject> pEvent) { updateVisualization(); } }); // create layout mLayout = new edu.uci.ics.jung.algorithms.layout.FRLayout2<NodeObject, LinkObject>(tObsGraph); Shell activeShell = Display.getDefault().getActiveShell(); org.eclipse.swt.graphics.Rectangle tRectangle; if(activeShell != null) { tRectangle = activeShell.getBounds(); } else { tRectangle = new org.eclipse.swt.graphics.Rectangle(0,0, 300,300); } double tWidth = tRectangle.width * 0.4; double tHeight = tRectangle.height*0.4; //Logging.log(this, "Old size was " + tRectangle.width + "x" + tRectangle.height + " while new size will be " + tWidth + "x" + tHeight); mLayout.setSize(new Dimension((int)tWidth, (int)tHeight)); // create viewer mViewer = new VisualizationViewer<NodeObject, LinkObject>(mLayout); mViewer.setDoubleBuffered(true); mViewer.setPreferredSize(new Dimension((int)tWidth, (int)tHeight)); // setting up view of graph itself // Setup up a new vertex to paint transformer... Transformer<NodeObject, Paint> vertexPaint = new Transformer<NodeObject, Paint>() { private final Color colorBlue = new Color(.1f, .3f, 1f); private final Color colorYellow = new Color(1f, 1f, .3f); private final Color colorGreen = new Color(.1f, .9f, .3f); public Paint transform(Object i) { if(i instanceof DummyForwardingElement) { i = ((DummyForwardingElement) i).getObject(); } if (i instanceof AbstractGate) return Color.LIGHT_GRAY; if (i instanceof GateContainer) return colorGreen; if (i instanceof ILowerLayer) return colorYellow; // does the object define its color by itself? if(i instanceof Decorator) { Color decColor = ((Decorator) i).getColor(); if(decColor != null) { return decColor; } } // is there an external decorator for the object? if(mDecoration != null) { Decorator decorator = mDecoration.getDecorator(i); if(decorator != null) { Color decColor = decorator.getColor(); if(decColor != null) { return decColor; } } } if (i instanceof PartialRoutingService) return Color.ORANGE; if (i instanceof RemoteRoutingService) return colorBlue; if (i instanceof RoutingServiceAddress) return colorBlue; return Color.WHITE; } }; Transformer<NodeObject, Shape> vertexShapeTransformer = new Transformer<NodeObject, Shape>() { public Shape transform(NodeObject pObj) { Image tImage = loadImageFor(pObj); if(tImage != null) { Shape tShape = FourPassImageShaper.getShape(tImage); if(tShape.getBounds().getWidth() > 0 && tShape.getBounds().getHeight() > 0) { AffineTransform transform = AffineTransform.getTranslateInstance( - tImage.getWidth(null) / 2, - tImage.getHeight(null) / 2); tShape = transform.createTransformedShape(tShape); return tShape; } } String tLabel = mViewer.getRenderContext().getVertexLabelTransformer().transform(pObj); return new Rectangle( - (tLabel.length() * VERTEX_LABEL_CHAR_WIDTH + VERTEX_LABEL_ADD_WIDTH) / 2, - VERTEX_RECTANGLE_HEIGHT / 2, tLabel.length() * VERTEX_LABEL_CHAR_WIDTH + VERTEX_LABEL_ADD_WIDTH, VERTEX_RECTANGLE_HEIGHT); } }; Transformer<NodeObject, Icon> vertexIconTransformer = new Transformer<NodeObject, Icon>() { public Icon transform(NodeObject pObj) { return loadIconFor(pObj); } }; // Set up a new stroke Transformer for the edges Transformer<NodeObject, Stroke> vertexStrokeTransformer = new Transformer<NodeObject, Stroke>() { private final Stroke normalEdgeStroke = new BasicStroke(VERTEX_STROKE_NORMAL); public Stroke transform(Object pVertex) { float loadLevel = getLoadLevel(pVertex); if(loadLevel > 0) { return new BasicStroke(VERTEX_STROKE_NORMAL +VERTEX_STROKE_ADD_MAX_MSG * loadLevel); } else { return normalEdgeStroke; } } }; Transformer<NodeObject, Paint> vertexDraw = new Transformer<NodeObject, Paint>() { public Paint transform(Object pVertex) { Boolean tBroken = false; if (pVertex instanceof Breakable) { try { tBroken = ((Breakable)pVertex).isBroken() != Status.OK; } catch(RemoteException exc) { tBroken = true; } } if (tBroken) { return Color.RED; } else { Marker[] tMarkers = MarkerContainer.getInstance().get(pVertex); if(tMarkers.length > 0) { if(tMarkers.length > 1) { if(Config.Routing.USE_SPECIAL_MULTIPLE_MARKING_COLOR){ return MULTIPLE_MARKING_COLOR; }else{ return tMarkers[tMarkers.length - 1].getColor(); } } else { return tMarkers[0].getColor(); } } else { // // if the background is colored with a special an R/G/B color, we use white as frame color in order to have readable strings // if(pVertex instanceof IElementDecorator && ((IElementDecorator)pVertex).getDecorationParameter() != null && ((IElementDecorator)pVertex).getDecorationParameter() instanceof IElementDecorator.Color) { // IElementDecorator tDecorator = (IElementDecorator)pVertex; // if(tDecorator.getDecorationParameter() != null){ // return Color.WHITE; // } // } return DEFAULT_VERTEX_COLOR; } } } }; Transformer<LinkObject, Paint> edgeDraw = new Transformer<LinkObject, Paint>() { @Override public Paint transform(LinkObject pLink) { Marker[] tMarkers = MarkerContainer.getInstance().get(pLink); if(tMarkers.length > 0) { if(tMarkers.length > 1) { if(Config.Routing.USE_SPECIAL_MULTIPLE_MARKING_COLOR){ return MULTIPLE_MARKING_COLOR; }else{ return tMarkers[tMarkers.length - 1].getColor(); } } else { return tMarkers[0].getColor(); } } else { if(pLink instanceof Gate) { if(!((Gate)pLink).isOperational()) { return ERROR_EDGE_COLOR; } } return DEFAULT_EDGE_COLOR; } } }; Transformer<NodeObject, String> vertexLabeller = new Transformer<NodeObject, String>() { public String transform(Object s) { String tName = s.toString(); if (s instanceof RemoteRoutingService) { try { tName = ((RemoteRoutingService)s).getName(); } catch (RemoteException e) { // ignore it; we will stick to the previous tName } } return tName; } }; // Set up a new stroke Transformer for the edges Transformer<LinkObject, Stroke> edgeStrokeTransformer = new Transformer<LinkObject, Stroke>() { private final Stroke normalEdgeStroke = new BasicStroke(EDGE_STROKE_NORMAL); private final Stroke logicalEdgeStroke = new BasicStroke(EDGE_STROKE_LOGICAL, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{10.0f}, 0.0f); private final Stroke gateEdgeStroke = new BasicStroke(EDGE_STROKE_GATE); public Stroke transform(Object s) { float loadLevel = getLoadLevel(s); if(loadLevel > 0) { return new BasicStroke(EDGE_STROKE_GATE +EDGE_STROKE_GATE_ADD_MAX_MSG * loadLevel); } else if(s instanceof Gate) { return gateEdgeStroke; } else if(s.toString().regionMatches(0, "routing for", 0, "routing for".length())) { return logicalEdgeStroke; } return normalEdgeStroke; } }; Transformer<LinkObject, String> edgeLabeller = new Transformer<LinkObject, String>() { public String transform(Object edge) { if(edge == null) return "null"; // use StringBuilder in order to boost performance of string creation StringBuilder tName = null; if(edge instanceof Gate) { tName = new StringBuilder(); if(((Gate) edge).getGateID() != null) { tName.append(((Gate) edge).getGateID()); tName.append(" "); } tName.append(edge.getClass().getSimpleName()); tName.append(" ("); tName.append(((Gate) edge).getNumberMessages(false)); tName.append(")"); } else if(edge instanceof NetworkInterface) { return "";//"LL_" +((NetworkInterface) edge).getLowerLayerID(); } if(tName == null) return edge.toString(); else return tName.toString(); } }; EdgeLabelRenderer edgeLabelRenderer = new DefaultEdgeLabelRenderer(Color.BLACK) { private final Color colorBg = (Color)UIManager.getDefaults().get("Panel.background"); private final Color colorEdgeBackground = new Color(colorBg.getRed(), colorBg.getGreen(), colorBg.getBlue(), 128); @Override public <T> Component getEdgeLabelRendererComponent(JComponent arg0, Object arg1, Font arg2, boolean arg3, T arg4) { Component tRes = super.getEdgeLabelRendererComponent(arg0, arg1, arg2, arg3, arg4); tRes.setBackground(colorEdgeBackground); return tRes; } }; Transformer<LinkObject, Font> edgeFontTransformer = new Transformer<LinkObject, Font>() { public Font transform(LinkObject edge) { if(edge == null) return null; return edgeFont; } private Font edgeFont = new Font("SansSerif", Font.PLAIN, EDGE_FONT_SIZE); }; Transformer<NodeObject, Font> vertexFontTransformer = new Transformer<NodeObject, Font>() { public Font transform(NodeObject vertex) { if(vertex == null) return null; return vertexFont; } private Font vertexFont = new Font("SansSerif", Font.PLAIN, VERTEX_FONT_SIZE); }; mViewer.getRenderContext().setVertexFillPaintTransformer(vertexPaint); mViewer.getRenderContext().setVertexDrawPaintTransformer(vertexDraw); mViewer.getRenderContext().setVertexStrokeTransformer(vertexStrokeTransformer); mViewer.getRenderContext().setVertexShapeTransformer(vertexShapeTransformer); mViewer.getRenderContext().setVertexIconTransformer(vertexIconTransformer); mViewer.getRenderer().setVertexLabelRenderer(new vertexLabelRenderer()); mViewer.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.S); // mViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<NodeObject>()); mViewer.getRenderContext().setVertexLabelTransformer(vertexLabeller); mViewer.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); if(VERTEX_FONT_SIZE > 0) { mViewer.getRenderContext().setVertexFontTransformer(vertexFontTransformer); } // mViewer.getRenderContext().setEdgeShapeTransformer(new BentLine<NodeObject,LinkObject>()); mViewer.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); mViewer.getRenderContext().setEdgeDrawPaintTransformer(edgeDraw); mViewer.getRenderContext().setArrowDrawPaintTransformer(edgeDraw); mViewer.getRenderContext().setArrowFillPaintTransformer(edgeDraw); mViewer.getRenderContext().setEdgeLabelTransformer(edgeLabeller); mViewer.getRenderContext().setEdgeLabelRenderer(edgeLabelRenderer); if(EDGE_FONT_SIZE > 0) { mViewer.getRenderContext().setEdgeFontTransformer(edgeFontTransformer); } }
diff --git a/src/main/java/com/alta189/cyborg/commandkit/CommandKit.java b/src/main/java/com/alta189/cyborg/commandkit/CommandKit.java index 5106370..26d01f0 100644 --- a/src/main/java/com/alta189/cyborg/commandkit/CommandKit.java +++ b/src/main/java/com/alta189/cyborg/commandkit/CommandKit.java @@ -1,169 +1,169 @@ /* * Copyright (C) 2012 CyborgDev <[email protected]> * * This file is part of CommandKit * * CommandKit 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. * * CommandKit 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. If not, see <http://www.gnu.org/licenses/>. */ package com.alta189.cyborg.commandkit; import com.alta189.cyborg.api.command.annotation.EmptyConstructorInjector; import com.alta189.cyborg.api.command.annotation.SimpleInjector; import com.alta189.cyborg.api.plugin.CommonPlugin; import com.alta189.cyborg.api.util.yaml.YAMLFormat; import com.alta189.cyborg.api.util.yaml.YAMLProcessor; import com.alta189.cyborg.commandkit.google.GoogleCommands; import com.alta189.cyborg.commandkit.hastebin.HastebinCommands; import com.alta189.cyborg.commandkit.seen.SeenCommands; import com.alta189.cyborg.commandkit.seen.SeenEntry; import com.alta189.cyborg.commandkit.seen.SeenListener; import com.alta189.cyborg.commandkit.tell.TellCommands; import com.alta189.cyborg.commandkit.tell.TellEntry; import com.alta189.cyborg.commandkit.tell.TellListener; import com.alta189.cyborg.commandkit.twitter.TwitterCommands; import com.alta189.simplesave.Database; import com.alta189.simplesave.DatabaseFactory; import com.alta189.simplesave.exceptions.ConnectionException; import com.alta189.simplesave.exceptions.TableRegistrationException; import com.alta189.simplesave.mysql.MySQLConfiguration; import com.alta189.simplesave.mysql.MySQLConstants; import twitter4j.Twitter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; public class CommandKit extends CommonPlugin { private static CommandKit instance; private YAMLProcessor config; private Database db; @Override public void onEnable() { getLogger().log(Level.INFO, "Enabling..."); instance = this; MySQLConfiguration dbConfig = new MySQLConfiguration(); dbConfig.setHost(getConfig().getString("database.mysql.host", "127.0.0.1")); dbConfig.setPort(getConfig().getInt("database.mysql.port", MySQLConstants.DefaultPort)); dbConfig.setDatabase(getConfig().getString("database.mysql.database")); dbConfig.setUser(getConfig().getString("database.mysql.user", MySQLConstants.DefaultUser)); dbConfig.setPassword(getConfig().getString("database.mysql.password", MySQLConstants.DefaultPass)); db = DatabaseFactory.createNewDatabase(dbConfig); try { db.registerTable(SeenEntry.class); db.registerTable(TellEntry.class); } catch (TableRegistrationException e) { e.printStackTrace(); } try { db.connect(); } catch (ConnectionException e) { e.printStackTrace(); } // Register Listeners getCyborg().getEventManager().registerEvents(new SeenListener(), this); getCyborg().getEventManager().registerEvents(new TellListener(), this); // Register Commands getCyborg().getCommandManager().registerCommands(this, GoogleCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, SeenCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, TellCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, HastebinCommands.class, EmptyConstructorInjector.getInstance()); - getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("consumer-key"))); - getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("consumer-secret"))); + getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("twitter.consumer-key"))); + getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("twitter.consumer-secret"))); getLogger().log(Level.INFO, "Successfully Enabled!"); } @Override public void onDisable() { getLogger().log(Level.INFO, "Disabling..."); if (db != null) { try { db.close(); } catch (ConnectionException e) { e.printStackTrace(); } } getConfig().save(); instance = null; getLogger().log(Level.INFO, "Successfully Disabled!"); } public static YAMLProcessor getConfig() { if (instance.config == null) { instance.config = instance.setupConfig(new File(instance.getDataFolder(), "config.yml")); try { instance.config.load(); } catch (IOException e) { e.printStackTrace(); } } return instance.config; } public static Database getDatabase() { return instance.db; } private YAMLProcessor setupConfig(File file) { if (!file.exists()) { try { InputStream input = getClass().getResource("config.yml").openStream(); if (input != null) { FileOutputStream output = null; try { if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } output = new FileOutputStream(file); byte[] buf = new byte[8192]; int length; while ((length = input.read(buf)) > 0) { output.write(buf, 0, length); } } catch (Exception e) { e.printStackTrace(); } finally { try { input.close(); } catch (Exception ignored) { } try { if (output != null) { output.close(); } } catch (Exception e) { } } } } catch (Exception e) { } } return new YAMLProcessor(file, false, YAMLFormat.EXTENDED); } }
true
true
public void onEnable() { getLogger().log(Level.INFO, "Enabling..."); instance = this; MySQLConfiguration dbConfig = new MySQLConfiguration(); dbConfig.setHost(getConfig().getString("database.mysql.host", "127.0.0.1")); dbConfig.setPort(getConfig().getInt("database.mysql.port", MySQLConstants.DefaultPort)); dbConfig.setDatabase(getConfig().getString("database.mysql.database")); dbConfig.setUser(getConfig().getString("database.mysql.user", MySQLConstants.DefaultUser)); dbConfig.setPassword(getConfig().getString("database.mysql.password", MySQLConstants.DefaultPass)); db = DatabaseFactory.createNewDatabase(dbConfig); try { db.registerTable(SeenEntry.class); db.registerTable(TellEntry.class); } catch (TableRegistrationException e) { e.printStackTrace(); } try { db.connect(); } catch (ConnectionException e) { e.printStackTrace(); } // Register Listeners getCyborg().getEventManager().registerEvents(new SeenListener(), this); getCyborg().getEventManager().registerEvents(new TellListener(), this); // Register Commands getCyborg().getCommandManager().registerCommands(this, GoogleCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, SeenCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, TellCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, HastebinCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("consumer-key"))); getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("consumer-secret"))); getLogger().log(Level.INFO, "Successfully Enabled!"); }
public void onEnable() { getLogger().log(Level.INFO, "Enabling..."); instance = this; MySQLConfiguration dbConfig = new MySQLConfiguration(); dbConfig.setHost(getConfig().getString("database.mysql.host", "127.0.0.1")); dbConfig.setPort(getConfig().getInt("database.mysql.port", MySQLConstants.DefaultPort)); dbConfig.setDatabase(getConfig().getString("database.mysql.database")); dbConfig.setUser(getConfig().getString("database.mysql.user", MySQLConstants.DefaultUser)); dbConfig.setPassword(getConfig().getString("database.mysql.password", MySQLConstants.DefaultPass)); db = DatabaseFactory.createNewDatabase(dbConfig); try { db.registerTable(SeenEntry.class); db.registerTable(TellEntry.class); } catch (TableRegistrationException e) { e.printStackTrace(); } try { db.connect(); } catch (ConnectionException e) { e.printStackTrace(); } // Register Listeners getCyborg().getEventManager().registerEvents(new SeenListener(), this); getCyborg().getEventManager().registerEvents(new TellListener(), this); // Register Commands getCyborg().getCommandManager().registerCommands(this, GoogleCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, SeenCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, TellCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, HastebinCommands.class, EmptyConstructorInjector.getInstance()); getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("twitter.consumer-key"))); getCyborg().getCommandManager().registerCommands(this, TwitterCommands.class, new SimpleInjector(getConfig().getString("twitter.consumer-secret"))); getLogger().log(Level.INFO, "Successfully Enabled!"); }
diff --git a/frost-wot/source/frost/FileAccess.java b/frost-wot/source/frost/FileAccess.java index d75792ed..61cc8127 100644 --- a/frost-wot/source/frost/FileAccess.java +++ b/frost-wot/source/frost/FileAccess.java @@ -1,635 +1,638 @@ /* FileAccess.java / File Access Copyright (C) 2001 Jan-Thomas Czornack <[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., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost; import java.awt.Component; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.JFileChooser; import org.w3c.dom.*; import org.xml.sax.SAXException; public class FileAccess { /** * Writes a file to disk after opening a saveDialog window * @param parent The parent component, often 'this' can be used * @param conten The data to write to disk. * @param lastUsedDirectory The saveDialog starts at this directory * @param title The saveDialog gets this title */ public static void saveDialog(Component parent, String content, String lastUsedDirectory, String title) { final JFileChooser fc = new JFileChooser(lastUsedDirectory); fc.setDialogTitle(title); fc.setFileHidingEnabled(true); fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fc.setMultiSelectionEnabled(false); int returnVal = fc.showSaveDialog(parent); if( returnVal == JFileChooser.APPROVE_OPTION ) { File file = fc.getSelectedFile(); if( file != null ) { frame1.frostSettings.setValue("lastUsedDirectory", file.getParent()); if( !file.isDirectory() ) { writeFile(content, file); } } } } /** * removes unwanted files from the keypool * @param keyPath the directory to clean */ public static void cleanKeypool(String keyPath) { File[] chunks = (new File(keyPath)).listFiles(); String date = DateFun.getExtendedDate(); String fileSeparator = System.getProperty("file.separator"); for( int i = 0; i < chunks.length; i++ ) { if( chunks[i].isFile() ) { // Remove 0 byte and tmp files if( chunks[i].length() == 0 || chunks[i].getName().endsWith(".tmp") //|| //chunks[i].getName().endsWith(".txt") ) chunks[i].delete(); // Remove keyfiles and their locks if( !chunks[i].getName().startsWith(date) && chunks[i].getName().endsWith(".idx") ) chunks[i].delete(); if( !chunks[i].getName().startsWith(date) && chunks[i].getName().endsWith(".loc") ) chunks[i].delete(); } } } /** * Writes a byte[] to disk * @param data the byte[] with the data to write * @param file the destination file */ public static void writeByteArray(byte[] data, File file) { try { FileOutputStream fileOut = new FileOutputStream(file); fileOut.write(data); fileOut.close(); } catch( IOException e ) { Core.getOut().println("writeByteArray: " + e); } } /** * Reads a file and returns it's content in a byte[] * @param file the file to read * @return byte[] with the files content */ public static byte[] readByteArray(String filename) { return readByteArray(new File(filename)); } public static byte[] readByteArray(File file) { try { byte[] data = new byte[(int)file.length()]; FileInputStream fileIn = new FileInputStream(file); int count = 0; int bytesRead = 0; int dataChunkLength = data.length; while( bytesRead < dataChunkLength ) { count = fileIn.read(data, bytesRead, dataChunkLength - bytesRead); if( count < 0 ) { break; } else { bytesRead++; } } fileIn.close(); return data; } catch( IOException e ) { System.err.println(e); } return new byte[0]; } /** * Reads a file and returns it contents in a String */ public static String read(String path) { FileReader fr; StringBuffer content = new StringBuffer(); int c; try { fr = new FileReader(path); while( (c = fr.read()) != -1 ) { content.append((char)c); } fr.close(); } catch( IOException e ) { return("Read Error"); } return content.toString(); } /**Returns an ArrayList of File objects with all Directories and files*/ public static ArrayList getAllEntries(File file, final String extension) { ArrayList files = new ArrayList(); getAllFiles(file, extension, files); return files; } /** * Returns all files starting from given directory/file that have a given extension. */ private static void getAllFiles(File file, String extension, ArrayList filesLst) { if( file != null ) { if( file.isDirectory() ) { File[] dirfiles = file.listFiles(); if( dirfiles != null ) { for( int i = 0; i < dirfiles.length; i++ ) { getAllFiles(dirfiles[i], extension, filesLst); // process recursive } } } if( file.getName().endsWith(extension) ) { filesLst.add( file ); } } } /** * Writes zip file */ public static void writeZipFile(String content, String entry, File file) { writeZipFile(content.getBytes(), entry, file); } public static void writeZipFile(byte[] content, String entry, File file) { try { FileOutputStream fos = new FileOutputStream(file); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze = new ZipEntry(entry); zos.putNextEntry(ze); zos.write(content); zos.closeEntry(); zos.close(); } catch( IOException e ) { Core.getOut().println("files.writeZipFile: " + e); } } /** * Reads first zip file entry and returns content in a String */ public static String readZipFile(String path) { return readZipFile(new File(path)); } public static String readZipFile(File file) { if( !file.isFile() || file.length() == 0 ) return null; StringBuffer sb = new StringBuffer(); int bufferSize = 4096; try { FileInputStream fis = new FileInputStream(file); ZipInputStream zis = new ZipInputStream(fis); try { zis.getNextEntry(); byte[] zipData = new byte[bufferSize]; int len; boolean bur = true; // Buffer underrun int off = 0; int num = bufferSize; while( zis.available() == 1 ) { bur = true; off = 0; num = bufferSize; while( bur && zis.available() == 1 ) { len = zis.read(zipData, off, num); off += len; if( off >= bufferSize ) bur = false; else num = num - len; } sb.append(new String(zipData)); } fis.close(); zis.close(); } catch( IOException e ) { e.printStackTrace(Core.getOut()); Core.getOut().println("offeding file saved as badfile.zip, send to a dev for analysis"); File badFile = new File("badfile.zip"); file.renameTo(badFile); } } catch( FileNotFoundException e ) { Core.getOut().println("files.readZipFile: " + e); } return sb.toString(); } /** * Reads file and returns a Vector of lines */ public static Vector readLines(File file) { return readLines(file.getPath()); } public static Vector readLines(String path) { BufferedReader f; String line; line = ""; Vector data = new Vector(); try { f = new BufferedReader(new FileReader(path)); while( (line = f.readLine()) != null ) { data.add(line.trim()); } f.close(); } catch( IOException e ) { Core.getOut().println("Read Error: " + path); } return data; } /** * Reads a file and returns its contents in a String */ public static String readFile(File file) { return readFile(file.getPath()); } public static String readFile(String path) { BufferedReader f; String line = new String(); StringBuffer stringBuffer = new StringBuffer(); try { f = new BufferedReader(new FileReader(path)); while( (line = f.readLine()) != null ) { stringBuffer.append(line); stringBuffer.append("\r\n"); } f.close(); } catch( IOException e ) { Core.getOut().println("Read Error: " + path); } return stringBuffer.toString(); } /** * Writes a file "file" to "path" */ public static void writeFile(String content, String filename) { writeFile(content, new File(filename)); } public static void writeFile(String content, File file) { FileWriter f1; try { f1 = new FileWriter(file); f1.write(content); f1.close(); } catch( IOException e ) { Core.getOut().println("Write Error: " + file.getPath()); } } /** * Returns filenames in a directory */ public static String[] getFilenames(String Path) { File FileObject = new File(Path); String[] filenames; if( FileObject.isDirectory() ) filenames = FileObject.list(); else filenames = new String[0]; return filenames; } /** * Deletes the given directory and ALL FILES/DIRS IN IT !!! * USE CAREFUL !!! */ public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // The directory is now empty so delete it return dir.delete(); } /** * Reads a keyfile from disk and adds the keys to a map * @param source keyfile as String or as File * @param chk Map that will be used to add the keys * @param exchange the exchange flag of SharedFileObject will be set to this value */ public static void readKeyFile(String source, Map chk) { readKeyFile(new File(source), chk); } public static void readKeyFile(File source, Map chk) { if (source.isFile() && source.length() > 0) { BufferedReader f; String line = new String(); String filename = new String(); String size = new String(); String date = new String(); String dateShared = null; String key = null; String SHA1 = null; String owner = new String(); String batch = null; int counter = 0; //parse the xml file Document d= null; try { d = XMLTools.parseXmlFile(source.getPath(), false); } catch (IllegalArgumentException t) { t.printStackTrace(Core.getOut()); File badfile = new File("badfile.xml"); source.renameTo(badfile); Core.getOut().println("offending file saved as badfile.xml - send it to a dev for analysis"); } if (d == null) { Core.getOut().println("Couldn't parse index file."); return; } Element main = d.getDocumentElement(); // 'Filelist' ArrayList files = XMLTools.getChildElementsByTagName(main, "File"); if (files.size() == 0) { if (source.length() > 0 ) { Core.getOut().println("\n\n****Index empty but file is not!***"); - Core.getOut().println("send badfile.xml to dev for analysis\n\n"); + Core.getOut().println("send badfile.xml to dev for analysis with the following info: \n\n"); + Exception e = new Exception(); + e.fillInStackTrace(); + e.printStackTrace(Core.getOut()); File badfile = new File ("badfile.xml"); source.renameTo(badfile); } Core.getOut().println("Index empty!"); return; } //now get all the files Iterator i = files.iterator(); while (i.hasNext()) { Element current = (Element)i.next(); SharedFileObject newKey = new SharedFileObject(); try { newKey.loadXMLElement(current); }catch (SAXException e){ e.printStackTrace(Core.getOut()); File badfile = new File ("badfile.xml"); source.renameTo(badfile); Core.getOut().println("invalid index received. Its saved as badfile.xml, send that file to the devs for analysis"); break; } //validate the key if (!newKey.isValid()) { Core.getOut().println("invalid key found"); continue; } //check if we already have such key in the map SharedFileObject oldKey = (SharedFileObject)chk.get(newKey.getSHA1()); //if we don't just add the new key if (oldKey == null) { if (chk.size() < frame1.frostSettings.getIntValue("maxKeys")) { chk.put(newKey.getSHA1(), newKey); counter++; //not sure what exactly this counter is for } } else if ( oldKey.getOwner() == null || ( newKey.getOwner()!= null && oldKey.getOwner().compareTo(newKey.getOwner()) == 0) ) { //check if the old key was not or is the same owner // and update the fields GregorianCalendar cal, keyCal; if (newKey.getDate() != null) cal = newKey.getCal(); else cal = null; if (oldKey.getDate() != null) keyCal = oldKey.getCal(); else keyCal = null; if (cal != null && keyCal == null) oldKey.setDate(newKey.getDate()); else if ( cal != null && keyCal != null && keyCal.before(cal)) oldKey.setDate(newKey.getDate()); oldKey.setKey(newKey.getKey()); oldKey.setOwner(newKey.getOwner()); // ^^^ this allows for taking ownership of unsigned files. It is deliberately so } //check if it (??? what ???) } } } public static void writeKeyFile(Map chk, String destination) { writeKeyFile(chk, new File(destination)); } public static void writeKeyFile(Map chk, File destination) { File tmpFile = new File( destination.getPath() + ".tmp" ); Document doc = XMLTools.createDomDocument(); if( doc == null ) { System.out.println("Error - writeKeyFile: factory could'nt create XML Document."); return; } Element rootElement = doc.createElement("Filelist"); if (frame1.frostSettings.getBoolValue("signUploads")) { rootElement.setAttribute("sharer", frame1.getMyId().getUniqueName()); rootElement.setAttribute("pubkey", frame1.getMyId().getKey()); } doc.appendChild(rootElement); synchronized (chk) { Iterator i = chk.values().iterator(); while (i.hasNext()) { SharedFileObject current = (SharedFileObject)i.next(); if (current.getOwner() != null && frame1.getEnemies().Get(current.getOwner()) != null) { Core.getOut().println("skipping file from BAD user"); continue; } rootElement.appendChild( current.getXMLElement(doc) ); } } // xml tree created, now save boolean writeOK = false; try { writeOK = XMLTools.writeXmlFile(doc, tmpFile.getPath()); } catch(Throwable t) { System.out.println("Exception - writeKeyFile:"); t.printStackTrace(Core.getOut()); } if( writeOK ) { File oldFile = new File(destination.getPath() + ".old"); oldFile.delete(); destination.renameTo(oldFile); tmpFile.renameTo(destination); } else { // delete incomplete file tmpFile.delete(); } } public static String readFileRaw(String path) { return readFileRaw(new File(path)); } public static String readFileRaw(File file) { if (!file.exists()) return null; return readFile(file); /* String result; try { FileChannel fc = (new FileInputStream(file)).getChannel(); ByteBuffer buf = ByteBuffer.allocate((int)file.length()); while (buf.remaining() > 0) { fc.read(buf); } fc.close(); buf.flip(); result = charset.decode(buf).toString(); } catch (IOException e) { e.printStackTrace(Core.getOut()); return new String(); } return result;*/ } }
true
true
public static void readKeyFile(File source, Map chk) { if (source.isFile() && source.length() > 0) { BufferedReader f; String line = new String(); String filename = new String(); String size = new String(); String date = new String(); String dateShared = null; String key = null; String SHA1 = null; String owner = new String(); String batch = null; int counter = 0; //parse the xml file Document d= null; try { d = XMLTools.parseXmlFile(source.getPath(), false); } catch (IllegalArgumentException t) { t.printStackTrace(Core.getOut()); File badfile = new File("badfile.xml"); source.renameTo(badfile); Core.getOut().println("offending file saved as badfile.xml - send it to a dev for analysis"); } if (d == null) { Core.getOut().println("Couldn't parse index file."); return; } Element main = d.getDocumentElement(); // 'Filelist' ArrayList files = XMLTools.getChildElementsByTagName(main, "File"); if (files.size() == 0) { if (source.length() > 0 ) { Core.getOut().println("\n\n****Index empty but file is not!***"); Core.getOut().println("send badfile.xml to dev for analysis\n\n"); File badfile = new File ("badfile.xml"); source.renameTo(badfile); } Core.getOut().println("Index empty!"); return; } //now get all the files Iterator i = files.iterator(); while (i.hasNext()) { Element current = (Element)i.next(); SharedFileObject newKey = new SharedFileObject(); try { newKey.loadXMLElement(current); }catch (SAXException e){ e.printStackTrace(Core.getOut()); File badfile = new File ("badfile.xml"); source.renameTo(badfile); Core.getOut().println("invalid index received. Its saved as badfile.xml, send that file to the devs for analysis"); break; } //validate the key if (!newKey.isValid()) { Core.getOut().println("invalid key found"); continue; } //check if we already have such key in the map SharedFileObject oldKey = (SharedFileObject)chk.get(newKey.getSHA1()); //if we don't just add the new key if (oldKey == null) { if (chk.size() < frame1.frostSettings.getIntValue("maxKeys")) { chk.put(newKey.getSHA1(), newKey); counter++; //not sure what exactly this counter is for } } else if ( oldKey.getOwner() == null || ( newKey.getOwner()!= null && oldKey.getOwner().compareTo(newKey.getOwner()) == 0) ) { //check if the old key was not or is the same owner // and update the fields GregorianCalendar cal, keyCal; if (newKey.getDate() != null) cal = newKey.getCal(); else cal = null; if (oldKey.getDate() != null) keyCal = oldKey.getCal(); else keyCal = null; if (cal != null && keyCal == null) oldKey.setDate(newKey.getDate()); else if ( cal != null && keyCal != null && keyCal.before(cal)) oldKey.setDate(newKey.getDate()); oldKey.setKey(newKey.getKey()); oldKey.setOwner(newKey.getOwner()); // ^^^ this allows for taking ownership of unsigned files. It is deliberately so } //check if it (??? what ???) } } }
public static void readKeyFile(File source, Map chk) { if (source.isFile() && source.length() > 0) { BufferedReader f; String line = new String(); String filename = new String(); String size = new String(); String date = new String(); String dateShared = null; String key = null; String SHA1 = null; String owner = new String(); String batch = null; int counter = 0; //parse the xml file Document d= null; try { d = XMLTools.parseXmlFile(source.getPath(), false); } catch (IllegalArgumentException t) { t.printStackTrace(Core.getOut()); File badfile = new File("badfile.xml"); source.renameTo(badfile); Core.getOut().println("offending file saved as badfile.xml - send it to a dev for analysis"); } if (d == null) { Core.getOut().println("Couldn't parse index file."); return; } Element main = d.getDocumentElement(); // 'Filelist' ArrayList files = XMLTools.getChildElementsByTagName(main, "File"); if (files.size() == 0) { if (source.length() > 0 ) { Core.getOut().println("\n\n****Index empty but file is not!***"); Core.getOut().println("send badfile.xml to dev for analysis with the following info: \n\n"); Exception e = new Exception(); e.fillInStackTrace(); e.printStackTrace(Core.getOut()); File badfile = new File ("badfile.xml"); source.renameTo(badfile); } Core.getOut().println("Index empty!"); return; } //now get all the files Iterator i = files.iterator(); while (i.hasNext()) { Element current = (Element)i.next(); SharedFileObject newKey = new SharedFileObject(); try { newKey.loadXMLElement(current); }catch (SAXException e){ e.printStackTrace(Core.getOut()); File badfile = new File ("badfile.xml"); source.renameTo(badfile); Core.getOut().println("invalid index received. Its saved as badfile.xml, send that file to the devs for analysis"); break; } //validate the key if (!newKey.isValid()) { Core.getOut().println("invalid key found"); continue; } //check if we already have such key in the map SharedFileObject oldKey = (SharedFileObject)chk.get(newKey.getSHA1()); //if we don't just add the new key if (oldKey == null) { if (chk.size() < frame1.frostSettings.getIntValue("maxKeys")) { chk.put(newKey.getSHA1(), newKey); counter++; //not sure what exactly this counter is for } } else if ( oldKey.getOwner() == null || ( newKey.getOwner()!= null && oldKey.getOwner().compareTo(newKey.getOwner()) == 0) ) { //check if the old key was not or is the same owner // and update the fields GregorianCalendar cal, keyCal; if (newKey.getDate() != null) cal = newKey.getCal(); else cal = null; if (oldKey.getDate() != null) keyCal = oldKey.getCal(); else keyCal = null; if (cal != null && keyCal == null) oldKey.setDate(newKey.getDate()); else if ( cal != null && keyCal != null && keyCal.before(cal)) oldKey.setDate(newKey.getDate()); oldKey.setKey(newKey.getKey()); oldKey.setOwner(newKey.getOwner()); // ^^^ this allows for taking ownership of unsigned files. It is deliberately so } //check if it (??? what ???) } } }
diff --git a/ttools/src/main/uk/ac/starlink/ttools/plot/ShaderTweaker.java b/ttools/src/main/uk/ac/starlink/ttools/plot/ShaderTweaker.java index 27c2e6e8e..641e41ac9 100644 --- a/ttools/src/main/uk/ac/starlink/ttools/plot/ShaderTweaker.java +++ b/ttools/src/main/uk/ac/starlink/ttools/plot/ShaderTweaker.java @@ -1,226 +1,227 @@ package uk.ac.starlink.ttools.plot; import java.awt.Color; /** * DataColorTweaker implementation which uses an array of Shader objects. * * @author Mark Taylor * @since 5 Jun 2007 */ public class ShaderTweaker implements DataColorTweaker { private final int ioff_; private final int ndim_; private final Shader[] shaders_; private final Scaler[] scalers_; private final double[] knobs_; private boolean hasEffect_; /** * Constructor. * * @param ioff offset into supplied coordinate arrays at which * auxiliary data starts * @param shaders array of shaders, one for each aux axis * @param ranges array of (low,high) range bounds, one for each aux axis * @param logFlags array of logarithmic scaling flags, * one for each aux axis * @param flipFlags array of axis inversion flags, * one for each aux axis */ public ShaderTweaker( int ioff, Shader[] shaders, double[][] ranges, boolean[] logFlags, boolean[] flipFlags ) { ioff_ = ioff; shaders_ = shaders; /* Create a scaler for each of the auxiliary axes. These turn * data coordinates into normalised coordinates (0..1). */ int ndim = shaders_.length; knobs_ = new double[ ndim ]; scalers_ = new Scaler[ ndim ]; int nd = 0; for ( int idim = 0; idim < ndim; idim++ ) { knobs_[ idim ] = Double.NaN; if ( shaders_[ idim ] != null ) { int jdim = ioff + idim; scalers_[ idim ] = createScaler( ranges[ jdim ][ 0 ], ranges[ jdim ][ 1 ], logFlags[ jdim ], flipFlags[ jdim ] ); nd = idim + 1; } } ndim_ = nd; } public int getNcoord() { return ioff_ + ndim_; } /** * This implementation returns true unless the scaler results in a NaN * for any of the coordinates. */ public boolean setCoords( double[] coords ) { boolean hasEffect = false; for ( int idim = 0; idim < ndim_; idim++ ) { if ( shaders_[ idim ] != null ) { int jdim = ioff_ + idim; double value = coords[ jdim ]; if ( Double.isNaN( value ) ) { knobs_[ idim ] = Double.NaN; } else { hasEffect = true; Scaler scaler = scalers_[ idim ]; double sval = scaler.scale( value ); if ( scaler.inRange( value ) ) { knobs_[ idim ] = sval; assert sval >= 0.0 && sval <= 1.0; } else if ( Double.isNaN( sval ) ) { - return false; + hasEffect = false; + return hasEffect; } else { knobs_[ idim ] = sval > 1.0 ? 1.0 : 0.0; } } } } hasEffect_ = hasEffect; - return true; + return hasEffect; } public void tweakColor( float[] rgba ) { if ( hasEffect_ ) { for ( int idim = 0; idim < ndim_; idim++ ) { Shader shader = shaders_[ idim ]; if ( shader != null ) { double knob = knobs_[ idim ]; if ( ! Double.isNaN( knob ) ) { shader.adjustRgba( rgba, (float) knob ); } } } } } public Color tweakColor( Color orig ) { if ( hasEffect_ ) { float[] rgba = orig.getRGBComponents( null ); tweakColor( rgba ); return new Color( rgba[ 0 ], rgba[ 1 ], rgba[ 2 ], rgba[ 3 ] ); } else { return orig; } } /** * Returns a new tweaker suitable for a given plot. Iff no colour * tweaking will be performed (that is, if such an object would do no work) * then null will be returned. * * @param ioff offset into supplied coordinate arrays at which * auxiliary data starts * @param state describes the plot for which this object will be used * @return new tweaker, or null */ public static ShaderTweaker createTweaker( int ioff, PlotState state ) { Shader[] shaders = state.getShaders(); int naux = shaders.length; if ( naux == 0 ) { return null; } else { int nd = state.getMainNdim(); double[][] ranges; if ( ioff == nd ) { ranges = state.getRanges(); } /* If necessary adjust for the case in which there is a different * number of geometrical axes than non-auxiliary axes. */ else { ranges = new double[ ioff + naux ][]; System.arraycopy( state.getRanges(), nd, ranges, ioff, naux ); } return new ShaderTweaker( ioff, shaders, ranges, state.getLogFlags(), state.getFlipFlags() ); } } /** * Factory method for scaler objects which normalise auxiliary coordinate * data values. * * @param lo data lower limit * @param hi data upper limit * @param logFlag whether logarithmic scaling is to be used * @param flip whether axis is to be inverted */ private static Scaler createScaler( final double lo, final double hi, boolean logFlag, boolean flipFlag ) { if ( logFlag ) { final double base1 = 1.0 / ( flipFlag ? hi : lo ); final double scale1 = 1.0 / ( Math.log( flipFlag ? lo / hi : hi / lo ) ); return new Scaler( lo, hi ) { public double scale( double value ) { return Math.log( value * base1 ) * scale1; } }; } else { final double base = flipFlag ? hi : lo; final double scale1 = 1.0 / ( flipFlag ? lo - hi : hi - lo ); return new Scaler( lo, hi ) { public double scale( double value ) { return ( value - base ) * scale1; } }; } } /** * Interface for normalising coordinate data values to the range 0..1. */ private static abstract class Scaler { private final double lo_; private final double hi_; /** * Constructor. * * @param lo lower bound for data of interest * @param hi upper bound for data of interest */ public Scaler( double lo, double hi ) { lo_ = lo; hi_ = hi; } /** * Indicates whether a value is in the coordinate range of interest * to this object. * * @param value value to test * @return true iff <code>value</code> is in data range of interest */ public boolean inRange( double value ) { return value >= lo_ && value <= hi_; } /** * Maps a value in this Scaler's range of interest to the range 0..1. * If <code>inRange(value)</code> then <code>0<=scale(value)<=1</code>. * Outside that range results are undefined. * * @param value value in data range of interest * @return value in range 0..1 */ public abstract double scale( double value ); } }
false
true
public boolean setCoords( double[] coords ) { boolean hasEffect = false; for ( int idim = 0; idim < ndim_; idim++ ) { if ( shaders_[ idim ] != null ) { int jdim = ioff_ + idim; double value = coords[ jdim ]; if ( Double.isNaN( value ) ) { knobs_[ idim ] = Double.NaN; } else { hasEffect = true; Scaler scaler = scalers_[ idim ]; double sval = scaler.scale( value ); if ( scaler.inRange( value ) ) { knobs_[ idim ] = sval; assert sval >= 0.0 && sval <= 1.0; } else if ( Double.isNaN( sval ) ) { return false; } else { knobs_[ idim ] = sval > 1.0 ? 1.0 : 0.0; } } } } hasEffect_ = hasEffect; return true; }
public boolean setCoords( double[] coords ) { boolean hasEffect = false; for ( int idim = 0; idim < ndim_; idim++ ) { if ( shaders_[ idim ] != null ) { int jdim = ioff_ + idim; double value = coords[ jdim ]; if ( Double.isNaN( value ) ) { knobs_[ idim ] = Double.NaN; } else { hasEffect = true; Scaler scaler = scalers_[ idim ]; double sval = scaler.scale( value ); if ( scaler.inRange( value ) ) { knobs_[ idim ] = sval; assert sval >= 0.0 && sval <= 1.0; } else if ( Double.isNaN( sval ) ) { hasEffect = false; return hasEffect; } else { knobs_[ idim ] = sval > 1.0 ? 1.0 : 0.0; } } } } hasEffect_ = hasEffect; return hasEffect; }
diff --git a/src/main/java/net/praqma/hudson/scm/PucmScm.java b/src/main/java/net/praqma/hudson/scm/PucmScm.java index fdb139f..f0a7a15 100644 --- a/src/main/java/net/praqma/hudson/scm/PucmScm.java +++ b/src/main/java/net/praqma/hudson/scm/PucmScm.java @@ -1,704 +1,705 @@ package net.praqma.hudson.scm; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.FilePath.FileCallable; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.FreeStyleBuild; import hudson.model.ParameterValue; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Job; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.scm.SCM; import hudson.util.FormValidation; import hudson.util.VariableResolver; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.praqma.clearcase.ucm.UCMException; import net.praqma.clearcase.ucm.entities.Project; import net.praqma.clearcase.ucm.entities.Baseline; import net.praqma.clearcase.ucm.entities.Activity; import net.praqma.clearcase.ucm.entities.Component; import net.praqma.clearcase.ucm.utils.BaselineList; import net.praqma.clearcase.ucm.entities.Stream; import net.praqma.clearcase.ucm.entities.UCMEntity; import net.praqma.clearcase.ucm.entities.Version; import net.praqma.clearcase.ucm.view.SnapshotView; import net.praqma.clearcase.ucm.view.SnapshotView.COMP; import net.praqma.clearcase.ucm.view.UCMView; import net.praqma.clearcase.ucm.utils.BaselineDiff; import net.praqma.hudson.Config; import net.praqma.hudson.exception.ScmException; import net.praqma.hudson.scm.PucmState.State; import net.praqma.util.debug.Logger; import net.sf.json.JSONObject; //import net.praqma.hudson.Version; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.export.Exported; /** * CC4HClass is responsible for everything regarding Hudsons connection to * ClearCase pre-build. This class defines all the files required by the user. * The information can be entered on the config page. * * @author Troels Selch S�rensen * @author Margit Bennetzen * */ public class PucmScm extends SCM { private String levelToPoll; private String loadModule; private String component; private String stream; private boolean newest; private Baseline bl; private List<String> levels = null; private List<String> loadModules = null; //private BaselineList baselines; private boolean compRevCalled; private StringBuffer pollMsgs = new StringBuffer(); private Stream integrationstream; private Component comp; private SnapshotView sv = null; private boolean doPostBuild = true; private String buildProject; private String jobName = ""; private Integer jobNumber; private String id = ""; protected static Logger logger = Logger.getLogger(); public static PucmState pucm = new PucmState(); /** * The constructor is used by Hudson to create the instance of the plugin * needed for a connection to ClearCase. It is annotated with * <code>@DataBoundConstructor</code> to tell Hudson where to put the * information retrieved from the configuration page in the WebUI. * * @param component * defines the component needed to find baselines. * @param levelToPoll * defines the level to poll ClearCase for. * @param loadModule * tells if we should load all modules or only the ones that are * modifiable. * @param stream * defines the stream needed to find baselines. * @param newest * tells whether we should build only the newest baseline. * @param newerThanRecommended * tells whether we should look at all baselines or only ones * newer than the recommended baseline */ @DataBoundConstructor public PucmScm( String component, String levelToPoll, String loadModule, String stream, boolean newest, boolean testing, String buildProject ) { logger.trace_function(); logger.debug( "PucmSCM constructor" ); this.component = component; this.levelToPoll = levelToPoll; this.loadModule = loadModule; this.stream = stream; this.newest = newest; this.buildProject = buildProject; } @Override public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName(); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.includeClass( i.trim() ); } } if ( build.getBuildVariables().get( "pucm_baseline" ) != null ) { Stream integrationstream = null; String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); integrationstream = bl.GetStream(); + state.setStream( state.getBaseline().GetStream() ); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + integrationstream.GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { //baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { bl.Load(); } catch( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } if( bl == null ) { consoleOutput.println( "[PUCM] bl is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject ); String changelog = workspace.act( ct ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } //doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); doPostBuild = false; result = false; } } //pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) ); //state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; } @Override public ChangeLogParser createChangeLogParser() { logger.trace_function(); return new ChangeLogParserImpl(); } @Override public PollingResult compareRemoteRevisionWith( AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline ) throws IOException, InterruptedException { this.id = "[" + project.getDisplayName() + "::" + project.getNextBuildNumber() + "]"; logger.trace_function(); logger.debug( id + "PucmSCM Pollingresult" ); /* Make a state object, which is only temporary, only to determine if there's baselines to build this object will be stored in checkout */ jobName = project.getDisplayName(); jobNumber = project.getNextBuildNumber(); /* This number is not the final job number */ State state = pucm.getState( jobName, jobNumber ); PollingResult p; try { //baselinesToBuild( component, stream, project, project.getDisplayName(), project.getNextBuildNumber() ); baselinesToBuild( project, state ); compRevCalled = true; logger.info( id + "Polling result = BUILD NOW" ); p = PollingResult.BUILD_NOW; } catch ( ScmException e ) { logger.info( id + "Polling result = NO CHANGES" ); p = PollingResult.NO_CHANGES; PrintStream consoleOut = listener.getLogger(); consoleOut.println( pollMsgs + "\n" + e.getMessage() ); pollMsgs = new StringBuffer(); logger.debug( id + "Removed job " + state.getJobNumber() + " from list" ); state.remove(); } logger.debug( id + "FINAL Polling result = " + p.change.toString() ); return p; } @Override public SCMRevisionState calcRevisionsFromBuild( AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( id + "PucmSCM calcRevisionsFromBuild" ); // PrintStream hudsonOut = listener.getLogger(); SCMRevisionStateImpl scmRS = null; if ( !( bl == null ) ) { scmRS = new SCMRevisionStateImpl(); } return scmRS; } private void baselinesToBuild( AbstractProject<?, ?> project, State state ) throws ScmException { logger.trace_function(); /* Store the component to the state */ try { state.setComponent( UCMEntity.GetComponent( component, false ) ); } catch ( UCMException e ) { throw new ScmException( "Could not get component. " + e.getMessage() ); } /* Store the stream to the state */ try { state.setStream( UCMEntity.GetStream( stream, false ) ); } catch ( UCMException e ) { throw new ScmException( "Could not get stream. " + e.getMessage() ); } state.setPlevel( Project.Plevel.valueOf( levelToPoll ) ); /* The baseline list */ BaselineList baselines = null; try { pollMsgs.append( "[PUCM] Getting all baselines for :\n[PUCM] * Stream: " ); pollMsgs.append( stream ); pollMsgs.append( "\n[PUCM] * Component: " ); pollMsgs.append( component ); pollMsgs.append( "\n[PUCM] * Promotionlevel: " ); pollMsgs.append( levelToPoll ); pollMsgs.append( "\n" ); baselines = state.getComponent().GetBaselines( state.getStream(), state.getPlevel() ); } catch ( UCMException e ) { throw new ScmException( "Could not retrieve baselines from repository. " + e.getMessage() ); } if ( baselines.size() > 0 ) { printBaselines( baselines ); logger.debug( id + "PUCM=" + pucm.stringify() ); try { List<Baseline> baselinelist = state.getStream().GetRecommendedBaselines(); pollMsgs.append( "\n[PUCM] Recommended baseline(s): \n" ); for ( Baseline b : baselinelist ) { pollMsgs.append( b.GetShortname() + "\n" ); } /* Determine the baseline to build */ bl = null; state.setBaseline( null ); /* For each baseline retrieved from ClearCase */ //for ( Baseline b : baselinelist ) int start = 0; int stop = baselines.size(); int increment = 1; if( newest ) { start = baselines.size() - 1; //stop = 0; increment = -1; } /* Find the Baseline to build */ for( int i = start ; i < stop && i >= 0 ; i += increment ) { /* The current baseline */ Baseline b = baselines.get( i ); State cstate = pucm.getStateByBaseline( jobName, b.GetFQName() ); /* The baseline is in progress, determine if the job is still running */ //if( thisJob.containsKey( b.GetFQName() ) ) if( cstate != null ) { //Integer bnum = thisJob.get( b.GetFQName() ); //State Integer bnum = cstate.getJobNumber(); Object o = project.getBuildByNumber( bnum ); Build bld = (Build)o; /* The job is not running */ if( !bld.isLogUpdated() ) { logger.debug( id + "Job " + bld.getNumber() + " is not building, using baseline: " + b ); bl = b; //thisJob.put( b.GetFQName(), state.getJobNumber() ); break; } else { logger.debug( id + "Job " + bld.getNumber() + " is building " + cstate.getBaseline().GetFQName() ); } } /* The baseline is available */ else { bl = b; //thisJob.put( b.GetFQName(), state.getJobNumber() ); logger.debug( id + "The baseline " + b + " is available" ); break; } } if( bl == null ) { logger.log( id + "No baselines available on chosen parameters." ); throw new ScmException( "No baselines available on chosen parameters." ); } pollMsgs.append( "\n[PUCM] Building baseline: " + bl + "\n" ); state.setBaseline( bl ); /* Store the baseline to build */ //thisJob.put( bl.GetFQName(), state.getJobNumber() ); } catch ( UCMException e ) { throw new ScmException( "Could not get recommended baselines. " + e.getMessage() ); } } else { throw new ScmException( "No baselines on chosen parameters." ); } //logger.debug( id + "PRINTING THIS JOB:" ); //logger.debug( net.praqma.util.structure.Printer.mapPrinterToString( thisJob ) ); } private void printBaselines( BaselineList baselines ) { pollMsgs.append( "[PUCM] Retrieved baselines:\n" ); if ( !( baselines.size() > 20 ) ) { for ( Baseline b : baselines ) { pollMsgs.append( b.GetShortname() ); pollMsgs.append( "\n" ); } } else { int i = baselines.size(); pollMsgs.append( "[PUCM] There are " + i + " baselines - only printing first and last three\n" ); pollMsgs.append( baselines.get( 0 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( 1 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( 2 ).GetShortname() + "\n" ); pollMsgs.append( "...\n" ); pollMsgs.append( baselines.get( i - 3 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( i - 2 ).GetShortname() + "\n" ); pollMsgs.append( baselines.get( i - 1 ).GetShortname() + "\n" ); } } /* * The following getters and booleans (six in all) are used to display saved * userdata in Hudsons gui */ public String getLevelToPoll() { logger.trace_function(); return levelToPoll; } public String getComponent() { logger.trace_function(); return component; } public String getStream() { logger.trace_function(); return stream; } public String getLoadModule() { logger.trace_function(); return loadModule; } public boolean isNewest() { logger.trace_function(); return newest; } /* * getStreamObject() and getBaseline() are used by PucmNotifier to get the * Baseline and Stream in use */ public Stream getStreamObject() { logger.trace_function(); return integrationstream; } @Exported public Baseline getBaseline() { logger.trace_function(); return bl; } @Exported public boolean doPostbuild() { logger.trace_function(); return doPostBuild; } public String getBuildProject() { logger.trace_function(); return buildProject; } /** * This class is used to describe the plugin to Hudson * * @author Troels Selch S�rensen * @author Margit Bennetzen * */ @Extension public static class PucmScmDescriptor extends SCMDescriptor<PucmScm> { private String cleartool; private List<String> loadModules; public PucmScmDescriptor() { super( PucmScm.class, null ); logger.trace_function(); loadModules = getLoadModules(); load(); Config.setContext(); } /** * This method is called, when the user saves the global Hudson * configuration. */ @Override public boolean configure( org.kohsuke.stapler.StaplerRequest req, JSONObject json ) throws FormException { logger.trace_function(); cleartool = req.getParameter( "PUCM.cleartool" ).trim(); save(); return true; } /** * This is called by Hudson to discover the plugin name */ @Override public String getDisplayName() { logger.trace_function(); return "Praqmatic UCM"; } /** * This method is called by the scm/Pucm/global.jelly to validate the * input without reloading the global configuration page * * @param value * @return */ public FormValidation doExecutableCheck( @QueryParameter String value ) { logger.trace_function(); return FormValidation.validateExecutable( value ); } /** * Called by Hudson. If the user does not input a command for Hudson to * use when polling, default value is returned * * @return */ public String getCleartool() { logger.trace_function(); if ( cleartool == null || cleartool.equals( "" ) ) { return "cleartool"; } return cleartool; } /** * Used by Hudson to display a list of valid promotion levels to build * from. The list of promotion levels is hard coded in * net.praqma.hudson.Config.java * * @return */ public List<String> getLevels() { logger.trace_function(); return Config.getLevels(); } /** * Used by Hudson to display a list of loadModules (whether to poll all * or only modifiable elements * * @return */ public List<String> getLoadModules() { logger.trace_function(); loadModules = new ArrayList<String>(); loadModules.add( "All" ); loadModules.add( "Modifiable" ); return loadModules; } } }
true
true
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName(); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.includeClass( i.trim() ); } } if ( build.getBuildVariables().get( "pucm_baseline" ) != null ) { Stream integrationstream = null; String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); integrationstream = bl.GetStream(); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + integrationstream.GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { //baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { bl.Load(); } catch( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } if( bl == null ) { consoleOutput.println( "[PUCM] bl is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject ); String changelog = workspace.act( ct ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } //doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); doPostBuild = false; result = false; } } //pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) ); //state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; }
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException { logger.trace_function(); logger.debug( "PucmSCM checkout" ); boolean result = true; // consoleOutput Printstream is from Hudson, so it can only be accessed // here PrintStream consoleOutput = listener.getLogger(); consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" ); /* Recalculate the states */ int count = pucm.recalculate( build.getProject() ); logger.info( "Removed " + count + " from states." ); doPostBuild = true; jobName = build.getParent().getDisplayName(); jobNumber = build.getNumber(); /* If we polled, we should get the same object created at that point */ State state = pucm.getState( jobName, jobNumber ); logger.debug( id + "The initial state:\n" + state.stringify() ); this.id = "[" + jobName + "::" + jobNumber + "]"; if ( build.getBuildVariables().get( "include_classes" ) != null ) { String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," ); for( String i : is ) { logger.includeClass( i.trim() ); } } if ( build.getBuildVariables().get( "pucm_baseline" ) != null ) { Stream integrationstream = null; String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" ); try { state.setBaseline( UCMEntity.GetBaseline( baselinename ) ); integrationstream = bl.GetStream(); state.setStream( state.getBaseline().GetStream() ); consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + integrationstream.GetShortname() ); } catch ( UCMException e ) { consoleOutput.println( "[PUCM] Could not find baseline from parameter." ); state.setPostBuild( false ); result = false; } } else { // compRevCalled tells whether we have polled for baselines to build // - // so if we haven't polled, we do it now if ( !compRevCalled ) { try { //baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() ); baselinesToBuild( build.getProject(), state ); } catch ( ScmException e ) { pollMsgs.append( e.getMessage() ); result = false; } } compRevCalled = false; // pollMsgs are set in either compareRemoteRevisionWith() or // baselinesToBuild() consoleOutput.println( pollMsgs ); pollMsgs = new StringBuffer(); } if ( result ) { try { /* Force the Baseline to be loaded */ try { bl.Load(); } catch( UCMException e ) { logger.debug( id + "Could not load Baseline" ); consoleOutput.println( "[PUCM] Could not load Baseline." ); } /* Check parameters */ if( listener == null ) { consoleOutput.println( "[PUCM] Listener is null" ); } if( jobName == null ) { consoleOutput.println( "[PUCM] jobname is null" ); } if( build == null ) { consoleOutput.println( "[PUCM] BUILD is null" ); } if( stream == null ) { consoleOutput.println( "[PUCM] stream is null" ); } if( loadModule == null ) { consoleOutput.println( "[PUCM] loadModule is null" ); } if( buildProject == null ) { consoleOutput.println( "[PUCM] buildProject is null" ); } if( bl == null ) { consoleOutput.println( "[PUCM] bl is null" ); } CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject ); String changelog = workspace.act( ct ); /* Write change log */ try { FileOutputStream fos = new FileOutputStream( changelogFile ); fos.write( changelog.getBytes() ); fos.close(); } catch( IOException e ) { logger.debug( id + "Could not write change log file" ); consoleOutput.println( "[PUCM] Could not write change log file" ); } //doPostBuild = changelog.length() > 0 ? true : false; } catch ( Exception e ) { consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() ); doPostBuild = false; result = false; } } //pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) ); //state.save(); logger.debug( id + "The CO state:\n" + state.stringify() ); return result; }
diff --git a/src/main/java/tconstruct/modifiers/tools/ModReinforced.java b/src/main/java/tconstruct/modifiers/tools/ModReinforced.java index 757c57d2c..d1713bfb6 100644 --- a/src/main/java/tconstruct/modifiers/tools/ModReinforced.java +++ b/src/main/java/tconstruct/modifiers/tools/ModReinforced.java @@ -1,70 +1,70 @@ package tconstruct.modifiers.tools; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; public class ModReinforced extends ModInteger { public ModReinforced(ItemStack[] items, int effect, int increase) { super(items, effect, "Reinforced", 1, "\u00a75", "Reinforced"); } @Override public void modify (ItemStack[] input, ItemStack tool) { NBTTagCompound tags = tool.getTagCompound().getCompoundTag("InfiTool"); if (tags.hasKey(key)) { int increase = tags.getInteger(key); increase += secondaryIncrease; tags.setInteger(key, increase); } else { tags.setInteger(key, initialIncrease); } int modifiers = tags.getInteger("Modifiers"); modifiers -= 1; tags.setInteger("Modifiers", modifiers); int reinforced = tags.getInteger("Unbreaking"); reinforced += 1; tags.setInteger("Unbreaking", reinforced); addToolTip(tool, color + tooltipName, color + key); } protected int addToolTip (ItemStack tool, String tooltip, String modifierTip) { NBTTagCompound tags = tool.getTagCompound().getCompoundTag("InfiTool"); int tipNum = 0; while (true) { tipNum++; String tip = "Tooltip" + tipNum; if (!tags.hasKey(tip)) { - //tags.setString(tip, tooltip); + tags.setString(tip, ""); String modTip = "ModifierTip" + tipNum; String tag = tags.getString(modTip); tags.setString(modTip, getProperName(modifierTip, tag)); return tipNum; } else { String modTip = "ModifierTip" + tipNum; String tag = tags.getString(modTip); if (tag.contains(modifierTip)) { - //tags.setString(tip, getProperName(tooltip, tag)); + tags.setString(tip, ""); tag = tags.getString(modTip); tags.setString(modTip, getProperName(modifierTip, tag)); return tipNum; } } } } }
false
true
protected int addToolTip (ItemStack tool, String tooltip, String modifierTip) { NBTTagCompound tags = tool.getTagCompound().getCompoundTag("InfiTool"); int tipNum = 0; while (true) { tipNum++; String tip = "Tooltip" + tipNum; if (!tags.hasKey(tip)) { //tags.setString(tip, tooltip); String modTip = "ModifierTip" + tipNum; String tag = tags.getString(modTip); tags.setString(modTip, getProperName(modifierTip, tag)); return tipNum; } else { String modTip = "ModifierTip" + tipNum; String tag = tags.getString(modTip); if (tag.contains(modifierTip)) { //tags.setString(tip, getProperName(tooltip, tag)); tag = tags.getString(modTip); tags.setString(modTip, getProperName(modifierTip, tag)); return tipNum; } } } }
protected int addToolTip (ItemStack tool, String tooltip, String modifierTip) { NBTTagCompound tags = tool.getTagCompound().getCompoundTag("InfiTool"); int tipNum = 0; while (true) { tipNum++; String tip = "Tooltip" + tipNum; if (!tags.hasKey(tip)) { tags.setString(tip, ""); String modTip = "ModifierTip" + tipNum; String tag = tags.getString(modTip); tags.setString(modTip, getProperName(modifierTip, tag)); return tipNum; } else { String modTip = "ModifierTip" + tipNum; String tag = tags.getString(modTip); if (tag.contains(modifierTip)) { tags.setString(tip, ""); tag = tags.getString(modTip); tags.setString(modTip, getProperName(modifierTip, tag)); return tipNum; } } } }
diff --git a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/SearchEngine.java b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/SearchEngine.java index 4c2784254..90453e2ed 100644 --- a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/SearchEngine.java +++ b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/core/search/SearchEngine.java @@ -1,781 +1,781 @@ /******************************************************************************* * Copyright (c) 2000, 2006 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.dltk.core.search; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.dltk.core.IBuildpathEntry; import org.eclipse.dltk.core.IBuiltinModuleProvider; import org.eclipse.dltk.core.IDLTKLanguageToolkit; import org.eclipse.dltk.core.IModelElement; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.IType; import org.eclipse.dltk.core.ModelException; import org.eclipse.dltk.core.WorkingCopyOwner; import org.eclipse.dltk.core.search.indexing.IndexManager; import org.eclipse.dltk.internal.compiler.env.AccessRuleSet; import org.eclipse.dltk.internal.core.ModelManager; import org.eclipse.dltk.internal.core.Openable; import org.eclipse.dltk.internal.core.search.IndexQueryRequestor; import org.eclipse.dltk.internal.core.search.PatternSearchJob; import org.eclipse.dltk.internal.core.search.TypeNameMatchRequestorWrapper; import org.eclipse.dltk.internal.core.search.TypeNameRequestorWrapper; import org.eclipse.dltk.internal.core.search.matching.MixinPattern; import org.eclipse.dltk.internal.core.util.HandleFactory; /** * A {@link SearchEngine} searches for Script elements following a search pattern. * The search can be limited to a search scope. * <p> * Various search patterns can be created using the factory methods * {@link SearchPattern#createPattern(String, int, int, int)}, {@link SearchPattern#createPattern(IModelElement, int)}, * {@link SearchPattern#createOrPattern(SearchPattern, SearchPattern)}. * </p> * <p>For example, one can search for references to a method in the hierarchy of a type, * or one can search for the declarations of types starting with "Abstract" in a project. * </p> * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> */ public class SearchEngine { private static final String SPECIAL_MIXIN = "#special#mixin:"; // Search engine now uses basic engine functionalities private BasicSearchEngine basicEngine; /** * Creates a new search engine. */ public SearchEngine() { this.basicEngine = new BasicSearchEngine(); } /** * Creates a new search engine with a list of working copies that will take precedence over * their original compilation units in the subsequent search operations. * <p> * Note that passing an empty working copy will be as if the original compilation * unit had been deleted.</p> * <p> * The given working copies take precedence over primary working copies (if any). * * @param workingCopies the working copies that take precedence over their original compilation units * */ public SearchEngine(ISourceModule[] workingCopies) { int length = workingCopies.length; ISourceModule[] units = new ISourceModule[length]; System.arraycopy(workingCopies, 0, units, 0, length); this.basicEngine = new BasicSearchEngine(units); } /** * Creates a new search engine with the given working copy owner. * The working copies owned by this owner will take precedence over * the primary compilation units in the subsequent search operations. * * @param workingCopyOwner the owner of the working copies that take precedence over their original compilation units * */ public SearchEngine(WorkingCopyOwner workingCopyOwner) { this.basicEngine = new BasicSearchEngine(workingCopyOwner); } /** * Returns a Script search scope limited to the hierarchy of the given type. * The Script elements resulting from a search with this scope will * be types in this hierarchy, or members of the types in this hierarchy. * * @param type the focus of the hierarchy scope * @return a new hierarchy scope * @exception ModelException if the hierarchy could not be computed on the given type */ public static IDLTKSearchScope createHierarchyScope(IType type) throws ModelException { return BasicSearchEngine.createHierarchyScope(type); } /** * Returns a Script search scope limited to the hierarchy of the given type. * When the hierarchy is computed, the types defined in the working copies owned * by the given owner take precedence over the original compilation units. * The Script elements resulting from a search with this scope will * be types in this hierarchy, or members of the types in this hierarchy. * * @param type the focus of the hierarchy scope * @param owner the owner of working copies that take precedence over original compilation units * @return a new hierarchy scope * @exception ModelException if the hierarchy could not be computed on the given type * */ public static IDLTKSearchScope createHierarchyScope(IType type, WorkingCopyOwner owner) throws ModelException { return BasicSearchEngine.createHierarchyScope(type, owner); } /** * Returns a Script search scope limited to the given Script elements. * The Script elements resulting from a search with this scope will * be children of the given elements. * <p> * If an element is an IScriptProject, then the project's source folders, * its jars (external and internal) and its referenced projects (with their source * folders and jars, recursively) will be included. * If an element is an IProjectFragment, then only the package fragments of * this package fragment root will be included. * If an element is an IScriptFolder, then only the compilation unit and class * files of this package fragment will be included. Subpackages will NOT be * included.</p> * <p> * In other words, this is equivalent to using SearchEngine.createJavaSearchScope(elements, true).</p> * * @param elements the Script elements the scope is limited to * @return a new Script search scope * */ public static IDLTKSearchScope createSearchScope(IModelElement[] elements) { return BasicSearchEngine.createSearchScope(elements); } /** * Returns a Script search scope limited to the given Script elements. * The Script elements resulting from a search with this scope will * be children of the given elements. * * If an element is an IScriptProject, then the project's source folders, * its jars (external and internal) and - if specified - its referenced projects * (with their source folders and jars, recursively) will be included. * If an element is an IProjectFragment, then only the package fragments of * this package fragment root will be included. * If an element is an IScriptFolder, then only the compilation unit and class * files of this package fragment will be included. Subpackages will NOT be * included. * * @param elements the Script elements the scope is limited to * @param includeReferencedProjects a flag indicating if referenced projects must be * recursively included * @return a new Script search scope * */ public static IDLTKSearchScope createSearchScope(IModelElement[] elements, boolean includeReferencedProjects) { return BasicSearchEngine.createSearchScope(elements, includeReferencedProjects); } /** * Returns a Script search scope limited to the given Script elements. * The Script elements resulting from a search with this scope will * be children of the given elements. * * If an element is an IScriptProject, then it includes: * - its source folders if IJavaSearchScope.SOURCES is specified, * - its application libraries (internal and external jars, class folders that are on the raw buildpath, * or the ones that are coming from a buildpath path variable, * or the ones that are coming from a buildpath container with the K_APPLICATION kind) * if IJavaSearchScope.APPLICATION_LIBRARIES is specified * - its system libraries (internal and external jars, class folders that are coming from an * IBuildpathContainer with the K_SYSTEM kind) * if IJavaSearchScope.APPLICATION_LIBRARIES is specified * - its referenced projects (with their source folders and jars, recursively) * if IJavaSearchScope.REFERENCED_PROJECTS is specified. * If an element is an IProjectFragment, then only the package fragments of * this package fragment root will be included. * If an element is an IScriptFolder, then only the compilation unit and class * files of this package fragment will be included. Subpackages will NOT be * included. * * @param elements the Script elements the scope is limited to * @param includeMask the bit-wise OR of all include types of interest * @return a new Script search scope * @see IJavaSearchScope#SOURCES * @see IJavaSearchScope#APPLICATION_LIBRARIES * @see IJavaSearchScope#SYSTEM_LIBRARIES * @see IJavaSearchScope#REFERENCED_PROJECTS * */ public static IDLTKSearchScope createSearchScope(IModelElement[] elements, int includeMask) { return BasicSearchEngine.createSearchScope(elements, includeMask); } /** * Create a type name match on a given type with specific modifiers. * * @param type The java model handle of the type * @param modifiers Modifiers of the type * @return A non-null match on the given type. */ public static TypeNameMatch createTypeNameMatch(IType type, int modifiers) { return BasicSearchEngine.createTypeNameMatch(type, modifiers); } /** * Returns a Script search scope with the workspace as the only limit. * * @return a new workspace scope */ public static IDLTKSearchScope createWorkspaceScope(IDLTKLanguageToolkit toolkit) { return BasicSearchEngine.createWorkspaceScope(toolkit); } /** * Returns a new default Script search participant. * * @return a new default Script search participant * */ public static SearchParticipant getDefaultSearchParticipant() { return BasicSearchEngine.getDefaultSearchParticipant(); } /** * Searches for matches of a given search pattern. Search patterns can be created using helper * methods (from a String pattern or a Script element) and encapsulate the description of what is * being searched (for example, search method declarations in a case sensitive way). * * @param pattern the pattern to search * @param participants the particpants in the search * @param scope the search scope * @param requestor the requestor to report the matches to * @param monitor the progress monitor used to report progress * @exception CoreException if the search failed. Reasons include: * <ul> * <li>the buildpath is incorrectly set</li> * </ul> * */ public void search(SearchPattern pattern, SearchParticipant[] participants, IDLTKSearchScope scope, SearchRequestor requestor, IProgressMonitor monitor) throws CoreException { this.basicEngine.search(pattern, participants, scope, requestor, monitor); } public List searchSourceOnly(SearchPattern pattern, SearchParticipant[] participants, IDLTKSearchScope scope, IProgressMonitor monitor) throws CoreException { return this.basicEngine.searchSourceOnly(pattern, participants, scope, monitor); } /** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package exact full name or * a type name with specific match mode). * * @param packageExactName the exact package full name of the searched types.<br> * If you want to use a prefix or a wild-carded string for package, you need to use * {@link #searchAllTypeNames(char[], int, char[], int, int, IJavaSearchScope, TypeNameRequestor, int, IProgressMonitor)} method instead. * @param typeName the dot-separated qualified name of the searched type (the qualification include * the enclosing types if the searched type is a member type), or a prefix * for this type, or a wild-carded string for this type. * @param matchRule type name match rule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param searchFor determines the nature of the searched elements * <ul> * <li>{@link IDLTKSearchConstants#CLASS}: only look for classes</li> * <li>{@link IDLTKSearchConstants#INTERFACE}: only look for interfaces</li> * <li>{@link IDLTKSearchConstants#ENUM}: only look for enumeration</li> * <li>{@link IDLTKSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li> * <li>{@link IDLTKSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li> * <li>{@link IDLTKSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li> * <li>{@link IDLTKSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li> * </ul> * @param scope the scope to search in * @param nameRequestor the requestor that collects the results of the search * @param waitingPolicy one of * <ul> * <li>{@link IDLTKSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IDLTKSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IDLTKSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception ModelException if the search failed. Reasons include: * <ul> * <li>the buildpath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[] packageExactName, final char[] typeName, final int matchRule, int searchFor, IDLTKSearchScope scope, final TypeNameRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws ModelException { searchAllTypeNames(packageExactName, SearchPattern.R_EXACT_MATCH, typeName, matchRule, searchFor, scope, nameRequestor, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package name using specific match mode * and/or a type name using another specific match mode). * * @param packageName the full name of the package of the searched types, or a prefix for this * package, or a wild-carded string for this package. * @param typeName the dot-separated qualified name of the searched type (the qualification include * the enclosing types if the searched type is a member type), or a prefix * for this type, or a wild-carded string for this type. * @param packageMatchRule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param typeMatchRule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param searchFor determines the nature of the searched elements * <ul> * <li>{@link IDLTKSearchConstants#CLASS}: only look for classes</li> * <li>{@link IDLTKSearchConstants#INTERFACE}: only look for interfaces</li> * <li>{@link IDLTKSearchConstants#ENUM}: only look for enumeration</li> * <li>{@link IDLTKSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li> * <li>{@link IDLTKSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li> * <li>{@link IDLTKSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li> * <li>{@link IDLTKSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li> * </ul> * @param scope the scope to search in * @param nameRequestor the requestor that collects the results of the search * @param waitingPolicy one of * <ul> * <li>{@link IDLTKSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IDLTKSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IDLTKSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception ModelException if the search failed. Reasons include: * <ul> * <li>the buildpath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[] packageName, final int packageMatchRule, final char[] typeName, final int typeMatchRule, int searchFor, IDLTKSearchScope scope, final TypeNameRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws ModelException { TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); this.basicEngine.searchAllTypeNames(packageName, packageMatchRule, typeName, typeMatchRule, searchFor, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package name using specific match mode * and/or a type name using another specific match mode). * <p> * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} * matches found during the search. * </p> * * @param packageName the full name of the package of the searched types, or a prefix for this * package, or a wild-carded string for this package. * May be <code>null</code>, then any package name is accepted. * @param packageMatchRule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param typeName the dot-separated qualified name of the searched type (the qualification include * the enclosing types if the searched type is a member type), or a prefix * for this type, or a wild-carded string for this type. * May be <code>null</code>, then any type name is accepted. * @param typeMatchRule one of * <ul> * <li>{@link SearchPattern#R_EXACT_MATCH} if the package name and type name are the full names * of the searched types.</li> * <li>{@link SearchPattern#R_PREFIX_MATCH} if the package name and type name are prefixes of the names * of the searched types.</li> * <li>{@link SearchPattern#R_PATTERN_MATCH} if the package name and type name contain wild-cards.</li> * <li>{@link SearchPattern#R_CAMELCASE_MATCH} if type name are camel case of the names of the searched types.</li> * </ul> * combined with {@link SearchPattern#R_CASE_SENSITIVE}, * e.g. {@link SearchPattern#R_EXACT_MATCH} | {@link SearchPattern#R_CASE_SENSITIVE} if an exact and case sensitive match is requested, * or {@link SearchPattern#R_PREFIX_MATCH} if a prefix non case sensitive match is requested. * @param searchFor determines the nature of the searched elements * <ul> * <li>{@link IJavaSearchConstants#CLASS}: only look for classes</li> * <li>{@link IJavaSearchConstants#INTERFACE}: only look for interfaces</li> * <li>{@link IJavaSearchConstants#ENUM}: only look for enumeration</li> * <li>{@link IJavaSearchConstants#ANNOTATION_TYPE}: only look for annotation type</li> * <li>{@link IJavaSearchConstants#CLASS_AND_ENUM}: only look for classes and enumerations</li> * <li>{@link IJavaSearchConstants#CLASS_AND_INTERFACE}: only look for classes and interfaces</li> * <li>{@link IJavaSearchConstants#TYPE}: look for all types (ie. classes, interfaces, enum and annotation types)</li> * </ul> * @param scope the scope to search in * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects * {@link TypeNameMatch matches} of the search. * @param waitingPolicy one of * <ul> * <li>{@link IJavaSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IJavaSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IJavaSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception JavaModelException if the search failed. Reasons include: * <ul> * <li>the classpath is incorrectly set</li> * </ul> * @since 3.3 */ public void searchAllTypeNames( final char[] packageName, final int packageMatchRule, final char[] typeName, final int typeMatchRule, int searchFor, IDLTKSearchScope scope, final TypeNameMatchRequestor nameMatchRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws ModelException { TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); this.basicEngine.searchAllTypeNames(packageName, packageMatchRule, typeName, typeMatchRule, searchFor, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope matching any of the given qualifications * and type names in a case sensitive way. * * @param qualifications the qualified name of the package/enclosing type of the searched types * @param typeNames the simple names of the searched types * @param scope the scope to search in * @param nameRequestor the requestor that collects the results of the search * @param waitingPolicy one of * <ul> * <li>{@link IDLTKSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IDLTKSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IDLTKSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception ModelException if the search failed. Reasons include: * <ul> * <li>the buildpath is incorrectly set</li> * </ul> * */ public void searchAllTypeNames( final char[][] qualifications, final char[][] typeNames, IDLTKSearchScope scope, final TypeNameRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws ModelException { TypeNameRequestorWrapper requestorWrapper = new TypeNameRequestorWrapper(nameRequestor); this.basicEngine.searchAllTypeNames( qualifications, typeNames, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IDLTKSearchConstants.TYPE, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all top-level types and member types in the given scope matching any of the given qualifications * and type names in a case sensitive way. * <p> * Provided {@link TypeNameMatchRequestor} requestor will collect {@link TypeNameMatch} * matches found during the search. * </p> * * @param qualifications the qualified name of the package/enclosing type of the searched types. * May be <code>null</code>, then any package name is accepted. * @param typeNames the simple names of the searched types. * If this parameter is <code>null</code>, then no type will be found. * @param scope the scope to search in * @param nameMatchRequestor the {@link TypeNameMatchRequestor requestor} that collects * {@link TypeNameMatch matches} of the search. * @param waitingPolicy one of * <ul> * <li>{@link IJavaSearchConstants#FORCE_IMMEDIATE_SEARCH} if the search should start immediately</li> * <li>{@link IJavaSearchConstants#CANCEL_IF_NOT_READY_TO_SEARCH} if the search should be cancelled if the * underlying indexer has not finished indexing the workspace</li> * <li>{@link IJavaSearchConstants#WAIT_UNTIL_READY_TO_SEARCH} if the search should wait for the * underlying indexer to finish indexing the workspace</li> * </ul> * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress * monitor is provided * @exception JavaModelException if the search failed. Reasons include: * <ul> * <li>the classpath is incorrectly set</li> * </ul> */ public void searchAllTypeNames( final char[][] qualifications, final char[][] typeNames, IDLTKSearchScope scope, final TypeNameMatchRequestor nameMatchRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws ModelException { TypeNameMatchRequestorWrapper requestorWrapper = new TypeNameMatchRequestorWrapper(nameMatchRequestor, scope); this.basicEngine.searchAllTypeNames( qualifications, typeNames, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, IDLTKSearchConstants.TYPE, scope, requestorWrapper, waitingPolicy, progressMonitor); } /** * Searches for all declarations of the fields accessed in the given element. * The element can be a compilation unit, a source type, or a source method. * Reports the field declarations using the given requestor. * <p> * Consider the following code: * <code> * <pre> * class A { * int field1; * } * class B extends A { * String value; * } * class X { * void test() { * B b = new B(); * System.out.println(b.value + b.field1); * }; * } * </pre> * </code> * then searching for declarations of accessed fields in method * <code>X.test()</code> would collect the fields * <code>B.value</code> and <code>A.field1</code>. * </p> * * @param enclosingElement the method, type, or compilation unit to be searched in * @param requestor a callback object to which each match is reported * @param monitor the progress monitor used to report progress * @exception ModelException if the search failed. Reasons include: * <ul> * <li>the element doesn't exist</li> * <li>the buildpath is incorrectly set</li> * </ul> * */ public void searchDeclarationsOfAccessedFields(IModelElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws ModelException { this.basicEngine.searchDeclarationsOfAccessedFields(enclosingElement, requestor, monitor); } /** * Searches for all declarations of the types referenced in the given element. * The element can be a compilation unit, a source type, or a source method. * Reports the type declarations using the given requestor. * <p> * Consider the following code: * <code> * <pre> * class A { * } * class B extends A { * } * interface I { * int VALUE = 0; * } * class X { * void test() { * B b = new B(); * this.foo(b, I.VALUE); * }; * } * </pre> * </code> * then searching for declarations of referenced types in method <code>X.test()</code> * would collect the class <code>B</code> and the interface <code>I</code>. * </p> * * @param enclosingElement the method, type, or compilation unit to be searched in * @param requestor a callback object to which each match is reported * @param monitor the progress monitor used to report progress * @exception ModelException if the search failed. Reasons include: * <ul> * <li>the element doesn't exist</li> * <li>the buildpath is incorrectly set</li> * </ul> * */ public void searchDeclarationsOfReferencedTypes(IModelElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws ModelException { this.basicEngine.searchDeclarationsOfReferencedTypes(enclosingElement, requestor, monitor); } /** * Searches for all declarations of the methods invoked in the given element. * The element can be a compilation unit, a source type, or a source method. * Reports the method declarations using the given requestor. * <p> * Consider the following code: * <code> * <pre> * class A { * void foo() {}; * void bar() {}; * } * class B extends A { * void foo() {}; * } * class X { * void test() { * A a = new B(); * a.foo(); * B b = (B)a; * b.bar(); * }; * } * </pre> * </code> * then searching for declarations of sent messages in method * <code>X.test()</code> would collect the methods * <code>A.foo()</code>, <code>B.foo()</code>, and <code>A.bar()</code>. * </p> * * @param enclosingElement the method, type, or compilation unit to be searched in * @param requestor a callback object to which each match is reported * @param monitor the progress monitor used to report progress * @exception ModelException if the search failed. Reasons include: * <ul> * <li>the element doesn't exist</li> * <li>the buildpath is incorrectly set</li> * </ul> * */ public void searchDeclarationsOfSentMessages(IModelElement enclosingElement, SearchRequestor requestor, IProgressMonitor monitor) throws ModelException { this.basicEngine.searchDeclarationsOfSentMessages(enclosingElement, requestor, monitor); } public static ISourceModule[] searchMixinSources(String key, IDLTKLanguageToolkit toolkit ) { final IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(toolkit); // Index requestor final HandleFactory factory = new HandleFactory(); final List modules = new ArrayList(); IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { if( documentPath.startsWith(SPECIAL_MIXIN)) { documentPath = documentPath.substring(SPECIAL_MIXIN.length()); } String s = IBuildpathEntry.BUILDIN_EXTERNAL_ENTRY.toString(); - if( documentPath.contains(s)) { + if( documentPath.indexOf(s) != -1) { documentPath = documentPath.substring(documentPath.indexOf(s)); } Openable createOpenable = factory.createOpenable(documentPath, scope); if( createOpenable instanceof ISourceModule ) { modules.add(createOpenable); } return true; } }; IndexManager indexManager = ModelManager.getModelManager().getIndexManager(); MixinPattern pattern = new MixinPattern(key.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_PATTERN_MATCH); // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob( pattern, SearchEngine.getDefaultSearchParticipant(), // Script search only scope, searchRequestor), IDLTKSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); return (ISourceModule[])modules.toArray(new ISourceModule[modules.size()]); } public static String[] searchMixinPatterns(String key, IDLTKLanguageToolkit toolkit) { final IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(toolkit); // Index requestor final List result = new ArrayList(); IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { String val = new String( indexRecord.getIndexKey() ); if( !result.contains(val)) { result.add(val); } return true; } }; IndexManager indexManager = ModelManager.getModelManager().getIndexManager(); int flags = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; if (key.indexOf('*') != -1 || key.indexOf('?') != -1) flags |= SearchPattern.R_PATTERN_MATCH; MixinPattern pattern = new MixinPattern(key.toCharArray(), flags); // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob( pattern, SearchEngine.getDefaultSearchParticipant(), // Script search only scope, searchRequestor), IDLTKSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); return (String[])result.toArray(new String[result.size()]); } }
true
true
public static ISourceModule[] searchMixinSources(String key, IDLTKLanguageToolkit toolkit ) { final IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(toolkit); // Index requestor final HandleFactory factory = new HandleFactory(); final List modules = new ArrayList(); IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { if( documentPath.startsWith(SPECIAL_MIXIN)) { documentPath = documentPath.substring(SPECIAL_MIXIN.length()); } String s = IBuildpathEntry.BUILDIN_EXTERNAL_ENTRY.toString(); if( documentPath.contains(s)) { documentPath = documentPath.substring(documentPath.indexOf(s)); } Openable createOpenable = factory.createOpenable(documentPath, scope); if( createOpenable instanceof ISourceModule ) { modules.add(createOpenable); } return true; } }; IndexManager indexManager = ModelManager.getModelManager().getIndexManager(); MixinPattern pattern = new MixinPattern(key.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_PATTERN_MATCH); // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob( pattern, SearchEngine.getDefaultSearchParticipant(), // Script search only scope, searchRequestor), IDLTKSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); return (ISourceModule[])modules.toArray(new ISourceModule[modules.size()]); }
public static ISourceModule[] searchMixinSources(String key, IDLTKLanguageToolkit toolkit ) { final IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(toolkit); // Index requestor final HandleFactory factory = new HandleFactory(); final List modules = new ArrayList(); IndexQueryRequestor searchRequestor = new IndexQueryRequestor(){ public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { if( documentPath.startsWith(SPECIAL_MIXIN)) { documentPath = documentPath.substring(SPECIAL_MIXIN.length()); } String s = IBuildpathEntry.BUILDIN_EXTERNAL_ENTRY.toString(); if( documentPath.indexOf(s) != -1) { documentPath = documentPath.substring(documentPath.indexOf(s)); } Openable createOpenable = factory.createOpenable(documentPath, scope); if( createOpenable instanceof ISourceModule ) { modules.add(createOpenable); } return true; } }; IndexManager indexManager = ModelManager.getModelManager().getIndexManager(); MixinPattern pattern = new MixinPattern(key.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE | SearchPattern.R_PATTERN_MATCH); // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob( pattern, SearchEngine.getDefaultSearchParticipant(), // Script search only scope, searchRequestor), IDLTKSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); return (ISourceModule[])modules.toArray(new ISourceModule[modules.size()]); }
diff --git a/v9t9/v9t9-java/v9t9-gui/src/v9t9/gui/client/swt/svg/SVGImageProvider.java b/v9t9/v9t9-java/v9t9-gui/src/v9t9/gui/client/swt/svg/SVGImageProvider.java index 8bfbab83e..47ba22ce4 100644 --- a/v9t9/v9t9-java/v9t9-gui/src/v9t9/gui/client/swt/svg/SVGImageProvider.java +++ b/v9t9/v9t9-java/v9t9-gui/src/v9t9/gui/client/swt/svg/SVGImageProvider.java @@ -1,157 +1,157 @@ /* SVGImageProvider.java (c) 2010-2012 Edward Swartz 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 v9t9.gui.client.swt.svg; import java.util.TreeMap; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import v9t9.gui.client.swt.bars.IImageCanvas; import v9t9.gui.client.swt.bars.MultiImageSizeProvider; import v9t9.gui.client.swt.imageimport.ImageUtils; import ejs.base.utils.Pair; /** * @author ejs * */ public class SVGImageProvider extends MultiImageSizeProvider { private static boolean DEBUG = false; private final ISVGLoader svgLoader; private Thread loadIconThread; private Point desiredSize; private Image scaledImage; private boolean svgFailed; private IImageCanvas imageCanvas; /** * @param iconMap */ public SVGImageProvider(TreeMap<Integer, Image> iconMap, ISVGLoader svgIcon) { super(iconMap); this.svgLoader = svgIcon; } public void setImageCanvas(IImageCanvas imageCanvas) { this.imageCanvas = imageCanvas; } /* (non-Javadoc) * @see v9t9.emulator.clients.builtin.swt.MultiImageSizeProvider#getImage(org.eclipse.swt.graphics.Point) */ @Override public synchronized Pair<Double, Image> getImage(final int sx, final int sy) { boolean recreate = false; final Point size = new Point(sx, sy); if (scaledImage == null || !size.equals(desiredSize)) { if (loadIconThread == null || !svgLoader.isSlow()) { recreate = true; } } if (!svgFailed && recreate) { desiredSize = size; if (scaledImage != null) scaledImage.dispose(); scaledImage = null; if (svgLoader.isSlow()) { loadIconThread = new Thread("Scaling icon") { public void run() { fetchImage(desiredSize); loadIconThread = null; } }; loadIconThread.start(); } else { fetchImage(size); } } if (scaledImage == null) { return super.getImage(sx, sy); } else { int min = iconMap.values().iterator().next().getBounds().width; double ratio = (double) scaledImage.getBounds().width / min; if (DEBUG) System.out.println("Using svg image " + scaledImage.getBounds() + " at " +ratio); return new Pair<Double, Image>(ratio, scaledImage); } } /** * @param size */ protected void fetchImage(final Point size) { if (!svgLoader.isValid()) { svgFailed = true; return; } synchronized (this) { while (!svgLoader.isLoaded()) { try { wait(100); } catch (InterruptedException e) { svgFailed = true; return; } } //int min = iconMap.values().iterator().next().getBounds().width; final Composite composite = imageCanvas.getComposite(); Point scaledSize = new Point(size.x, size.y); Point svgSize = svgLoader.getSize(); scaledSize.y = size.y * svgSize.y / svgSize.x; long start = System.currentTimeMillis(); final ImageData scaledImageData; try { scaledImageData = ImageUtils.convertAwtImageData(svgLoader.getImageData(scaledSize)); } catch (SVGException e) { e.printStackTrace(); svgFailed = true; return; } long end = System.currentTimeMillis(); if (DEBUG) System.out.println("Loaded " + svgLoader.getURI() + " @ " + scaledSize + ": " + (end - start) + " ms"); svgFailed = false; if (composite != null && !composite.isDisposed() && scaledImageData != null) { - composite.getDisplay().syncExec(new Runnable() { + composite.getDisplay().asyncExec(new Runnable() { public void run() { if (composite.isDisposed()) return; scaledImage = new Image(composite.getDisplay(), scaledImageData); if (DEBUG) System.out.println("Got image " + scaledImage.getBounds()); imageCanvas.redrawAll(); } }); } } } }
true
true
protected void fetchImage(final Point size) { if (!svgLoader.isValid()) { svgFailed = true; return; } synchronized (this) { while (!svgLoader.isLoaded()) { try { wait(100); } catch (InterruptedException e) { svgFailed = true; return; } } //int min = iconMap.values().iterator().next().getBounds().width; final Composite composite = imageCanvas.getComposite(); Point scaledSize = new Point(size.x, size.y); Point svgSize = svgLoader.getSize(); scaledSize.y = size.y * svgSize.y / svgSize.x; long start = System.currentTimeMillis(); final ImageData scaledImageData; try { scaledImageData = ImageUtils.convertAwtImageData(svgLoader.getImageData(scaledSize)); } catch (SVGException e) { e.printStackTrace(); svgFailed = true; return; } long end = System.currentTimeMillis(); if (DEBUG) System.out.println("Loaded " + svgLoader.getURI() + " @ " + scaledSize + ": " + (end - start) + " ms"); svgFailed = false; if (composite != null && !composite.isDisposed() && scaledImageData != null) { composite.getDisplay().syncExec(new Runnable() { public void run() { if (composite.isDisposed()) return; scaledImage = new Image(composite.getDisplay(), scaledImageData); if (DEBUG) System.out.println("Got image " + scaledImage.getBounds()); imageCanvas.redrawAll(); } }); } } }
protected void fetchImage(final Point size) { if (!svgLoader.isValid()) { svgFailed = true; return; } synchronized (this) { while (!svgLoader.isLoaded()) { try { wait(100); } catch (InterruptedException e) { svgFailed = true; return; } } //int min = iconMap.values().iterator().next().getBounds().width; final Composite composite = imageCanvas.getComposite(); Point scaledSize = new Point(size.x, size.y); Point svgSize = svgLoader.getSize(); scaledSize.y = size.y * svgSize.y / svgSize.x; long start = System.currentTimeMillis(); final ImageData scaledImageData; try { scaledImageData = ImageUtils.convertAwtImageData(svgLoader.getImageData(scaledSize)); } catch (SVGException e) { e.printStackTrace(); svgFailed = true; return; } long end = System.currentTimeMillis(); if (DEBUG) System.out.println("Loaded " + svgLoader.getURI() + " @ " + scaledSize + ": " + (end - start) + " ms"); svgFailed = false; if (composite != null && !composite.isDisposed() && scaledImageData != null) { composite.getDisplay().asyncExec(new Runnable() { public void run() { if (composite.isDisposed()) return; scaledImage = new Image(composite.getDisplay(), scaledImageData); if (DEBUG) System.out.println("Got image " + scaledImage.getBounds()); imageCanvas.redrawAll(); } }); } } }
diff --git a/src/cc/game/SteampunkZelda/screen/gamescreen/GameScreen.java b/src/cc/game/SteampunkZelda/screen/gamescreen/GameScreen.java index dd743ac..742138a 100644 --- a/src/cc/game/SteampunkZelda/screen/gamescreen/GameScreen.java +++ b/src/cc/game/SteampunkZelda/screen/gamescreen/GameScreen.java @@ -1,73 +1,75 @@ package cc.game.SteampunkZelda.screen.gamescreen; import cc.game.SteampunkZelda.SteampunkZelda; import cc.game.SteampunkZelda.screen.Screen; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import java.io.*; import java.util.ArrayList; /** * Created with IntelliJ IDEA. * User: calv * Date: 30/03/13 * Time: 14:29 * To change this template use File | Settings | File Templates. */ public abstract class GameScreen extends Screen { private Image bgImage; protected int levelID; protected ArrayList<int[]> collisions; protected GameScreen(SteampunkZelda game, int levelID, int MAP_WIDTH, int MAP_HEIGHT) { super(game, MAP_WIDTH, MAP_HEIGHT); this.levelID = levelID; try { this.bgImage = new Image("res/screens/gamescreens/" + this.levelID + ".png"); } catch (SlickException e) { System.err.println("Couldn't load background image."); e.printStackTrace(); } this.collisions = new ArrayList<int[]>(); loadCollisions(this.levelID); } private void loadCollisions(int levelID) { try { FileInputStream fis = new FileInputStream("res/collisions/" + levelID + ".csv"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { if (line.isEmpty() || line.startsWith("#")) { continue; } else { int[] pos = new int[4]; String[] split = line.split(","); for (int i = 0; i < split.length; i++) { pos[i] = Integer.parseInt(split[i]); } this.collisions.add(pos); } } } catch (FileNotFoundException e) { System.err.println("Couldn't load collision file!"); + System.err.println("Did you delete it, or did I screw up? Who knows? Send me the details!"); e.printStackTrace(); } catch (IOException e) { System.err.println("Couldn't read the collision file!"); + System.err.println("Did you somehow change the permissions on the file? You naughty male/female/other."); e.printStackTrace(); } } @Override public void update(GameContainer gameContainer, int deltaTime) throws SlickException { } @Override public void render(GameContainer paramGameContainer) { bgImage.draw(); } }
false
true
private void loadCollisions(int levelID) { try { FileInputStream fis = new FileInputStream("res/collisions/" + levelID + ".csv"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { if (line.isEmpty() || line.startsWith("#")) { continue; } else { int[] pos = new int[4]; String[] split = line.split(","); for (int i = 0; i < split.length; i++) { pos[i] = Integer.parseInt(split[i]); } this.collisions.add(pos); } } } catch (FileNotFoundException e) { System.err.println("Couldn't load collision file!"); e.printStackTrace(); } catch (IOException e) { System.err.println("Couldn't read the collision file!"); e.printStackTrace(); } }
private void loadCollisions(int levelID) { try { FileInputStream fis = new FileInputStream("res/collisions/" + levelID + ".csv"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String line; while ((line = br.readLine()) != null) { if (line.isEmpty() || line.startsWith("#")) { continue; } else { int[] pos = new int[4]; String[] split = line.split(","); for (int i = 0; i < split.length; i++) { pos[i] = Integer.parseInt(split[i]); } this.collisions.add(pos); } } } catch (FileNotFoundException e) { System.err.println("Couldn't load collision file!"); System.err.println("Did you delete it, or did I screw up? Who knows? Send me the details!"); e.printStackTrace(); } catch (IOException e) { System.err.println("Couldn't read the collision file!"); System.err.println("Did you somehow change the permissions on the file? You naughty male/female/other."); e.printStackTrace(); } }
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java index 368be52fe..7262d699f 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CommitCommentArea.java @@ -1,633 +1,632 @@ /******************************************************************************* * 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 * Sebastian Davids - bug 57208 * Maik Schreiber - bug 102461 * Eugene Kuleshov ([email protected]) - Bug 112742 [Wizards] Add spell check to commit dialog * Brock Janiczak <[email protected]> - Bug 179183 Use spelling support from JFace in CVS commit dialog *******************************************************************************/ package org.eclipse.team.internal.ccvs.ui; import java.util.*; import org.eclipse.core.resources.IProject; import org.eclipse.jface.action.*; import org.eclipse.jface.commands.ActionHandler; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.*; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.source.*; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.internal.ccvs.core.*; import org.eclipse.team.internal.ccvs.core.util.Util; import org.eclipse.team.internal.ui.SWTUtils; import org.eclipse.team.internal.ui.dialogs.DialogArea; import org.eclipse.ui.ActiveShellExpression; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferencesUtil; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.editors.text.TextSourceViewerConfiguration; import org.eclipse.ui.handlers.IHandlerActivation; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.texteditor.*; /** * This area provides the widgets for providing the CVS commit comment */ public class CommitCommentArea extends DialogArea { private class TextBox implements ModifyListener, TraverseListener, FocusListener, Observer { private final StyledText fTextField; // updated only by modify events private final String fMessage; private String fText; public TextBox(Composite composite, String message, String initialText) { fMessage= message; fText= initialText; AnnotationModel annotationModel = new AnnotationModel(); IAnnotationAccess annotationAccess = new DefaultMarkerAnnotationAccess(); Composite cc = new Composite(composite, SWT.BORDER); cc.setLayout(new FillLayout()); cc.setLayoutData(new GridData(GridData.FILL_BOTH)); final SourceViewer sourceViewer = new SourceViewer(cc, null, null, true, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP); fTextField = sourceViewer.getTextWidget(); fTextField.setIndent(2); final SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(sourceViewer, null, annotationAccess, EditorsUI.getSharedTextColors()); - support.setMarginPainterPreferenceKeys(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); Iterator e= new MarkerAnnotationPreferences().getAnnotationPreferences().iterator(); while (e.hasNext()) support.setAnnotationPreference((AnnotationPreference) e.next()); support.install(EditorsUI.getPreferenceStore()); final IHandlerService handlerService= (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class); final IHandlerActivation handlerActivation= installQuickFixActionHandler(handlerService, sourceViewer); final TextViewerAction cutAction = new TextViewerAction(sourceViewer, ITextOperationTarget.CUT); cutAction.setText(CVSUIMessages.CommitCommentArea_7); cutAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT); final TextViewerAction copyAction = new TextViewerAction(sourceViewer, ITextOperationTarget.COPY); copyAction.setText(CVSUIMessages.CommitCommentArea_8); copyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY); final TextViewerAction pasteAction = new TextViewerAction(sourceViewer, ITextOperationTarget.PASTE); pasteAction.setText(CVSUIMessages.CommitCommentArea_9); pasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE); final TextViewerAction selectAllAction = new TextViewerAction(sourceViewer, ITextOperationTarget.SELECT_ALL); selectAllAction.setText(CVSUIMessages.CommitCommentArea_10); selectAllAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL); MenuManager contextMenu = new MenuManager(); contextMenu.add(cutAction); contextMenu.add(copyAction); contextMenu.add(pasteAction); contextMenu.add(selectAllAction); contextMenu.add(new Separator()); final SubMenuManager quickFixMenu = new SubMenuManager(contextMenu); quickFixMenu.setVisible(true); quickFixMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { quickFixMenu.removeAll(); IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); Iterator annotationIterator = annotationModel.getAnnotationIterator(); while (annotationIterator.hasNext()) { Annotation annotation = (Annotation) annotationIterator.next(); if (!annotation.isMarkedDeleted() && includes(annotationModel.getPosition(annotation), sourceViewer.getTextWidget().getCaretOffset()) && sourceViewer.getQuickAssistAssistant().canFix(annotation)) { ICompletionProposal[] computeQuickAssistProposals = sourceViewer.getQuickAssistAssistant().getQuickAssistProcessor().computeQuickAssistProposals(sourceViewer.getQuickAssistInvocationContext()); for (int i = 0; i < computeQuickAssistProposals.length; i++) { final ICompletionProposal proposal = computeQuickAssistProposals[i]; quickFixMenu.add(new Action(proposal.getDisplayString()) { /* (non-Javadoc) * @see org.eclipse.jface.action.Action#run() */ public void run() { proposal.apply(sourceViewer.getDocument()); } /* (non-Javadoc) * @see org.eclipse.jface.action.Action#getImageDescriptor() */ public ImageDescriptor getImageDescriptor() { if (proposal.getImage() != null) { return ImageDescriptor.createFromImage(proposal.getImage()); } return null; } }); } } } } }); fTextField.addFocusListener(new FocusListener() { private IHandlerActivation cutHandlerActivation; private IHandlerActivation copyHandlerActivation; private IHandlerActivation pasteHandlerActivation; private IHandlerActivation selectAllHandlerActivation; public void focusGained(FocusEvent e) { cutAction.update(); copyAction.update(); IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); this.cutHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.CUT, new ActionHandler(cutAction), new ActiveShellExpression(getComposite().getShell())); this.copyHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.COPY, new ActionHandler(copyAction), new ActiveShellExpression(getComposite().getShell())); this.pasteHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.PASTE, new ActionHandler(pasteAction), new ActiveShellExpression(getComposite().getShell())); this.selectAllHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.SELECT_ALL, new ActionHandler(selectAllAction), new ActiveShellExpression(getComposite().getShell())); } /* (non-Javadoc) * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent e) { IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (cutHandlerActivation != null) { service.deactivateHandler(cutHandlerActivation); } if (copyHandlerActivation != null) { service.deactivateHandler(copyHandlerActivation); } if (pasteHandlerActivation != null) { service.deactivateHandler(pasteHandlerActivation); } if (selectAllHandlerActivation != null) { service.deactivateHandler(selectAllHandlerActivation); } } }); fTextField.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { cutAction.update(); copyAction.update(); } }); sourceViewer.getTextWidget().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { support.uninstall(); handlerService.deactivateHandler(handlerActivation); } }); Document document = new Document(initialText); // NOTE: Configuration must be applied before the document is set in order for // Hyperlink coloring to work. (Presenter needs document object up front) sourceViewer.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore())); sourceViewer.setDocument(document, annotationModel); fTextField.addTraverseListener(this); fTextField.addModifyListener(this); fTextField.addFocusListener(this); fTextField.setMenu(contextMenu.createContextMenu(fTextField)); } protected boolean includes(Position position, int caretOffset) { return position.includes(caretOffset) || (position.offset + position.length) == caretOffset; } /** * Installs the quick fix action handler * and returns the handler activation. * * @param handlerService the handler service * @param sourceViewer the source viewer * @return the handler activation * @since 3.4 */ private IHandlerActivation installQuickFixActionHandler(IHandlerService handlerService, SourceViewer sourceViewer) { return handlerService.activateHandler( ITextEditorActionDefinitionIds.QUICK_ASSIST, createQuickFixActionHandler(sourceViewer), new ActiveShellExpression(sourceViewer.getTextWidget().getShell())); } /** * Creates and returns a quick fix action handler. * * @param textOperationTarget the target for text operations * @since 3.4 */ private ActionHandler createQuickFixActionHandler(final ITextOperationTarget textOperationTarget) { Action quickFixAction= new Action() { /* (non-Javadoc) * @see org.eclipse.jface.action.Action#run() */ public void run() { textOperationTarget.doOperation(ISourceViewer.QUICK_ASSIST); } }; quickFixAction.setActionDefinitionId(ITextEditorActionDefinitionIds.QUICK_ASSIST); return new ActionHandler(quickFixAction); } public void modifyText(ModifyEvent e) { final String old = fText; fText = fTextField.getText(); firePropertyChangeChange(COMMENT_MODIFIED, old, fText); } public void keyTraversed(TraverseEvent e) { if (e.detail == SWT.TRAVERSE_RETURN && (e.stateMask & SWT.CTRL) != 0) { e.doit = false; firePropertyChangeChange(OK_REQUESTED, null, null); } } public void focusGained(FocusEvent e) { if (fText.length() > 0) return; fTextField.removeModifyListener(this); try { fTextField.setText(fText); } finally { fTextField.addModifyListener(this); } } public void focusLost(FocusEvent e) { if (fText.length() > 0) return; fTextField.removeModifyListener(this); try { fTextField.setText(fMessage); fTextField.selectAll(); } finally { fTextField.addModifyListener(this); } } public void setEnabled(boolean enabled) { fTextField.setEnabled(enabled); } public void update(Observable o, Object arg) { if (arg instanceof String) { setText((String)arg); // triggers a modify event } } public String getText() { return fText; } private void setText(String text) { if (text.length() == 0) { fTextField.setText(fMessage); fTextField.selectAll(); } else fTextField.setText(text); } public void setFocus() { fTextField.setFocus(); } } private static class ComboBox extends Observable implements SelectionListener, FocusListener { private final String fMessage; private final String [] fComments; private String[] fCommentTemplates; private final Combo fCombo; public ComboBox(Composite composite, String message, String [] options, String[] commentTemplates) { fMessage= message; fComments= options; fCommentTemplates = commentTemplates; fCombo = new Combo(composite, SWT.READ_ONLY); fCombo.setLayoutData(SWTUtils.createHFillGridData()); fCombo.setVisibleItemCount(20); // populate the previous comment list populateList(); // We don't want to have an initial selection // (see bug 32078: http://bugs.eclipse.org/bugs/show_bug.cgi?id=32078) fCombo.addFocusListener(this); fCombo.addSelectionListener(this); } private void populateList() { fCombo.removeAll(); fCombo.add(fMessage); for (int i = 0; i < fCommentTemplates.length; i++) { fCombo.add(CVSUIMessages.CommitCommentArea_6 + ": " + //$NON-NLS-1$ Util.flattenText(fCommentTemplates[i])); } for (int i = 0; i < fComments.length; i++) { fCombo.add(Util.flattenText(fComments[i])); } fCombo.setText(fMessage); } public void widgetSelected(SelectionEvent e) { int index = fCombo.getSelectionIndex(); if (index > 0) { index--; setChanged(); // map from combo box index to array index String message; if (index < fCommentTemplates.length) { message = fCommentTemplates[index]; } else { message = fComments[index - fCommentTemplates.length]; } notifyObservers(message); } } public void widgetDefaultSelected(SelectionEvent e) { } public void focusGained(FocusEvent e) { } /* (non-Javadoc) * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent e) { fCombo.removeSelectionListener(this); try { fCombo.setText(fMessage); } finally { fCombo.addSelectionListener(this); } } public void setEnabled(boolean enabled) { fCombo.setEnabled(enabled); } void setCommentTemplates(String[] templates) { fCommentTemplates = templates; populateList(); } } private static final String EMPTY_MESSAGE= CVSUIMessages.CommitCommentArea_0; private static final String COMBO_MESSAGE= CVSUIMessages.CommitCommentArea_1; private static final String CONFIGURE_TEMPLATES_MESSAGE= CVSUIMessages.CommitCommentArea_5; public static final String OK_REQUESTED = "OkRequested";//$NON-NLS-1$ public static final String COMMENT_MODIFIED = "CommentModified";//$NON-NLS-1$ private TextBox fTextBox; private ComboBox fComboBox; private IProject fMainProject; private String fProposedComment; private Composite fComposite; /** * @see org.eclipse.team.internal.ccvs.ui.DialogArea#createArea(org.eclipse.swt.widgets.Composite) */ public void createArea(Composite parent) { Dialog.applyDialogFont(parent); initializeDialogUnits(parent); fComposite = createGrabbingComposite(parent, 1); initializeDialogUnits(fComposite); fTextBox= new TextBox(fComposite, EMPTY_MESSAGE, getInitialComment()); final String [] comments = CVSUIPlugin.getPlugin().getRepositoryManager().getPreviousComments(); final String[] commentTemplates = CVSUIPlugin.getPlugin().getRepositoryManager().getCommentTemplates(); fComboBox= new ComboBox(fComposite, COMBO_MESSAGE, comments, commentTemplates); Link templatesPrefsLink = new Link(fComposite, 0); templatesPrefsLink.setText("<a href=\"configureTemplates\">" + //$NON-NLS-1$ CONFIGURE_TEMPLATES_MESSAGE + "</a>"); //$NON-NLS-1$ templatesPrefsLink.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { openCommentTemplatesPreferencePage(); } public void widgetSelected(SelectionEvent e) { openCommentTemplatesPreferencePage(); } }); fComboBox.addObserver(fTextBox); } void openCommentTemplatesPreferencePage() { PreferencesUtil.createPreferenceDialogOn( null, "org.eclipse.team.cvs.ui.CommentTemplatesPreferences", //$NON-NLS-1$ new String[] { "org.eclipse.team.cvs.ui.CommentTemplatesPreferences" }, //$NON-NLS-1$ null).open(); fComboBox.setCommentTemplates( CVSUIPlugin.getPlugin().getRepositoryManager().getCommentTemplates()); } public String getComment(boolean save) { final String comment= fTextBox.getText(); if (comment == null) return ""; //$NON-NLS-1$ final String stripped= strip(comment); if (save && comment.length() > 0) CVSUIPlugin.getPlugin().getRepositoryManager().addComment(comment); return stripped; } /** * Calculates a shortened form of the commit message for use as a commit set * title * @return The first line or sentence of the commit message. The commit template * text will be removed, as will leading and trailing whitespace. */ public String getFirstLineOfComment() { String comment= fTextBox.getText(); if (comment == null) { comment= ""; //$NON-NLS-1$ } comment= strip(comment); int cr= comment.indexOf('\r'); if (cr != -1) { comment= comment.substring(0, cr); } int lf= comment.indexOf('\n'); if (lf != -1) { comment= comment.substring(0, lf); } int dot= comment.indexOf('.'); if (dot != -1) { comment= comment.substring(0, dot); } comment= comment.trim(); return comment; } public String getCommentWithPrompt(Shell shell) { final String comment= getComment(false); if (comment.length() == 0) { final IPreferenceStore store= CVSUIPlugin.getPlugin().getPreferenceStore(); final String value= store.getString(ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); if (MessageDialogWithToggle.NEVER.equals(value)) return null; if (MessageDialogWithToggle.PROMPT.equals(value)) { final String title= CVSUIMessages.CommitCommentArea_2; final String message= CVSUIMessages.CommitCommentArea_3; final String toggleMessage= CVSUIMessages.CommitCommentArea_4; final MessageDialogWithToggle dialog= MessageDialogWithToggle.openYesNoQuestion(shell, title, message, toggleMessage, false, store, ICVSUIConstants.PREF_ALLOW_EMPTY_COMMIT_COMMENTS); if (dialog.getReturnCode() != IDialogConstants.YES_ID) { fTextBox.setFocus(); return null; } } } return getComment(true); } public void setProject(IProject iProject) { this.fMainProject = iProject; } public void setFocus() { if (fTextBox != null) { fTextBox.setFocus(); } } public void setProposedComment(String proposedComment) { if (proposedComment == null || proposedComment.length() == 0) { this.fProposedComment = null; } else { this.fProposedComment = proposedComment; } } public boolean hasCommitTemplate() { try { String commitTemplate = getCommitTemplate(); return commitTemplate != null && commitTemplate.length() > 0; } catch (CVSException e) { CVSUIPlugin.log(e); return false; } } public void setEnabled(boolean enabled) { fTextBox.setEnabled(enabled); fComboBox.setEnabled(enabled); } public Composite getComposite() { return fComposite; } protected void firePropertyChangeChange(String property, Object oldValue, Object newValue) { super.firePropertyChangeChange(property, oldValue, newValue); } private String getInitialComment() { if (fProposedComment != null) return fProposedComment; try { return getCommitTemplate(); } catch (CVSException e) { CVSUIPlugin.log(e); return ""; //$NON-NLS-1$ } } private String strip(String comment) { // strip template from the comment entered try { final String commitTemplate = getCommitTemplate(); if (comment.startsWith(commitTemplate)) { return comment.substring(commitTemplate.length()); } else if (comment.endsWith(commitTemplate)) { return comment.substring(0, comment.length() - commitTemplate.length()); } } catch (CVSException e) { // we couldn't get the commit template. Log the error and continue CVSUIPlugin.log(e); } return comment; } private CVSTeamProvider getProvider() { if (fMainProject == null) return null; return (CVSTeamProvider) RepositoryProvider.getProvider(fMainProject, CVSProviderPlugin.getTypeId()); } private String getCommitTemplate() throws CVSException { CVSTeamProvider provider = getProvider(); if (provider == null) return ""; //$NON-NLS-1$ final String template = provider.getCommitTemplate(); return template != null ? template : ""; //$NON-NLS-1$ } }
true
true
public TextBox(Composite composite, String message, String initialText) { fMessage= message; fText= initialText; AnnotationModel annotationModel = new AnnotationModel(); IAnnotationAccess annotationAccess = new DefaultMarkerAnnotationAccess(); Composite cc = new Composite(composite, SWT.BORDER); cc.setLayout(new FillLayout()); cc.setLayoutData(new GridData(GridData.FILL_BOTH)); final SourceViewer sourceViewer = new SourceViewer(cc, null, null, true, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP); fTextField = sourceViewer.getTextWidget(); fTextField.setIndent(2); final SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(sourceViewer, null, annotationAccess, EditorsUI.getSharedTextColors()); support.setMarginPainterPreferenceKeys(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN); Iterator e= new MarkerAnnotationPreferences().getAnnotationPreferences().iterator(); while (e.hasNext()) support.setAnnotationPreference((AnnotationPreference) e.next()); support.install(EditorsUI.getPreferenceStore()); final IHandlerService handlerService= (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class); final IHandlerActivation handlerActivation= installQuickFixActionHandler(handlerService, sourceViewer); final TextViewerAction cutAction = new TextViewerAction(sourceViewer, ITextOperationTarget.CUT); cutAction.setText(CVSUIMessages.CommitCommentArea_7); cutAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT); final TextViewerAction copyAction = new TextViewerAction(sourceViewer, ITextOperationTarget.COPY); copyAction.setText(CVSUIMessages.CommitCommentArea_8); copyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY); final TextViewerAction pasteAction = new TextViewerAction(sourceViewer, ITextOperationTarget.PASTE); pasteAction.setText(CVSUIMessages.CommitCommentArea_9); pasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE); final TextViewerAction selectAllAction = new TextViewerAction(sourceViewer, ITextOperationTarget.SELECT_ALL); selectAllAction.setText(CVSUIMessages.CommitCommentArea_10); selectAllAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL); MenuManager contextMenu = new MenuManager(); contextMenu.add(cutAction); contextMenu.add(copyAction); contextMenu.add(pasteAction); contextMenu.add(selectAllAction); contextMenu.add(new Separator()); final SubMenuManager quickFixMenu = new SubMenuManager(contextMenu); quickFixMenu.setVisible(true); quickFixMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { quickFixMenu.removeAll(); IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); Iterator annotationIterator = annotationModel.getAnnotationIterator(); while (annotationIterator.hasNext()) { Annotation annotation = (Annotation) annotationIterator.next(); if (!annotation.isMarkedDeleted() && includes(annotationModel.getPosition(annotation), sourceViewer.getTextWidget().getCaretOffset()) && sourceViewer.getQuickAssistAssistant().canFix(annotation)) { ICompletionProposal[] computeQuickAssistProposals = sourceViewer.getQuickAssistAssistant().getQuickAssistProcessor().computeQuickAssistProposals(sourceViewer.getQuickAssistInvocationContext()); for (int i = 0; i < computeQuickAssistProposals.length; i++) { final ICompletionProposal proposal = computeQuickAssistProposals[i]; quickFixMenu.add(new Action(proposal.getDisplayString()) { /* (non-Javadoc) * @see org.eclipse.jface.action.Action#run() */ public void run() { proposal.apply(sourceViewer.getDocument()); } /* (non-Javadoc) * @see org.eclipse.jface.action.Action#getImageDescriptor() */ public ImageDescriptor getImageDescriptor() { if (proposal.getImage() != null) { return ImageDescriptor.createFromImage(proposal.getImage()); } return null; } }); } } } } }); fTextField.addFocusListener(new FocusListener() { private IHandlerActivation cutHandlerActivation; private IHandlerActivation copyHandlerActivation; private IHandlerActivation pasteHandlerActivation; private IHandlerActivation selectAllHandlerActivation; public void focusGained(FocusEvent e) { cutAction.update(); copyAction.update(); IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); this.cutHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.CUT, new ActionHandler(cutAction), new ActiveShellExpression(getComposite().getShell())); this.copyHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.COPY, new ActionHandler(copyAction), new ActiveShellExpression(getComposite().getShell())); this.pasteHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.PASTE, new ActionHandler(pasteAction), new ActiveShellExpression(getComposite().getShell())); this.selectAllHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.SELECT_ALL, new ActionHandler(selectAllAction), new ActiveShellExpression(getComposite().getShell())); } /* (non-Javadoc) * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent e) { IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (cutHandlerActivation != null) { service.deactivateHandler(cutHandlerActivation); } if (copyHandlerActivation != null) { service.deactivateHandler(copyHandlerActivation); } if (pasteHandlerActivation != null) { service.deactivateHandler(pasteHandlerActivation); } if (selectAllHandlerActivation != null) { service.deactivateHandler(selectAllHandlerActivation); } } }); fTextField.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { cutAction.update(); copyAction.update(); } }); sourceViewer.getTextWidget().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { support.uninstall(); handlerService.deactivateHandler(handlerActivation); } }); Document document = new Document(initialText); // NOTE: Configuration must be applied before the document is set in order for // Hyperlink coloring to work. (Presenter needs document object up front) sourceViewer.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore())); sourceViewer.setDocument(document, annotationModel); fTextField.addTraverseListener(this); fTextField.addModifyListener(this); fTextField.addFocusListener(this); fTextField.setMenu(contextMenu.createContextMenu(fTextField)); }
public TextBox(Composite composite, String message, String initialText) { fMessage= message; fText= initialText; AnnotationModel annotationModel = new AnnotationModel(); IAnnotationAccess annotationAccess = new DefaultMarkerAnnotationAccess(); Composite cc = new Composite(composite, SWT.BORDER); cc.setLayout(new FillLayout()); cc.setLayoutData(new GridData(GridData.FILL_BOTH)); final SourceViewer sourceViewer = new SourceViewer(cc, null, null, true, SWT.MULTI | SWT.V_SCROLL | SWT.WRAP); fTextField = sourceViewer.getTextWidget(); fTextField.setIndent(2); final SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(sourceViewer, null, annotationAccess, EditorsUI.getSharedTextColors()); Iterator e= new MarkerAnnotationPreferences().getAnnotationPreferences().iterator(); while (e.hasNext()) support.setAnnotationPreference((AnnotationPreference) e.next()); support.install(EditorsUI.getPreferenceStore()); final IHandlerService handlerService= (IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class); final IHandlerActivation handlerActivation= installQuickFixActionHandler(handlerService, sourceViewer); final TextViewerAction cutAction = new TextViewerAction(sourceViewer, ITextOperationTarget.CUT); cutAction.setText(CVSUIMessages.CommitCommentArea_7); cutAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT); final TextViewerAction copyAction = new TextViewerAction(sourceViewer, ITextOperationTarget.COPY); copyAction.setText(CVSUIMessages.CommitCommentArea_8); copyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY); final TextViewerAction pasteAction = new TextViewerAction(sourceViewer, ITextOperationTarget.PASTE); pasteAction.setText(CVSUIMessages.CommitCommentArea_9); pasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE); final TextViewerAction selectAllAction = new TextViewerAction(sourceViewer, ITextOperationTarget.SELECT_ALL); selectAllAction.setText(CVSUIMessages.CommitCommentArea_10); selectAllAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL); MenuManager contextMenu = new MenuManager(); contextMenu.add(cutAction); contextMenu.add(copyAction); contextMenu.add(pasteAction); contextMenu.add(selectAllAction); contextMenu.add(new Separator()); final SubMenuManager quickFixMenu = new SubMenuManager(contextMenu); quickFixMenu.setVisible(true); quickFixMenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { quickFixMenu.removeAll(); IAnnotationModel annotationModel = sourceViewer.getAnnotationModel(); Iterator annotationIterator = annotationModel.getAnnotationIterator(); while (annotationIterator.hasNext()) { Annotation annotation = (Annotation) annotationIterator.next(); if (!annotation.isMarkedDeleted() && includes(annotationModel.getPosition(annotation), sourceViewer.getTextWidget().getCaretOffset()) && sourceViewer.getQuickAssistAssistant().canFix(annotation)) { ICompletionProposal[] computeQuickAssistProposals = sourceViewer.getQuickAssistAssistant().getQuickAssistProcessor().computeQuickAssistProposals(sourceViewer.getQuickAssistInvocationContext()); for (int i = 0; i < computeQuickAssistProposals.length; i++) { final ICompletionProposal proposal = computeQuickAssistProposals[i]; quickFixMenu.add(new Action(proposal.getDisplayString()) { /* (non-Javadoc) * @see org.eclipse.jface.action.Action#run() */ public void run() { proposal.apply(sourceViewer.getDocument()); } /* (non-Javadoc) * @see org.eclipse.jface.action.Action#getImageDescriptor() */ public ImageDescriptor getImageDescriptor() { if (proposal.getImage() != null) { return ImageDescriptor.createFromImage(proposal.getImage()); } return null; } }); } } } } }); fTextField.addFocusListener(new FocusListener() { private IHandlerActivation cutHandlerActivation; private IHandlerActivation copyHandlerActivation; private IHandlerActivation pasteHandlerActivation; private IHandlerActivation selectAllHandlerActivation; public void focusGained(FocusEvent e) { cutAction.update(); copyAction.update(); IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); this.cutHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.CUT, new ActionHandler(cutAction), new ActiveShellExpression(getComposite().getShell())); this.copyHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.COPY, new ActionHandler(copyAction), new ActiveShellExpression(getComposite().getShell())); this.pasteHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.PASTE, new ActionHandler(pasteAction), new ActiveShellExpression(getComposite().getShell())); this.selectAllHandlerActivation = service.activateHandler(IWorkbenchActionDefinitionIds.SELECT_ALL, new ActionHandler(selectAllAction), new ActiveShellExpression(getComposite().getShell())); } /* (non-Javadoc) * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent e) { IHandlerService service = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class); if (cutHandlerActivation != null) { service.deactivateHandler(cutHandlerActivation); } if (copyHandlerActivation != null) { service.deactivateHandler(copyHandlerActivation); } if (pasteHandlerActivation != null) { service.deactivateHandler(pasteHandlerActivation); } if (selectAllHandlerActivation != null) { service.deactivateHandler(selectAllHandlerActivation); } } }); fTextField.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { cutAction.update(); copyAction.update(); } }); sourceViewer.getTextWidget().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { support.uninstall(); handlerService.deactivateHandler(handlerActivation); } }); Document document = new Document(initialText); // NOTE: Configuration must be applied before the document is set in order for // Hyperlink coloring to work. (Presenter needs document object up front) sourceViewer.configure(new TextSourceViewerConfiguration(EditorsUI.getPreferenceStore())); sourceViewer.setDocument(document, annotationModel); fTextField.addTraverseListener(this); fTextField.addModifyListener(this); fTextField.addFocusListener(this); fTextField.setMenu(contextMenu.createContextMenu(fTextField)); }
diff --git a/WEB-INF/src/org/cdlib/xtf/textIndexer/IndexMerge.java b/WEB-INF/src/org/cdlib/xtf/textIndexer/IndexMerge.java index 599d7a0a..a6e17f90 100644 --- a/WEB-INF/src/org/cdlib/xtf/textIndexer/IndexMerge.java +++ b/WEB-INF/src/org/cdlib/xtf/textIndexer/IndexMerge.java @@ -1,554 +1,554 @@ package org.cdlib.xtf.textIndexer; /** * Copyright (c) 2006, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the University of California 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. */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashSet; import java.util.Vector; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.cdlib.xtf.util.Path; import org.cdlib.xtf.util.Trace; /** * This class merges the contents of two or more XTF indexes, with certain * caveats. * * @author Martin Haye */ public class IndexMerge { ////////////////////////////////////////////////////////////////////////////// /** Main entry-point for the index merger. <br><br> * * This function takes the command line arguments passed and uses them to * find the indexes and merge them. */ public static void main( String[] args ) { Trace.info( "IndexMerge v. 1.8" ); try { IndexerConfig cfgInfo = new IndexerConfig(); XMLConfigParser cfgParser = new XMLConfigParser(); int startArg = 0; boolean showUsage = false; // Make sure the XTF_HOME environment variable is specified. cfgInfo.xtfHomePath = System.getProperty( "xtf.home" ); if( cfgInfo.xtfHomePath == null || cfgInfo.xtfHomePath.length() == 0 ) { Trace.error( "Error: xtf.home property not found" ); return; } cfgInfo.xtfHomePath = Path.normalizePath( cfgInfo.xtfHomePath ); if( !new File(cfgInfo.xtfHomePath).isDirectory() ) { Trace.error( "Error: xtf.home directory \"" + cfgInfo.xtfHomePath + "\" does not exist or cannot be read." ); return; } // Parse the command-line arguments. Vector mergePaths = new Vector(); HashSet pathSet = new HashSet(); - for(;;) { + while( !showUsage && startArg < args.length ) { // The minimum set of arguments consists of the name of an index // to read and an output index. That requires four arguments; if // we don't get that many, we will show the usage text and bail. // if( args.length < 4 ) showUsage = true; // We have enough arguments, so... else { // Read the command line arguments until we find what we // need to do some work, or until we run out. // int ret = cfgInfo.readCmdLine( args, startArg ); // If we didn't find enough command line arguments... if( ret == -1 ) { // And this is the first time we've visited the command // line arguments, avoid trying to doing work and just // display the usage text. Otherwise, we're done. // if( startArg == 0 ) showUsage = true; else break; } // if( ret == -1 ) // We did find enough command line arguments, so... // else { // Make sure the configuration path is absolute if( !(new File(cfgInfo.cfgFilePath).isAbsolute()) ) { cfgInfo.cfgFilePath = Path.resolveRelOrAbs( cfgInfo.xtfHomePath, cfgInfo.cfgFilePath); } // Get the configuration for the index specified by the // current command line arguments. // if( cfgParser.configure(cfgInfo) < 0 ) { Trace.error( "Error: index '" + cfgInfo.indexInfo.indexName + "' not found\n" ); System.exit( 1 ); } } // else( ret != -1 ) // Save the new start argument for the next time. startArg = ret; // The indexes should all be in different directories. IndexInfo idxInfo = cfgInfo.indexInfo; String idxPath = Path.resolveRelOrAbs(cfgInfo.xtfHomePath, idxInfo.indexPath); if( pathSet.contains(idxPath) ) { Trace.error( "Error: indexes to be merged must be in separate directories." ); System.exit( 1 ); } pathSet.add( idxPath ); // Save the index info for the merge mergePaths.add( idxPath ); } // else } // for // At least two indexes should be specified. if( mergePaths.size() < 2 ) showUsage = true; // Show usage message if any problems found. if( showUsage ) { // Do so... Trace.error( " usage: " ); Trace.tab(); Trace.error( "indexMerge {-config <configfile>} " + "-index <inputOutputIndex> " + "-index <inputIndex1> " + "{-index inputIndex2...}\n\n" ); Trace.untab(); // And then bail. System.exit( 1 ); } // if( showUsage ) // Make sure all the indexes exist, and that their parameters are at // least minimally compatible. // DirInfo[] dirInfos = new DirInfo[mergePaths.size()]; boolean createTarget = false; boolean done = false; for( int i = 0; i < mergePaths.size(); i++ ) { String idxPath = (String) mergePaths.get( i ); if( !IndexReader.indexExists(idxPath) ) { // It's okay if the target index doesn't exist. if( i == 0 ) { createTarget = true; dirInfos[0] = new DirInfo( idxPath, null ); continue; } throw new RuntimeException( "Error: Cannot locate index in directory '" + idxPath + "'" ); } Directory srcDir = FSDirectory.getDirectory( idxPath, false ); dirInfos[i] = readInfo( idxPath, srcDir ); // Check for parameter compatibility if( (i == 1 && !createTarget) || (i > 1) ) { if( dirInfos[i].chunkOverlap != dirInfos[i-1].chunkOverlap ) throw new RuntimeException( "Error: index parameters must match exactly (chunkOverlap mismatch detected)" ); if( dirInfos[i].chunkSize != dirInfos[i-1].chunkSize ) throw new RuntimeException( "Error: index parameters must match exactly (chunkSize mismatch detected)" ); if( !dirInfos[i].stopWords.equals(dirInfos[i-1].stopWords) ) throw new RuntimeException( "Error: index parameters must match exactly (stopWords mismatch detected)" ); if( !dirInfos[i].accentMapName.equals(dirInfos[i-1].accentMapName) ) throw new RuntimeException( "Error: index parameters must match exactly (accentMapName mismatch detected)" ); if( !dirInfos[i].pluralMapName.equals(dirInfos[i-1].pluralMapName) ) throw new RuntimeException( "Error: index parameters must match exactly (pluralMapName mismatch detected)" ); } } // for // Well, enough preparing. Let's do the job we were sent to do. doMerge( dirInfos, createTarget ); } // try // Log any unhandled exceptions. catch( Exception e ) { Trace.error( "*** Last Chance Exception: " + e.getClass() ); Trace.error( " With message: " + e.getMessage() ); Trace.error( "" ); e.printStackTrace( System.out ); System.exit( 1 ); } catch( Throwable t ) { Trace.error( "*** Last Chance Exception: " + t.getClass() ); Trace.error( " With message: " + t ); Trace.error( "" ); t.printStackTrace( System.out ); System.exit( 1 ); } // Exit successfully. System.exit( 0 ); } // main() ////////////////////////////////////////////////////////////////////////////// private static DirInfo readInfo( String path, Directory dir ) throws IOException { IndexReader indexReader = IndexReader.open( dir ); try { // Fetch the chunk size and overlap from the index. Hits match = new IndexSearcher(indexReader).search( new TermQuery( new Term("indexInfo", "1")) ); if( match.length() == 0 ) throw new IOException( "Index missing indexInfo doc" ); assert match.id(0) == 0 : "indexInfo chunk must be first in index"; Document doc = match.doc( 0 ); // Pick out all the info we need. DirInfo ret = new DirInfo( path, dir ); ret.chunkSize = Integer.parseInt(doc.get("chunkSize")); ret.chunkOverlap = Integer.parseInt(doc.get("chunkOvlp")); ret.stopWords = doc.get( "stopWords" ); ret.pluralMapName = doc.get( "pluralMap" ); ret.accentMapName = doc.get( "accentMap" ); return ret; } finally { indexReader.close(); } } ////////////////////////////////////////////////////////////////////////////// /** * Merge a bunch of indexes together. */ private static void doMerge( DirInfo[] dirInfos, boolean createTarget ) throws InterruptedException, IOException { long startTime = System.currentTimeMillis(); // Let the user know what's about to occur. Trace.info( "Ready to merge data from the following index directories:" ); Trace.tab(); for( int i = 1; i < dirInfos.length; i++ ) Trace.info( dirInfos[i].path ); Trace.untab(); Trace.info( "into (and including data from) index directory:" ); Trace.tab(); Trace.info( dirInfos[0].path ); Trace.untab(); // Give them time to abort without consequences. Trace.info( "" ); Trace.info( "Merge will begin in 5 seconds ... " ); Thread.sleep( 5000 ); Trace.info( "" ); Trace.info( "Merging indexes ... " ); Trace.tab(); // Open the writer for the target Lucene index IndexWriter writer = new IndexWriter( dirInfos[0].path, new StandardAnalyzer(), createTarget ); // Merge each piece (spelling, lazy files, main indexes) mergeSpelling( dirInfos ); mergeLazy( dirInfos ); mergeAux( dirInfos ); mergeLucene( writer, dirInfos ); // All done. Report how long we spent. Trace.untab(); long timeMsec = System.currentTimeMillis() - startTime; long timeSec = timeMsec / 1000; long timeMin = timeSec / 60; long timeHour = timeMin / 60; Trace.info( "Total time: " ); if( timeHour > 0 ) { String ending = (timeHour == 1) ? "" : "s"; Trace.more( Trace.info, timeHour + " hour" + ending + ", " ); } if( timeMin > 0 ) { String ending = ((timeMin % 60) == 1) ? "" : "s"; Trace.more( Trace.info, (timeMin % 60) + " minute" + ending + ", " ); } String ending = ((timeSec % 60) == 1) ? "" : "s"; Trace.more( Trace.info, (timeSec % 60) + " second" + ending + "." ); Trace.info( "Merge completed successfully." ); } // doMerge() ////////////////////////////////////////////////////////////////////////////// private static void mergeSpelling( DirInfo[] dirInfos ) throws IOException { // If there are none to do, skip this step. boolean anyToDo = false; for( int i = 1; i < dirInfos.length; i++ ) { String sourceDir = dirInfos[i].path; File sourceFile = new File( sourceDir + "SpellDict/newWords.dat" ); if( !sourceFile.isFile() && sourceFile.canRead() ) continue; anyToDo = true; } if( !anyToDo ) return; Trace.info( "Processing spellcheck word lists ... " ); // Append each input file. for( int i = 1; i < dirInfos.length; i++ ) { String sourceDir = dirInfos[i].path; File sourceFile = new File( sourceDir + "SpellDict/newWords.dat" ); if( !sourceFile.isFile() && sourceFile.canRead() ) continue; // Open the target file. String targetDir = dirInfos[0].path; Path.createPath( targetDir + "spellDict" ); File targetFile = new File( targetDir + "spellDict/newWords.dat" ); ObjectOutputStream targetWriter = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(targetFile, targetFile.isFile()))); InputStream sourceRaw = new BufferedInputStream( new FileInputStream(sourceFile)); ObjectInputStream sourceReader = new ObjectInputStream(sourceRaw); boolean eof = false; while( !eof ) { try { String word = sourceReader.readUTF(); targetWriter.writeUTF( word ); } catch (EOFException e) { eof = true; } } sourceReader.close(); sourceRaw.close(); targetWriter.close(); } // for Trace.more( "Done." ); } // mergeSpelling() ////////////////////////////////////////////////////////////////////////////// private static void mergeAux( DirInfo[] dirInfos ) throws IOException { // If there are none to do, skip this step. boolean anyToDo = false; for( int i = 1; i < dirInfos.length; i++ ) { String sourceDir = dirInfos[i].path; File accentFile = new File( sourceDir + dirInfos[i].accentMapName ); File pluralFile = new File( sourceDir + dirInfos[i].pluralMapName ); if( accentFile.canRead() || pluralFile.canRead() ) anyToDo = true; } if( !anyToDo ) return; Trace.info( "Processing auxiliary files ... " ); // Copy files from each directory... for( int i = 1; i < dirInfos.length; i++ ) { File accentSrc = new File( dirInfos[i].path, dirInfos[i].accentMapName ); File pluralSrc = new File( dirInfos[i].path, dirInfos[i].pluralMapName ); File accentDst = new File( dirInfos[0].path, dirInfos[i].accentMapName ); File pluralDst = new File( dirInfos[0].path, dirInfos[i].pluralMapName ); if( accentSrc.canRead() && !accentDst.canRead() ) Path.copyFile( accentSrc, accentDst ); if( pluralSrc.canRead() && !pluralDst.canRead() ) Path.copyFile( pluralSrc, pluralDst ); } // for Trace.more( "Done." ); } // mergeAux() ////////////////////////////////////////////////////////////////////////////// private static void mergeLazy( DirInfo[] dirInfos ) throws IOException { // Get the target lazy directory. String targetDir = dirInfos[0].path; // See if there are any source directories to merge. boolean anyToDo = false; for( int i = 1; i < dirInfos.length; i++ ) { String sourceDir = dirInfos[i].path; File lazyDir = new File( sourceDir, "lazy" ); if( lazyDir.isDirectory() ) anyToDo = true; } if( !anyToDo ) return; Trace.info( "Processing lazy tree files ... " ); // Process each source directory. for( int i = 1; i < dirInfos.length; i++ ) { String sourceDir = dirInfos[i].path; mergeLazy( new File(sourceDir, "lazy"), new File(targetDir, "lazy") ); } // for Trace.more( "Done." ); } // mergeLazy() ////////////////////////////////////////////////////////////////////////////// private static void mergeLazy( File src, File dst ) throws IOException { // If the source is a file, copy it. if( src.isFile() ) { // If the target file already exists, don't overwrite. if( dst.isFile() ) return; // Copy away. Path.copyFile( src, dst ); return; } // If the source is a directory, create the corresponding target // directory, and copy the files and sub-directories. // if( src.isDirectory() ) { if( !dst.isDirectory() ) { if( !Path.createPath(dst.toString()) ) throw new IOException( "Error creating lazy file directory '" + dst + "'" ); } // Process each sub-file String[] subFiles = src.list(); for( int i = 0; i < subFiles.length; i++ ) { mergeLazy( new File(src, subFiles[i]), new File(dst, subFiles[i]) ); } // for } // if } // mergeLazy() ////////////////////////////////////////////////////////////////////////////// private static void mergeLucene( IndexWriter writer, DirInfo[] dirInfos ) throws IOException { Trace.info( "Processing Lucene indexes (time-consuming) ... " ); Directory[] dirs = new Directory[dirInfos.length-1]; for( int i = 1; i < dirInfos.length; i++ ) dirs[i-1] = dirInfos[i].dir; writer.addIndexes( dirs ); writer.optimize(); writer.close(); Trace.more( "Done." ); } // mergeLucene() ////////////////////////////////////////////////////////////////////////////// private static class DirInfo { public DirInfo(String idxPath, Directory srcDir) { this.path = idxPath; this.dir = srcDir; } String path; Directory dir; int chunkSize; int chunkOverlap; String stopWords; String pluralMapName; String accentMapName; } // class DirInfo } // class IndexMerge
true
true
public static void main( String[] args ) { Trace.info( "IndexMerge v. 1.8" ); try { IndexerConfig cfgInfo = new IndexerConfig(); XMLConfigParser cfgParser = new XMLConfigParser(); int startArg = 0; boolean showUsage = false; // Make sure the XTF_HOME environment variable is specified. cfgInfo.xtfHomePath = System.getProperty( "xtf.home" ); if( cfgInfo.xtfHomePath == null || cfgInfo.xtfHomePath.length() == 0 ) { Trace.error( "Error: xtf.home property not found" ); return; } cfgInfo.xtfHomePath = Path.normalizePath( cfgInfo.xtfHomePath ); if( !new File(cfgInfo.xtfHomePath).isDirectory() ) { Trace.error( "Error: xtf.home directory \"" + cfgInfo.xtfHomePath + "\" does not exist or cannot be read." ); return; } // Parse the command-line arguments. Vector mergePaths = new Vector(); HashSet pathSet = new HashSet(); for(;;) { // The minimum set of arguments consists of the name of an index // to read and an output index. That requires four arguments; if // we don't get that many, we will show the usage text and bail. // if( args.length < 4 ) showUsage = true; // We have enough arguments, so... else { // Read the command line arguments until we find what we // need to do some work, or until we run out. // int ret = cfgInfo.readCmdLine( args, startArg ); // If we didn't find enough command line arguments... if( ret == -1 ) { // And this is the first time we've visited the command // line arguments, avoid trying to doing work and just // display the usage text. Otherwise, we're done. // if( startArg == 0 ) showUsage = true; else break; } // if( ret == -1 ) // We did find enough command line arguments, so... // else { // Make sure the configuration path is absolute if( !(new File(cfgInfo.cfgFilePath).isAbsolute()) ) { cfgInfo.cfgFilePath = Path.resolveRelOrAbs( cfgInfo.xtfHomePath, cfgInfo.cfgFilePath); } // Get the configuration for the index specified by the // current command line arguments. // if( cfgParser.configure(cfgInfo) < 0 ) { Trace.error( "Error: index '" + cfgInfo.indexInfo.indexName + "' not found\n" ); System.exit( 1 ); } } // else( ret != -1 ) // Save the new start argument for the next time. startArg = ret; // The indexes should all be in different directories. IndexInfo idxInfo = cfgInfo.indexInfo; String idxPath = Path.resolveRelOrAbs(cfgInfo.xtfHomePath, idxInfo.indexPath); if( pathSet.contains(idxPath) ) { Trace.error( "Error: indexes to be merged must be in separate directories." ); System.exit( 1 ); } pathSet.add( idxPath ); // Save the index info for the merge mergePaths.add( idxPath ); } // else } // for // At least two indexes should be specified. if( mergePaths.size() < 2 ) showUsage = true; // Show usage message if any problems found. if( showUsage ) { // Do so... Trace.error( " usage: " ); Trace.tab(); Trace.error( "indexMerge {-config <configfile>} " + "-index <inputOutputIndex> " + "-index <inputIndex1> " + "{-index inputIndex2...}\n\n" ); Trace.untab(); // And then bail. System.exit( 1 ); } // if( showUsage ) // Make sure all the indexes exist, and that their parameters are at // least minimally compatible. // DirInfo[] dirInfos = new DirInfo[mergePaths.size()]; boolean createTarget = false; boolean done = false; for( int i = 0; i < mergePaths.size(); i++ ) { String idxPath = (String) mergePaths.get( i ); if( !IndexReader.indexExists(idxPath) ) { // It's okay if the target index doesn't exist. if( i == 0 ) { createTarget = true; dirInfos[0] = new DirInfo( idxPath, null ); continue; } throw new RuntimeException( "Error: Cannot locate index in directory '" + idxPath + "'" ); } Directory srcDir = FSDirectory.getDirectory( idxPath, false ); dirInfos[i] = readInfo( idxPath, srcDir ); // Check for parameter compatibility if( (i == 1 && !createTarget) || (i > 1) ) { if( dirInfos[i].chunkOverlap != dirInfos[i-1].chunkOverlap ) throw new RuntimeException( "Error: index parameters must match exactly (chunkOverlap mismatch detected)" ); if( dirInfos[i].chunkSize != dirInfos[i-1].chunkSize ) throw new RuntimeException( "Error: index parameters must match exactly (chunkSize mismatch detected)" ); if( !dirInfos[i].stopWords.equals(dirInfos[i-1].stopWords) ) throw new RuntimeException( "Error: index parameters must match exactly (stopWords mismatch detected)" ); if( !dirInfos[i].accentMapName.equals(dirInfos[i-1].accentMapName) ) throw new RuntimeException( "Error: index parameters must match exactly (accentMapName mismatch detected)" ); if( !dirInfos[i].pluralMapName.equals(dirInfos[i-1].pluralMapName) ) throw new RuntimeException( "Error: index parameters must match exactly (pluralMapName mismatch detected)" ); } } // for // Well, enough preparing. Let's do the job we were sent to do. doMerge( dirInfos, createTarget ); } // try // Log any unhandled exceptions. catch( Exception e ) { Trace.error( "*** Last Chance Exception: " + e.getClass() ); Trace.error( " With message: " + e.getMessage() ); Trace.error( "" ); e.printStackTrace( System.out ); System.exit( 1 ); } catch( Throwable t ) { Trace.error( "*** Last Chance Exception: " + t.getClass() ); Trace.error( " With message: " + t ); Trace.error( "" ); t.printStackTrace( System.out ); System.exit( 1 ); } // Exit successfully. System.exit( 0 ); } // main()
public static void main( String[] args ) { Trace.info( "IndexMerge v. 1.8" ); try { IndexerConfig cfgInfo = new IndexerConfig(); XMLConfigParser cfgParser = new XMLConfigParser(); int startArg = 0; boolean showUsage = false; // Make sure the XTF_HOME environment variable is specified. cfgInfo.xtfHomePath = System.getProperty( "xtf.home" ); if( cfgInfo.xtfHomePath == null || cfgInfo.xtfHomePath.length() == 0 ) { Trace.error( "Error: xtf.home property not found" ); return; } cfgInfo.xtfHomePath = Path.normalizePath( cfgInfo.xtfHomePath ); if( !new File(cfgInfo.xtfHomePath).isDirectory() ) { Trace.error( "Error: xtf.home directory \"" + cfgInfo.xtfHomePath + "\" does not exist or cannot be read." ); return; } // Parse the command-line arguments. Vector mergePaths = new Vector(); HashSet pathSet = new HashSet(); while( !showUsage && startArg < args.length ) { // The minimum set of arguments consists of the name of an index // to read and an output index. That requires four arguments; if // we don't get that many, we will show the usage text and bail. // if( args.length < 4 ) showUsage = true; // We have enough arguments, so... else { // Read the command line arguments until we find what we // need to do some work, or until we run out. // int ret = cfgInfo.readCmdLine( args, startArg ); // If we didn't find enough command line arguments... if( ret == -1 ) { // And this is the first time we've visited the command // line arguments, avoid trying to doing work and just // display the usage text. Otherwise, we're done. // if( startArg == 0 ) showUsage = true; else break; } // if( ret == -1 ) // We did find enough command line arguments, so... // else { // Make sure the configuration path is absolute if( !(new File(cfgInfo.cfgFilePath).isAbsolute()) ) { cfgInfo.cfgFilePath = Path.resolveRelOrAbs( cfgInfo.xtfHomePath, cfgInfo.cfgFilePath); } // Get the configuration for the index specified by the // current command line arguments. // if( cfgParser.configure(cfgInfo) < 0 ) { Trace.error( "Error: index '" + cfgInfo.indexInfo.indexName + "' not found\n" ); System.exit( 1 ); } } // else( ret != -1 ) // Save the new start argument for the next time. startArg = ret; // The indexes should all be in different directories. IndexInfo idxInfo = cfgInfo.indexInfo; String idxPath = Path.resolveRelOrAbs(cfgInfo.xtfHomePath, idxInfo.indexPath); if( pathSet.contains(idxPath) ) { Trace.error( "Error: indexes to be merged must be in separate directories." ); System.exit( 1 ); } pathSet.add( idxPath ); // Save the index info for the merge mergePaths.add( idxPath ); } // else } // for // At least two indexes should be specified. if( mergePaths.size() < 2 ) showUsage = true; // Show usage message if any problems found. if( showUsage ) { // Do so... Trace.error( " usage: " ); Trace.tab(); Trace.error( "indexMerge {-config <configfile>} " + "-index <inputOutputIndex> " + "-index <inputIndex1> " + "{-index inputIndex2...}\n\n" ); Trace.untab(); // And then bail. System.exit( 1 ); } // if( showUsage ) // Make sure all the indexes exist, and that their parameters are at // least minimally compatible. // DirInfo[] dirInfos = new DirInfo[mergePaths.size()]; boolean createTarget = false; boolean done = false; for( int i = 0; i < mergePaths.size(); i++ ) { String idxPath = (String) mergePaths.get( i ); if( !IndexReader.indexExists(idxPath) ) { // It's okay if the target index doesn't exist. if( i == 0 ) { createTarget = true; dirInfos[0] = new DirInfo( idxPath, null ); continue; } throw new RuntimeException( "Error: Cannot locate index in directory '" + idxPath + "'" ); } Directory srcDir = FSDirectory.getDirectory( idxPath, false ); dirInfos[i] = readInfo( idxPath, srcDir ); // Check for parameter compatibility if( (i == 1 && !createTarget) || (i > 1) ) { if( dirInfos[i].chunkOverlap != dirInfos[i-1].chunkOverlap ) throw new RuntimeException( "Error: index parameters must match exactly (chunkOverlap mismatch detected)" ); if( dirInfos[i].chunkSize != dirInfos[i-1].chunkSize ) throw new RuntimeException( "Error: index parameters must match exactly (chunkSize mismatch detected)" ); if( !dirInfos[i].stopWords.equals(dirInfos[i-1].stopWords) ) throw new RuntimeException( "Error: index parameters must match exactly (stopWords mismatch detected)" ); if( !dirInfos[i].accentMapName.equals(dirInfos[i-1].accentMapName) ) throw new RuntimeException( "Error: index parameters must match exactly (accentMapName mismatch detected)" ); if( !dirInfos[i].pluralMapName.equals(dirInfos[i-1].pluralMapName) ) throw new RuntimeException( "Error: index parameters must match exactly (pluralMapName mismatch detected)" ); } } // for // Well, enough preparing. Let's do the job we were sent to do. doMerge( dirInfos, createTarget ); } // try // Log any unhandled exceptions. catch( Exception e ) { Trace.error( "*** Last Chance Exception: " + e.getClass() ); Trace.error( " With message: " + e.getMessage() ); Trace.error( "" ); e.printStackTrace( System.out ); System.exit( 1 ); } catch( Throwable t ) { Trace.error( "*** Last Chance Exception: " + t.getClass() ); Trace.error( " With message: " + t ); Trace.error( "" ); t.printStackTrace( System.out ); System.exit( 1 ); } // Exit successfully. System.exit( 0 ); } // main()
diff --git a/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java b/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java index a56950ae..438e3b1e 100644 --- a/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java +++ b/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java @@ -1,895 +1,897 @@ /* * Copyright (C) 2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 or * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ package uk.me.parabola.mkgmap.reader.osm; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import uk.me.parabola.imgfmt.MapFailedException; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.Coord; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.general.LineClipper; import uk.me.parabola.mkgmap.osmstyle.StyleImpl; import uk.me.parabola.util.EnhancedProperties; /** * Code to generate sea polygons from the coastline ways. * * Currently there are a number of different options. * Should pick one that works well and make it the default. * */ public class SeaGenerator extends OsmReadingHooksAdaptor { private static final Logger log = Logger.getLogger(SeaGenerator.class); private boolean generateSeaUsingMP = true; private int maxCoastlineGap; private boolean allowSeaSectors = true; private boolean extendSeaSectors; private String[] landTag = { "natural", "land" }; private boolean floodblocker = false; private int fbGap = 40; private double fbRatio = 0.5d; private int fbThreshold = 20; private boolean fbDebug = false; private ElementSaver saver; private List<Way> shoreline = new ArrayList<Way>(); private boolean roadsReachBoundary; // todo needs setting somehow private boolean generateSeaBackground = true; private String[] coastlineFilenames; private StyleImpl fbRules; /** * Sort out options from the command line. * Returns true only if the option to generate the sea is active, so that * the whole thing is omitted if not used. */ public boolean init(ElementSaver saver, EnhancedProperties props) { this.saver = saver; String gs = props.getProperty("generate-sea", null); boolean generateSea = gs != null; if(generateSea) { for(String o : gs.split(",")) { if("no-mp".equals(o) || "polygon".equals(o) || "polygons".equals(o)) generateSeaUsingMP = false; else if("multipolygon".equals(o)) generateSeaUsingMP = true; else if(o.startsWith("close-gaps=")) maxCoastlineGap = (int)Double.parseDouble(o.substring(11)); else if("no-sea-sectors".equals(o)) allowSeaSectors = false; else if("extend-sea-sectors".equals(o)) { allowSeaSectors = false; extendSeaSectors = true; } else if(o.startsWith("land-tag=")) landTag = o.substring(9).split("="); else if("floodblocker".equals(o)) floodblocker = true; else if(o.startsWith("fbgap=")) fbGap = (int)Double.parseDouble(o.substring("fbgap=".length())); else if(o.startsWith("fbratio=")) fbRatio = Double.parseDouble(o.substring("fbratio=".length())); else if(o.startsWith("fbthres=")) fbThreshold = (int)Double.parseDouble(o.substring("fbthres=".length())); else if("fbdebug".equals(o)) fbDebug = true; else { if(!"help".equals(o)) System.err.println("Unknown sea generation option '" + o + "'"); System.err.println("Known sea generation options are:"); System.err.println(" multipolygon use a multipolygon (default)"); System.err.println(" polygons | no-mp use polygons rather than a multipolygon"); System.err.println(" no-sea-sectors disable use of \"sea sectors\""); System.err.println(" extend-sea-sectors extend coastline to reach border"); System.err.println(" land-tag=TAG=VAL tag to use for land polygons (default natural=land)"); System.err.println(" close-gaps=NUM close gaps in coastline that are less than this distance (metres)"); System.err.println(" floodblocker enable the floodblocker (for multipolgon only)"); System.err.println(" fbgap=NUM points closer to the coastline are ignored for flood blocking (default 40)"); System.err.println(" fbthres=NUM min points contained in a polygon to be flood blocked (default 20)"); System.err.println(" fbratio=NUM min ratio (points/area size) for flood blocking (default 0.5)"); } } if (floodblocker) { try { fbRules = new StyleImpl(null, "floodblocker"); } catch (FileNotFoundException e) { log.error("Cannot load file floodblocker rules. Continue floodblocking disabled."); floodblocker = false; } } String coastlineFileOpt = props.getProperty("coastlinefile", null); if (coastlineFileOpt != null) { coastlineFilenames = coastlineFileOpt.split(","); CoastlineFileLoader.getCoastlineLoader().setCoastlineFiles( coastlineFilenames); CoastlineFileLoader.getCoastlineLoader().loadCoastlines(); log.info("Coastlines loaded"); } else { coastlineFilenames = null; } } return generateSea; } public Set<String> getUsedTags() { HashSet<String> usedTags = new HashSet<String>(); if (coastlineFilenames == null) { usedTags.add("natural"); } if (floodblocker) { usedTags.addAll(fbRules.getUsedTags()); } if (log.isDebugEnabled()) log.debug("Sea generator used tags: "+usedTags); return usedTags; } /** * Test to see if the way is part of the shoreline and if it is * we save it. * @param way The way to test. */ public void onAddWay(Way way) { String natural = way.getTag("natural"); if(natural != null) { if("coastline".equals(natural)) { way.deleteTag("natural"); if (coastlineFilenames == null) shoreline.add(way); } else if (natural.contains(";")) { // cope with compound tag value String others = null; boolean foundCoastline = false; for(String n : natural.split(";")) { if("coastline".equals(n.trim())) foundCoastline = true; else if(others == null) others = n; else others += ";" + n; } if(foundCoastline) { way.deleteTag("natural"); if(others != null) way.addTag("natural", others); if (coastlineFilenames == null) shoreline.add(way); } } } } /** * Joins the given segments to closed ways as good as possible. * @param segments a list of closed and unclosed ways * @return a list of ways completely joined */ public static ArrayList<Way> joinWays(Collection<Way> segments) { ArrayList<Way> joined = new ArrayList<Way>((int)Math.ceil(segments.size()*0.5)); Map<Coord, Way> beginMap = new HashMap<Coord, Way>(); for (Way w : segments) { if (w.isClosed()) { joined.add(w); } else { List<Coord> points = w.getPoints(); beginMap.put(points.get(0), w); } } segments.clear(); int merged = 1; while (merged > 0) { merged = 0; for (Way w1 : beginMap.values()) { if (w1.isClosed()) { // this should not happen log.error("joinWays2: Way "+w1+" is closed but contained in the begin map"); joined.add(w1); beginMap.remove(w1.getPoints().get(0)); merged=1; break; } List<Coord> points1 = w1.getPoints(); Way w2 = beginMap.get(points1.get(points1.size() - 1)); if (w2 != null) { log.info("merging: ", beginMap.size(), w1.getId(), w2.getId()); List<Coord> points2 = w2.getPoints(); Way wm; if (FakeIdGenerator.isFakeId(w1.getId())) { wm = w1; } else { wm = new Way(FakeIdGenerator.makeFakeId()); wm.getPoints().addAll(points1); beginMap.put(points1.get(0), wm); } wm.getPoints().addAll(points2.subList(1, points2.size())); beginMap.remove(points2.get(0)); merged++; if (wm.isClosed()) { joined.add(wm); beginMap.remove(wm.getPoints().get(0)); } break; } } } log.info(joined.size(),"closed ways.",beginMap.size(),"unclosed ways."); joined.addAll(beginMap.values()); return joined; } /** * All done, process the saved shoreline information and construct the polygons. */ public void end() { Area seaBounds = saver.getBoundingBox(); if (coastlineFilenames == null) { log.info("Shorelines before join", shoreline.size()); shoreline = joinWays(shoreline); } else { shoreline.addAll(CoastlineFileLoader.getCoastlineLoader() .getCoastlines(seaBounds)); log.info("Shorelines from extra file:", shoreline.size()); } int closedS = 0; int unclosedS = 0; for (Way w : shoreline) { if (w.isClosed()) { closedS++; } else { unclosedS++; } } log.info("Closed shorelines", closedS); log.info("Unclosed shorelines", unclosedS); // clip all shoreline segments clipShorlineSegments(shoreline, seaBounds); log.info("generating sea, seaBounds=", seaBounds); int minLat = seaBounds.getMinLat(); int maxLat = seaBounds.getMaxLat(); int minLong = seaBounds.getMinLong(); int maxLong = seaBounds.getMaxLong(); Coord nw = new Coord(minLat, minLong); Coord ne = new Coord(minLat, maxLong); Coord sw = new Coord(maxLat, minLong); Coord se = new Coord(maxLat, maxLong); if(shoreline.isEmpty()) { // no sea required // even though there is no sea, generate a land // polygon so that the tile's background colour will // match the land colour on the tiles that do contain // some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); // no matter if the multipolygon option is used it is // only necessary to create a land polygon saver.addWay(land); // nothing more to do return; } long multiId = FakeIdGenerator.makeFakeId(); Relation seaRelation = null; if(generateSeaUsingMP) { log.debug("Generate seabounds relation",multiId); seaRelation = new GeneralRelation(multiId); seaRelation.addTag("type", "multipolygon"); seaRelation.addTag("natural", "sea"); } List<Way> islands = new ArrayList<Way>(); // handle islands (closed shoreline components) first (they're easy) handleIslands(shoreline, seaBounds, islands); // the remaining shoreline segments should intersect the boundary // find the intersection points and store them in a SortedMap SortedMap<EdgeHit, Way> hitMap = findIntesectionPoints(shoreline, seaBounds, seaRelation); // now construct inner ways from these segments boolean shorelineReachesBoundary = createInnerWays(seaBounds, islands, hitMap); if(!shorelineReachesBoundary && roadsReachBoundary) { // try to avoid tiles being flooded by anti-lakes or other // bogus uses of natural=coastline generateSeaBackground = false; } List<Way> antiIslands = removeAntiIslands(seaRelation, islands); if (islands.isEmpty()) { // the tile doesn't contain any islands so we can assume // that it's showing a land mass that contains some // enclosed sea areas - in which case, we don't want a sea // coloured background generateSeaBackground = false; } if (generateSeaBackground) { // the background is sea so all anti-islands should be // contained by land otherwise they won't be visible for (Way ai : antiIslands) { boolean containedByLand = false; for(Way i : islands) { if(i.containsPointsOf(ai)) { containedByLand = true; break; } } if (!containedByLand) { // found an anti-island that is not contained by // land so convert it back into an island ai.deleteTag("natural"); ai.addTag(landTag[0], landTag[1]); if (generateSeaUsingMP) { // create a "inner" way for the island assert seaRelation != null; seaRelation.addElement("inner", ai); } log.warn("Converting anti-island starting at", ai.getPoints().get(0).toOSMURL() , "into an island as it is surrounded by water"); } } long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); // the sea background area must be a little bigger than all // inner land areas. this is a workaround for a mp shortcoming: // mp is not able to combine outer and inner if they intersect // or have overlaying lines // the added area will be clipped later by the style generator sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addPoint(new Coord(sw.getLatitude() + 1, sw.getLongitude() - 1)); sea.addPoint(new Coord(se.getLatitude() + 1, se.getLongitude() + 1)); sea.addPoint(new Coord(ne.getLatitude() - 1, ne.getLongitude() + 1)); sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) { assert seaRelation != null; seaRelation.addElement("outer", sea); } } else { // background is land // generate a land polygon so that the tile's // background colour will match the land colour on the // tiles that do contain some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); saver.addWay(land); if (generateSeaUsingMP) { seaRelation.addElement("inner", land); } } if (generateSeaUsingMP) { SeaPolygonRelation coastRel = saver.createSeaPolyRelation(seaRelation); coastRel.setFloodBlocker(floodblocker); - coastRel.setFloodBlockerGap(fbGap); - coastRel.setFloodBlockerRatio(fbRatio); - coastRel.setFloodBlockerThreshold(fbThreshold); - coastRel.setFloodBlockerRules(fbRules.getWayRules()); - coastRel.setLandTag(landTag[0], landTag[1]); - coastRel.setDebug(fbDebug); + if (floodblocker) { + coastRel.setFloodBlockerGap(fbGap); + coastRel.setFloodBlockerRatio(fbRatio); + coastRel.setFloodBlockerThreshold(fbThreshold); + coastRel.setFloodBlockerRules(fbRules.getWayRules()); + coastRel.setLandTag(landTag[0], landTag[1]); + coastRel.setDebug(fbDebug); + } saver.addRelation(coastRel); } } /** * Clip the shoreline ways to the bounding box of the map. * @param shoreline All the the ways making up the coast. * @param bounds The map bounds. */ private void clipShorlineSegments(List<Way> shoreline, Area bounds) { List<Way> toBeRemoved = new ArrayList<Way>(); List<Way> toBeAdded = new ArrayList<Way>(); for (Way segment : shoreline) { List<Coord> points = segment.getPoints(); List<List<Coord>> clipped = LineClipper.clip(bounds, points); if (clipped != null) { log.info("clipping", segment); toBeRemoved.add(segment); for (List<Coord> pts : clipped) { long id = FakeIdGenerator.makeFakeId(); Way shore = new Way(id, pts); toBeAdded.add(shore); } } } log.info("clipping: adding ", toBeAdded.size(), ", removing ", toBeRemoved.size()); shoreline.removeAll(toBeRemoved); shoreline.addAll(toBeAdded); } /** * Pick out the islands and save them for later. They are removed from the * shore line list and added to the island list. * * @param shoreline The collected shore line ways. * @param seaBounds The map boundary. * @param islands The islands are saved to this list. */ private void handleIslands(List<Way> shoreline, Area seaBounds, List<Way> islands) { Iterator<Way> it = shoreline.iterator(); while (it.hasNext()) { Way w = it.next(); if (w.isClosed()) { log.info("adding island", w); islands.add(w); it.remove(); } } closeGaps(shoreline, seaBounds); // there may be more islands now it = shoreline.iterator(); while (it.hasNext()) { Way w = it.next(); if (w.isClosed()) { log.debug("island after concatenating"); islands.add(w); it.remove(); } } } private boolean createInnerWays(Area seaBounds, List<Way> islands, SortedMap<EdgeHit, Way> hitMap) { NavigableSet<EdgeHit> hits = (NavigableSet<EdgeHit>) hitMap.keySet(); boolean shorelineReachesBoundary = false; while (!hits.isEmpty()) { long id = FakeIdGenerator.makeFakeId(); Way w = new Way(id); saver.addWay(w); EdgeHit hit = hits.first(); EdgeHit hFirst = hit; do { Way segment = hitMap.get(hit); log.info("current hit:", hit); EdgeHit hNext; if (segment != null) { // add the segment and get the "ending hit" log.info("adding:", segment); for(Coord p : segment.getPoints()) w.addPointIfNotEqualToLastPoint(p); hNext = getEdgeHit(seaBounds, segment.getPoints().get(segment.getPoints().size()-1)); } else { w.addPointIfNotEqualToLastPoint(hit.getPoint(seaBounds)); hNext = hits.higher(hit); if (hNext == null) hNext = hFirst; Coord p; if (hit.compareTo(hNext) < 0) { log.info("joining: ", hit, hNext); for (int i=hit.edge; i<hNext.edge; i++) { EdgeHit corner = new EdgeHit(i, 1.0); p = corner.getPoint(seaBounds); log.debug("way: ", corner, p); w.addPointIfNotEqualToLastPoint(p); } } else if (hit.compareTo(hNext) > 0) { log.info("joining: ", hit, hNext); for (int i=hit.edge; i<4; i++) { EdgeHit corner = new EdgeHit(i, 1.0); p = corner.getPoint(seaBounds); log.debug("way: ", corner, p); w.addPointIfNotEqualToLastPoint(p); } for (int i=0; i<hNext.edge; i++) { EdgeHit corner = new EdgeHit(i, 1.0); p = corner.getPoint(seaBounds); log.debug("way: ", corner, p); w.addPointIfNotEqualToLastPoint(p); } } w.addPointIfNotEqualToLastPoint(hNext.getPoint(seaBounds)); } hits.remove(hit); hit = hNext; } while (!hits.isEmpty() && !hit.equals(hFirst)); if (!w.isClosed()) w.getPoints().add(w.getPoints().get(0)); log.info("adding non-island landmass, hits.size()=" + hits.size()); islands.add(w); shorelineReachesBoundary = true; } return shorelineReachesBoundary; } /** * An 'anti-island' is something that has been detected as an island, but the water * is on the inside. I think you would call this a lake. * @param seaRelation The relation holding the sea. Only set if we are using multi-polygons for * the sea. * @param islands The island list that was found earlier. * @return The so-called anti-islands. */ private List<Way> removeAntiIslands(Relation seaRelation, List<Way> islands) { List<Way> antiIslands = new ArrayList<Way>(); for (Way w : islands) { if (!FakeIdGenerator.isFakeId(w.getId())) { Way w1 = new Way(FakeIdGenerator.makeFakeId()); w1.getPoints().addAll(w.getPoints()); // only copy the name tags for(String tag : w) if(tag.equals("name") || tag.endsWith(":name")) w1.addTag(tag, w.getTag(tag)); w = w1; } // determine where the water is if (w.clockwise()) { // water on the inside of the poly, it's an // "anti-island" so tag with natural=water (to // make it visible above the land) w.addTag("natural", "water"); antiIslands.add(w); saver.addWay(w); } else { // water on the outside of the poly, it's an island w.addTag(landTag[0], landTag[1]); saver.addWay(w); if(generateSeaUsingMP) { // create a "inner" way for each island seaRelation.addElement("inner", w); } } } islands.removeAll(antiIslands); return antiIslands; } /** * Find the points where the remaining shore line segments intersect with the * map boundary. * * @param shoreline The remaining shore line segments. * @param seaBounds The map boundary. * @param seaRelation If we are using a multi-polygon, this is it. Otherwise it will be null. * @return A map of the 'hits' where the shore line intersects the boundary. */ private SortedMap<EdgeHit, Way> findIntesectionPoints(List<Way> shoreline, Area seaBounds, Relation seaRelation) { assert !generateSeaUsingMP || seaRelation != null; SortedMap<EdgeHit, Way> hitMap = new TreeMap<EdgeHit, Way>(); for (Way w : shoreline) { List<Coord> points = w.getPoints(); Coord pStart = points.get(0); Coord pEnd = points.get(points.size()-1); EdgeHit hStart = getEdgeHit(seaBounds, pStart); EdgeHit hEnd = getEdgeHit(seaBounds, pEnd); if (hStart == null || hEnd == null) { /* * This problem occurs usually when the shoreline is cut by osmosis (e.g. country-extracts from geofabrik) * There are two possibilities to solve this problem: * 1. Close the way and treat it as an island. This is sometimes the best solution (Germany: Usedom at the * border to Poland) * 2. Create a "sea sector" only for this shoreline segment. This may also be the best solution * (see German border to the Netherlands where the shoreline continues in the Netherlands) * The first choice may lead to "flooded" areas, the second may lead to "triangles". * * Usually, the first choice is appropriate if the segment is "nearly" closed. */ double length = 0; Coord p0 = pStart; for (Coord p1 : points.subList(1, points.size()-1)) { length += p0.distance(p1); p0 = p1; } boolean nearlyClosed = pStart.distance(pEnd) < 0.1 * length; if (nearlyClosed) { // close the way points.add(pStart); if(!FakeIdGenerator.isFakeId(w.getId())) { Way w1 = new Way(FakeIdGenerator.makeFakeId()); w1.getPoints().addAll(w.getPoints()); // only copy the name tags for(String tag : w) if(tag.equals("name") || tag.endsWith(":name")) w1.addTag(tag, w.getTag(tag)); w = w1; } w.addTag(landTag[0], landTag[1]); saver.addWay(w); if(generateSeaUsingMP) { seaRelation.addElement("inner", w); } } else if(allowSeaSectors) { long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); sea.getPoints().addAll(points); sea.addPoint(new Coord(pEnd.getLatitude(), pStart.getLongitude())); sea.addPoint(pStart); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) seaRelation.addElement("outer", sea); generateSeaBackground = false; } else if (extendSeaSectors) { // create additional points at next border to prevent triangles from point 2 if (null == hStart) { hStart = getNextEdgeHit(seaBounds, pStart); w.getPoints().add(0, hStart.getPoint(seaBounds)); } if (null == hEnd) { hEnd = getNextEdgeHit(seaBounds, pEnd); w.getPoints().add(hEnd.getPoint(seaBounds)); } log.debug("hits (second try): ", hStart, hEnd); hitMap.put(hStart, w); hitMap.put(hEnd, null); } else { // show the coastline even though we can't produce // a polygon for the land w.addTag("natural", "coastline"); saver.addWay(w); } } else { log.debug("hits: ", hStart, hEnd); hitMap.put(hStart, w); hitMap.put(hEnd, null); } } return hitMap; } /** * Specifies where an edge of the bounding box is hit. */ private static class EdgeHit implements Comparable<EdgeHit> { private final int edge; private final double t; EdgeHit(int edge, double t) { this.edge = edge; this.t = t; } public int compareTo(EdgeHit o) { if (edge < o.edge) return -1; else if (edge > o.edge) return +1; else if (t > o.t) return +1; else if (t < o.t) return -1; else return 0; } public boolean equals(Object o) { if (o instanceof EdgeHit) { EdgeHit h = (EdgeHit) o; return (h.edge == edge && Double.compare(h.t, t) == 0); } else return false; } private Coord getPoint(Area a) { log.info("getPoint: ", this, a); switch (edge) { case 0: return new Coord(a.getMinLat(), (int) (a.getMinLong() + t * (a.getMaxLong()-a.getMinLong()))); case 1: return new Coord((int)(a.getMinLat() + t * (a.getMaxLat()-a.getMinLat())), a.getMaxLong()); case 2: return new Coord(a.getMaxLat(), (int)(a.getMaxLong() - t * (a.getMaxLong()-a.getMinLong()))); case 3: return new Coord((int)(a.getMaxLat() - t * (a.getMaxLat()-a.getMinLat())), a.getMinLong()); default: throw new MapFailedException("illegal state"); } } public String toString() { return "EdgeHit " + edge + "@" + t; } } private EdgeHit getEdgeHit(Area a, Coord p) { return getEdgeHit(a, p, 10); } private EdgeHit getEdgeHit(Area a, Coord p, int tolerance) { int lat = p.getLatitude(); int lon = p.getLongitude(); int minLat = a.getMinLat(); int maxLat = a.getMaxLat(); int minLong = a.getMinLong(); int maxLong = a.getMaxLong(); log.info(String.format("getEdgeHit: (%d %d) (%d %d %d %d)", lat, lon, minLat, minLong, maxLat, maxLong)); if (lat <= minLat+tolerance) { return new EdgeHit(0, ((double)(lon - minLong))/(maxLong-minLong)); } else if (lon >= maxLong-tolerance) { return new EdgeHit(1, ((double)(lat - minLat))/(maxLat-minLat)); } else if (lat >= maxLat-tolerance) { return new EdgeHit(2, ((double)(maxLong - lon))/(maxLong-minLong)); } else if (lon <= minLong+tolerance) { return new EdgeHit(3, ((double)(maxLat - lat))/(maxLat-minLat)); } else return null; } /** * Find the nearest edge for supplied Coord p. */ private EdgeHit getNextEdgeHit(Area a, Coord p) { int lat = p.getLatitude(); int lon = p.getLongitude(); int minLat = a.getMinLat(); int maxLat = a.getMaxLat(); int minLong = a.getMinLong(); int maxLong = a.getMaxLong(); log.info(String.format("getNextEdgeHit: (%d %d) (%d %d %d %d)", lat, lon, minLat, minLong, maxLat, maxLong)); // shortest distance to border (init with distance to southern border) int min = lat - minLat; // number of edge as used in getEdgeHit. // 0 = southern // 1 = eastern // 2 = northern // 3 = western edge of Area a int i = 0; // normalized position at border (0..1) double l = ((double)(lon - minLong))/(maxLong-minLong); // now compare distance to eastern border with already known distance if (maxLong - lon < min) { // update data if distance is shorter min = maxLong - lon; i = 1; l = ((double)(lat - minLat))/(maxLat-minLat); } // same for northern border if (maxLat - lat < min) { min = maxLat - lat; i = 2; l = ((double)(maxLong - lon))/(maxLong-minLong); } // same for western border if (lon - minLong < min) { i = 3; l = ((double)(maxLat - lat))/(maxLat-minLat); } // now created the EdgeHit for found values return new EdgeHit(i, l); } private void closeGaps(List<Way> ways, Area bounds) { // join up coastline segments whose end points are less than // maxCoastlineGap metres apart if (maxCoastlineGap > 0) { boolean changed = true; while (changed) { changed = false; for (Way w1 : ways) { if(w1.isClosed()) continue; List<Coord> points1 = w1.getPoints(); Coord w1e = points1.get(points1.size() - 1); if(bounds.onBoundary(w1e)) continue; Way nearest = null; double smallestGap = Double.MAX_VALUE; for (Way w2 : ways) { if(w1 == w2 || w2.isClosed()) continue; List<Coord> points2 = w2.getPoints(); Coord w2s = points2.get(0); if(bounds.onBoundary(w2s)) continue; double gap = w1e.distance(w2s); if(gap < smallestGap) { nearest = w2; smallestGap = gap; } } if (nearest != null && smallestGap < maxCoastlineGap) { Coord w2s = nearest.getPoints().get(0); log.warn("Bridging " + (int)smallestGap + "m gap in coastline from " + w1e.toOSMURL() + " to " + w2s.toOSMURL()); Way wm; if (FakeIdGenerator.isFakeId(w1.getId())) { wm = w1; } else { wm = new Way(FakeIdGenerator.makeFakeId()); ways.remove(w1); ways.add(wm); wm.getPoints().addAll(points1); wm.copyTags(w1); } wm.getPoints().addAll(nearest.getPoints()); ways.remove(nearest); // make a line that shows the filled gap Way w = new Way(FakeIdGenerator.makeFakeId()); w.addTag("natural", "mkgmap:coastline-gap"); w.addPoint(w1e); w.addPoint(w2s); saver.addWay(w); changed = true; break; } } } } } }
true
true
public void end() { Area seaBounds = saver.getBoundingBox(); if (coastlineFilenames == null) { log.info("Shorelines before join", shoreline.size()); shoreline = joinWays(shoreline); } else { shoreline.addAll(CoastlineFileLoader.getCoastlineLoader() .getCoastlines(seaBounds)); log.info("Shorelines from extra file:", shoreline.size()); } int closedS = 0; int unclosedS = 0; for (Way w : shoreline) { if (w.isClosed()) { closedS++; } else { unclosedS++; } } log.info("Closed shorelines", closedS); log.info("Unclosed shorelines", unclosedS); // clip all shoreline segments clipShorlineSegments(shoreline, seaBounds); log.info("generating sea, seaBounds=", seaBounds); int minLat = seaBounds.getMinLat(); int maxLat = seaBounds.getMaxLat(); int minLong = seaBounds.getMinLong(); int maxLong = seaBounds.getMaxLong(); Coord nw = new Coord(minLat, minLong); Coord ne = new Coord(minLat, maxLong); Coord sw = new Coord(maxLat, minLong); Coord se = new Coord(maxLat, maxLong); if(shoreline.isEmpty()) { // no sea required // even though there is no sea, generate a land // polygon so that the tile's background colour will // match the land colour on the tiles that do contain // some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); // no matter if the multipolygon option is used it is // only necessary to create a land polygon saver.addWay(land); // nothing more to do return; } long multiId = FakeIdGenerator.makeFakeId(); Relation seaRelation = null; if(generateSeaUsingMP) { log.debug("Generate seabounds relation",multiId); seaRelation = new GeneralRelation(multiId); seaRelation.addTag("type", "multipolygon"); seaRelation.addTag("natural", "sea"); } List<Way> islands = new ArrayList<Way>(); // handle islands (closed shoreline components) first (they're easy) handleIslands(shoreline, seaBounds, islands); // the remaining shoreline segments should intersect the boundary // find the intersection points and store them in a SortedMap SortedMap<EdgeHit, Way> hitMap = findIntesectionPoints(shoreline, seaBounds, seaRelation); // now construct inner ways from these segments boolean shorelineReachesBoundary = createInnerWays(seaBounds, islands, hitMap); if(!shorelineReachesBoundary && roadsReachBoundary) { // try to avoid tiles being flooded by anti-lakes or other // bogus uses of natural=coastline generateSeaBackground = false; } List<Way> antiIslands = removeAntiIslands(seaRelation, islands); if (islands.isEmpty()) { // the tile doesn't contain any islands so we can assume // that it's showing a land mass that contains some // enclosed sea areas - in which case, we don't want a sea // coloured background generateSeaBackground = false; } if (generateSeaBackground) { // the background is sea so all anti-islands should be // contained by land otherwise they won't be visible for (Way ai : antiIslands) { boolean containedByLand = false; for(Way i : islands) { if(i.containsPointsOf(ai)) { containedByLand = true; break; } } if (!containedByLand) { // found an anti-island that is not contained by // land so convert it back into an island ai.deleteTag("natural"); ai.addTag(landTag[0], landTag[1]); if (generateSeaUsingMP) { // create a "inner" way for the island assert seaRelation != null; seaRelation.addElement("inner", ai); } log.warn("Converting anti-island starting at", ai.getPoints().get(0).toOSMURL() , "into an island as it is surrounded by water"); } } long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); // the sea background area must be a little bigger than all // inner land areas. this is a workaround for a mp shortcoming: // mp is not able to combine outer and inner if they intersect // or have overlaying lines // the added area will be clipped later by the style generator sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addPoint(new Coord(sw.getLatitude() + 1, sw.getLongitude() - 1)); sea.addPoint(new Coord(se.getLatitude() + 1, se.getLongitude() + 1)); sea.addPoint(new Coord(ne.getLatitude() - 1, ne.getLongitude() + 1)); sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) { assert seaRelation != null; seaRelation.addElement("outer", sea); } } else { // background is land // generate a land polygon so that the tile's // background colour will match the land colour on the // tiles that do contain some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); saver.addWay(land); if (generateSeaUsingMP) { seaRelation.addElement("inner", land); } } if (generateSeaUsingMP) { SeaPolygonRelation coastRel = saver.createSeaPolyRelation(seaRelation); coastRel.setFloodBlocker(floodblocker); coastRel.setFloodBlockerGap(fbGap); coastRel.setFloodBlockerRatio(fbRatio); coastRel.setFloodBlockerThreshold(fbThreshold); coastRel.setFloodBlockerRules(fbRules.getWayRules()); coastRel.setLandTag(landTag[0], landTag[1]); coastRel.setDebug(fbDebug); saver.addRelation(coastRel); } }
public void end() { Area seaBounds = saver.getBoundingBox(); if (coastlineFilenames == null) { log.info("Shorelines before join", shoreline.size()); shoreline = joinWays(shoreline); } else { shoreline.addAll(CoastlineFileLoader.getCoastlineLoader() .getCoastlines(seaBounds)); log.info("Shorelines from extra file:", shoreline.size()); } int closedS = 0; int unclosedS = 0; for (Way w : shoreline) { if (w.isClosed()) { closedS++; } else { unclosedS++; } } log.info("Closed shorelines", closedS); log.info("Unclosed shorelines", unclosedS); // clip all shoreline segments clipShorlineSegments(shoreline, seaBounds); log.info("generating sea, seaBounds=", seaBounds); int minLat = seaBounds.getMinLat(); int maxLat = seaBounds.getMaxLat(); int minLong = seaBounds.getMinLong(); int maxLong = seaBounds.getMaxLong(); Coord nw = new Coord(minLat, minLong); Coord ne = new Coord(minLat, maxLong); Coord sw = new Coord(maxLat, minLong); Coord se = new Coord(maxLat, maxLong); if(shoreline.isEmpty()) { // no sea required // even though there is no sea, generate a land // polygon so that the tile's background colour will // match the land colour on the tiles that do contain // some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); // no matter if the multipolygon option is used it is // only necessary to create a land polygon saver.addWay(land); // nothing more to do return; } long multiId = FakeIdGenerator.makeFakeId(); Relation seaRelation = null; if(generateSeaUsingMP) { log.debug("Generate seabounds relation",multiId); seaRelation = new GeneralRelation(multiId); seaRelation.addTag("type", "multipolygon"); seaRelation.addTag("natural", "sea"); } List<Way> islands = new ArrayList<Way>(); // handle islands (closed shoreline components) first (they're easy) handleIslands(shoreline, seaBounds, islands); // the remaining shoreline segments should intersect the boundary // find the intersection points and store them in a SortedMap SortedMap<EdgeHit, Way> hitMap = findIntesectionPoints(shoreline, seaBounds, seaRelation); // now construct inner ways from these segments boolean shorelineReachesBoundary = createInnerWays(seaBounds, islands, hitMap); if(!shorelineReachesBoundary && roadsReachBoundary) { // try to avoid tiles being flooded by anti-lakes or other // bogus uses of natural=coastline generateSeaBackground = false; } List<Way> antiIslands = removeAntiIslands(seaRelation, islands); if (islands.isEmpty()) { // the tile doesn't contain any islands so we can assume // that it's showing a land mass that contains some // enclosed sea areas - in which case, we don't want a sea // coloured background generateSeaBackground = false; } if (generateSeaBackground) { // the background is sea so all anti-islands should be // contained by land otherwise they won't be visible for (Way ai : antiIslands) { boolean containedByLand = false; for(Way i : islands) { if(i.containsPointsOf(ai)) { containedByLand = true; break; } } if (!containedByLand) { // found an anti-island that is not contained by // land so convert it back into an island ai.deleteTag("natural"); ai.addTag(landTag[0], landTag[1]); if (generateSeaUsingMP) { // create a "inner" way for the island assert seaRelation != null; seaRelation.addElement("inner", ai); } log.warn("Converting anti-island starting at", ai.getPoints().get(0).toOSMURL() , "into an island as it is surrounded by water"); } } long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); // the sea background area must be a little bigger than all // inner land areas. this is a workaround for a mp shortcoming: // mp is not able to combine outer and inner if they intersect // or have overlaying lines // the added area will be clipped later by the style generator sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addPoint(new Coord(sw.getLatitude() + 1, sw.getLongitude() - 1)); sea.addPoint(new Coord(se.getLatitude() + 1, se.getLongitude() + 1)); sea.addPoint(new Coord(ne.getLatitude() - 1, ne.getLongitude() + 1)); sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) { assert seaRelation != null; seaRelation.addElement("outer", sea); } } else { // background is land // generate a land polygon so that the tile's // background colour will match the land colour on the // tiles that do contain some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); saver.addWay(land); if (generateSeaUsingMP) { seaRelation.addElement("inner", land); } } if (generateSeaUsingMP) { SeaPolygonRelation coastRel = saver.createSeaPolyRelation(seaRelation); coastRel.setFloodBlocker(floodblocker); if (floodblocker) { coastRel.setFloodBlockerGap(fbGap); coastRel.setFloodBlockerRatio(fbRatio); coastRel.setFloodBlockerThreshold(fbThreshold); coastRel.setFloodBlockerRules(fbRules.getWayRules()); coastRel.setLandTag(landTag[0], landTag[1]); coastRel.setDebug(fbDebug); } saver.addRelation(coastRel); } }
diff --git a/src/commons/org/codehaus/groovy/grails/plugins/GrailsPluginManagerFactoryBean.java b/src/commons/org/codehaus/groovy/grails/plugins/GrailsPluginManagerFactoryBean.java index 196cf2811..e0ba17ae5 100644 --- a/src/commons/org/codehaus/groovy/grails/plugins/GrailsPluginManagerFactoryBean.java +++ b/src/commons/org/codehaus/groovy/grails/plugins/GrailsPluginManagerFactoryBean.java @@ -1,76 +1,77 @@ /* * Copyright 2004-2006 Graeme Rocher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.plugins; import org.codehaus.groovy.grails.commons.DefaultGrailsApplication; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; /** * A factory bean for loading the GrailsPluginManager instance * * @author Graeme Rocher * @since 0.4 * */ public class GrailsPluginManagerFactoryBean implements FactoryBean, InitializingBean{ private Resource[] pluginFiles = new Resource[0]; private GrailsApplication application; private GrailsPluginManager pluginManager; /** * @param application the application to set */ public void setApplication(GrailsApplication application) { this.application = application; } /** * @param pluginFiles the pluginFiles to set */ public void setPluginFiles(Resource[] pluginFiles) { this.pluginFiles = pluginFiles; } public Object getObject() throws Exception { return this.pluginManager; } public Class getObjectType() { return GrailsPluginManager.class; } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { this.pluginManager = PluginManagerHolder.getPluginManager(); if(pluginManager == null) { pluginManager = new DefaultGrailsPluginManager(pluginFiles, application); PluginManagerHolder.setPluginManager(pluginManager); + pluginManager.loadPlugins(); } this.pluginManager.setApplication(application); this.pluginManager.doArtefactConfiguration(); application.initialise(); } }
true
true
public void afterPropertiesSet() throws Exception { this.pluginManager = PluginManagerHolder.getPluginManager(); if(pluginManager == null) { pluginManager = new DefaultGrailsPluginManager(pluginFiles, application); PluginManagerHolder.setPluginManager(pluginManager); } this.pluginManager.setApplication(application); this.pluginManager.doArtefactConfiguration(); application.initialise(); }
public void afterPropertiesSet() throws Exception { this.pluginManager = PluginManagerHolder.getPluginManager(); if(pluginManager == null) { pluginManager = new DefaultGrailsPluginManager(pluginFiles, application); PluginManagerHolder.setPluginManager(pluginManager); pluginManager.loadPlugins(); } this.pluginManager.setApplication(application); this.pluginManager.doArtefactConfiguration(); application.initialise(); }
diff --git a/src/main/java/water/exec/Env.java b/src/main/java/water/exec/Env.java index 965d0e34f..b2f98eda7 100644 --- a/src/main/java/water/exec/Env.java +++ b/src/main/java/water/exec/Env.java @@ -1,332 +1,332 @@ package water.exec; import java.text.*; import java.util.Arrays; import java.util.HashMap; import water.*; import water.fvec.*; import water.fvec.Vec.VectorGroup; /** Execute a R-like AST, in the context of an H2O Cloud * @author [email protected] */ public class Env extends Iced { // An environment is a classic stack of values, passed into AST's as the // execution state. The 3 types we support are Frames (2-d tables of data), // doubles (which are an optimized form of a 1x1 Frame), and ASTs (which are // 1st class functions). String _key[] = new String[4]; // For top-level globals only, record a frame Key Frame _ary[] = new Frame [4]; // Frame (or null if not a frame) double _d [] = new double[4]; // Double (only if frame & func are null) ASTOp _fcn[] = new ASTOp [4]; // Functions (or null if not a function) int _sp; // Stack pointer // Also a Pascal-style display, one display entry per lexical scope. Slot // zero is the start of the global scope (which contains all global vars like // hex Keys) and always starts at offset 0. int _display[] = new int[4]; int _tod; // Ref Counts for each vector transient final HashMap<Vec,Integer> _refcnt; transient final public StringBuilder _sb; // Holder for print results transient boolean _allow_tmp; // Deep-copy allowed to tmp transient boolean _busy_tmp; // Assert temp is available for use transient Frame _tmp; // The One Big Active Tmp Env() { _key = new String[4]; // Key for Frame _ary = new Frame [4]; // Frame (or null if not a frame) _d = new double[4]; // Double (only if frame & func are null) _fcn = new ASTOp [4]; // Functions (or null if not a function) _display= new int[4]; _refcnt = new HashMap<Vec,Integer>(); _sb = new StringBuilder(); } public int sp() { return _sp; } public boolean isAry() { return _ary[_sp-1] != null; } public boolean isFcn () { return _fcn[_sp-1] != null; } public boolean isDbl () { return !isAry() && !isFcn(); } public boolean isFcn (int i) { return _fcn[_sp+i] != null; } public boolean isAry(int i) { return _ary[_sp+i] != null; } // Peek operators public Frame ary(int i) { Frame fr = _ary[_sp+i]; assert fr != null; return fr; } public ASTOp fcn(int i) { ASTOp op = _fcn[_sp+i]; assert op != null; return op; } public double dbl(int i) { double d = _d [_sp+i]; return d; } // Load the nth Id/variable from the named lexical scope, typed as a Frame public Frame frId(int d, int n) { int idx = _display[_tod-d]+n; assert _ary[idx]!=null; return _ary[idx]; } // Push k empty slots void push( int slots ) { assert 0 <= slots && slots < 1000; int len = _d.length; _sp += slots; while( _sp > len ) { _key= Arrays.copyOf(_key,len<<1); _ary= Arrays.copyOf(_ary,len<<1); _d = Arrays.copyOf(_d ,len<<1); _fcn= Arrays.copyOf(_fcn,len<<=1); } } void push( Frame fr ) { push(1); _ary[_sp-1] = addRef(fr) ; assert check_refcnt(fr.anyVec()); } void push( double d ) { push(1); _d [_sp-1] = d ; } void push( ASTOp fcn) { push(1); _fcn[_sp-1] = addRef(fcn); } void push( Frame fr, String key ) { push(fr); _key[_sp-1]=key; } // Copy from display offset d, nth slot void push_slot( int d, int n ) { assert d==0; // Should use a fcn's closure for d>1 int idx = _display[_tod-d]+n; push(1); _ary[_sp-1] = addRef(_ary[idx]); _d [_sp-1] = _d [idx]; _fcn[_sp-1] = addRef(_fcn[idx]); assert _ary[0]==null || check_refcnt(_ary[0].anyVec()); } void push_slot( int d, int n, Env global ) { assert _refcnt==null; // Should use a fcn's closure for d>1 int idx = _display[_tod-d]+n; int gidx = global._sp; global.push(1); global._ary[gidx] = global.addRef(_ary[idx]); global._d [gidx] = _d [idx] ; global._fcn[gidx] = global.addRef(_fcn[idx]); assert global.check_refcnt(global._ary[0].anyVec()); } // Copy from TOS into a slot. Does NOT pop results. void tos_into_slot( int d, int n, String id ) { // In a copy-on-modify language, only update the local scope, or return val assert d==0 || (d==1 && _display[_tod]==n+1); int idx = _display[_tod-d]+n; subRef(_ary[idx], _key[idx]); subRef(_fcn[idx]); _ary[idx] = addRef(_ary[_sp-1]); _d [idx] = _d [_sp-1] ; _fcn[idx] = addRef(_fcn[_sp-1]); if( d==0 ) _key[idx] = id; assert _ary[0]== null || check_refcnt(_ary[0].anyVec()); } // Copy from TOS into stack. Pop's all intermediate. // Example: pop_into_stk(-4) BEFORE: A,B,C,D,TOS AFTER: A,TOS void pop_into_stk( int x ) { assert x < 0; subRef(_ary[_sp+x], _key[_sp+x]); // Nuke out old stuff subRef(_fcn[_sp+x]); _ary[_sp+x] = _ary[_sp-1]; // Copy without changing ref cnt _fcn[_sp+x] = _fcn[_sp-1]; _d [_sp+x] = _d [_sp-1]; _sp--; x++; // Pop without changing ref cnt while( x++ < -1 ) pop(); } // Push a scope, leaving room for passed args int pushScope(int args) { assert fcn(-args-1) instanceof ASTFunc; // Expect a function under the args return _display[++_tod] = _sp-args; } // Grab the function for nested scope d ASTFunc fcnScope( int d ) { return (ASTFunc)_fcn[_display[_tod]-1]; } // Pop a slot. Lowers refcnts on vectors. Always leaves stack null behind // (to avoid dangling pointers stretching lifetimes). void pop( Env global ) { assert _sp > _display[_tod]; // Do not over-pop current scope _sp--; _fcn[_sp]=global.subRef(_fcn[_sp]); _ary[_sp]=global.subRef(_ary[_sp],_key[_sp]); assert _sp==0 || _ary[0]==null || check_refcnt(_ary[0].anyVec()); } void pop( ) { pop(this); } void pop( int n ) { for( int i=0; i<n; i++ ) pop(); } void popScope() { assert _tod > 0; // Something to pop? assert _sp >= _display[_tod]; // Did not over-pop already? while( _sp > _display[_tod] ) pop(); _tod--; } // Pop & return a Frame or Fcn; ref-cnt of all things remains unchanged. // Caller is responsible for tracking lifetime. public double popDbl() { assert isDbl(); return _d [--_sp]; } public ASTOp popFcn() { assert isFcn(); ASTOp op = _fcn[--_sp]; _fcn[_sp]=null; return op; } public Frame popAry() { assert isAry(); Frame fr = _ary[--_sp]; _ary[_sp]=null; assert allAlive(fr); return fr; } public String key() { return _key[_sp]; } // Replace a function invocation with it's result public void poppush(double d) { pop(); push(d); } // Capture the current environment & return it (for some closure's future execution). Env capture( ) { return new Env(this); } private Env( Env e ) { _sp = e._sp; _key= Arrays.copyOf(e._key,_sp); _ary= Arrays.copyOf(e._ary,_sp); _d = Arrays.copyOf(e._d ,_sp); _fcn= Arrays.copyOf(e._fcn,_sp); _tod= e._tod; _display = Arrays.copyOf(e._display,_tod+1); // All other fields are ignored/zero _refcnt = null; _sb = null; } // Nice assert boolean allAlive(Frame fr) { for( Vec vec : fr.vecs() ) assert _refcnt.get(vec) > 0; return true; } public Futures subRef( Vec vec, Futures fs ) { int cnt = _refcnt.get(vec)-1; if( cnt > 0 ) _refcnt.put(vec,cnt); else { if( fs == null ) fs = new Futures(); Vec vmaster = vec.masterVec(); UKV.remove(vec._key,fs); _refcnt.remove(vec); if( vmaster != null ) subRef(vmaster,fs); } return fs; } // Lower the refcnt on all vecs in this frame. // Immediately free all vecs with zero count. // Always return a null. public Frame subRef( Frame fr, String key ) { if( fr == null ) return null; Futures fs = null; for( Vec vec : fr.vecs() ) fs = subRef(vec,fs); if( key != null && fs != null ) UKV.remove(Key.make(key),fs); if( fs != null ) fs.blockForPending(); return null; } // Lower refcounts on all vecs captured in the inner environment public ASTOp subRef( ASTOp op ) { if( op == null ) return null; if( !(op instanceof ASTFunc) ) return null; ASTFunc fcn = (ASTFunc)op; if( fcn._env != null ) fcn._env.subRef(this); else System.out.println("Popping fcn object, never executed no environ capture"); return null; } Vec addRef( Vec vec ) { Integer I = _refcnt.get(vec); assert I==null || I>0; assert vec.length() == 0 || (vec.at(0) > 0 || vec.at(0) <= 0 || Double.isNaN(vec.at(0))); _refcnt.put(vec,I==null?1:I+1); return vec; } // Add a refcnt to all vecs in this frame Frame addRef( Frame fr ) { if( fr == null ) return null; for( Vec vec : fr.vecs() ) addRef(vec); return fr; } ASTOp addRef( ASTOp op ) { if( op == null ) return null; if( !(op instanceof ASTFunc) ) return op; ASTFunc fcn = (ASTFunc)op; if( fcn._env != null ) fcn._env.addRef(this); else System.out.println("Pushing fcn object, never executed no environ capture"); return op; } private void addRef(Env global) { for( int i=0; i<_sp; i++ ) { if( _ary[i] != null ) global.addRef(_ary[i]); if( _fcn[i] != null ) global.addRef(_fcn[i]); } } private void subRef(Env global) { for( int i=0; i<_sp; i++ ) { if( _ary[i] != null ) global.subRef(_ary[i],_key[i]); if( _fcn[i] != null ) global.subRef(_fcn[i]); } } // Remove everything public void remove() { // Remove all shallow scopes - while( _tod > 1 ) popScope(); + while( _tod > 0 ) popScope(); // Push changes at the outer scope into the K/V store while( _sp > 0 ) { if( isAry() && _key[_sp-1] != null ) { // Has a K/V mapping? Frame fr = popAry(); // Pop w/out lower refcnt & delete Frame fr2=fr; String skey = key(); for( int i=0; i<fr.numCols(); i++ ) { Vec v = fr.vecs()[i]; int refcnt = _refcnt.get(v); assert refcnt > 0; if( refcnt > 1 ) { // Need a deep-copy now if( fr2==fr ) fr2 = new Frame(fr); Vec v2 = new Frame(v).deepSlice(null,null).vecs()[0]; fr2.replace(i,v2); // Replace with private deep-copy subRef(v,null); // Now lower refcnt for good assertions } // But not down to zero (do not delete items in global scope) } UKV.put(Key.make(_key[_sp]),fr2); } else pop(); } } // Done writing into all things. Allow rollups. public void postWrite() { for( Vec vec : _refcnt.keySet() ) vec.postWrite(); } // Count references the "hard way" - used to check refcnting math. int compute_refcnt( Vec vec ) { int cnt=0; for( int i=0; i<_sp; i++ ) if( _ary[i] != null && _ary[i].find(vec) != -1 ) cnt++; else if( _fcn[i] != null && (_fcn[i] instanceof ASTFunc) ) cnt += ((ASTFunc)_fcn[i])._env.compute_refcnt(vec); return cnt; } boolean check_refcnt( Vec vec ) { Integer I = _refcnt.get(vec); int cnt0 = I==null ? 0 : I; int cnt1 = compute_refcnt(vec); if( cnt0==cnt1 ) return true; System.out.println("Refcnt is "+cnt0+" but computed as "+cnt1); return false; } // Pop and return the result as a string public String resultString( ) { assert _tod==0 : "Still have lexical scopes past the global"; String s = toString(_sp-1,true); pop(); return s; } public String toString(int i, boolean verbose_fcn) { if( _ary[i] != null ) return _ary[i].numRows()+"x"+_ary[i].numCols(); else if( _fcn[i] != null ) return _fcn[i].toString(verbose_fcn); return Double.toString(_d[i]); } @Override public String toString() { String s="{"; for( int i=0; i<_sp; i++ ) s += toString(i,false)+","; return s+"}"; } }
true
true
public void remove() { // Remove all shallow scopes while( _tod > 1 ) popScope(); // Push changes at the outer scope into the K/V store while( _sp > 0 ) { if( isAry() && _key[_sp-1] != null ) { // Has a K/V mapping? Frame fr = popAry(); // Pop w/out lower refcnt & delete Frame fr2=fr; String skey = key(); for( int i=0; i<fr.numCols(); i++ ) { Vec v = fr.vecs()[i]; int refcnt = _refcnt.get(v); assert refcnt > 0; if( refcnt > 1 ) { // Need a deep-copy now if( fr2==fr ) fr2 = new Frame(fr); Vec v2 = new Frame(v).deepSlice(null,null).vecs()[0]; fr2.replace(i,v2); // Replace with private deep-copy subRef(v,null); // Now lower refcnt for good assertions } // But not down to zero (do not delete items in global scope) } UKV.put(Key.make(_key[_sp]),fr2); } else pop(); } }
public void remove() { // Remove all shallow scopes while( _tod > 0 ) popScope(); // Push changes at the outer scope into the K/V store while( _sp > 0 ) { if( isAry() && _key[_sp-1] != null ) { // Has a K/V mapping? Frame fr = popAry(); // Pop w/out lower refcnt & delete Frame fr2=fr; String skey = key(); for( int i=0; i<fr.numCols(); i++ ) { Vec v = fr.vecs()[i]; int refcnt = _refcnt.get(v); assert refcnt > 0; if( refcnt > 1 ) { // Need a deep-copy now if( fr2==fr ) fr2 = new Frame(fr); Vec v2 = new Frame(v).deepSlice(null,null).vecs()[0]; fr2.replace(i,v2); // Replace with private deep-copy subRef(v,null); // Now lower refcnt for good assertions } // But not down to zero (do not delete items in global scope) } UKV.put(Key.make(_key[_sp]),fr2); } else pop(); } }
diff --git a/libraries/emulatorview/src/jackpal/androidterm/emulatorview/UnicodeTranscript.java b/libraries/emulatorview/src/jackpal/androidterm/emulatorview/UnicodeTranscript.java index 584b643..8254403 100644 --- a/libraries/emulatorview/src/jackpal/androidterm/emulatorview/UnicodeTranscript.java +++ b/libraries/emulatorview/src/jackpal/androidterm/emulatorview/UnicodeTranscript.java @@ -1,1007 +1,1007 @@ /* * Copyright (C) 2011 Steven Luo * * 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 jackpal.androidterm.emulatorview; import android.util.Log; import jackpal.androidterm.emulatorview.compat.AndroidCharacterCompat; /** * A backing store for a TranscriptScreen. * * The text is stored as a circular buffer of rows. There are two types of * row: * - "basic", which is a char[] array used to store lines which consist * entirely of regular-width characters (no combining characters, zero-width * characters, East Asian double-width characters, etc.) in the BMP; and * - "full", which is a char[] array with extra trappings which can be used to * store a line containing any valid Unicode sequence. An array of short[] * is used to store the "offset" at which each column starts; for example, * if column 20 starts at index 23 in the array, then mOffset[20] = 3. * * Style information is stored in a separate circular buffer of StyleRows. * * Rows are allocated on demand, when a character is first stored into them. * A "basic" row is allocated unless the store which triggers the allocation * requires a "full" row. "Basic" rows are converted to "full" rows when * needed. There is no conversion in the other direction -- a "full" row * stays that way even if it contains only regular-width BMP characters. */ class UnicodeTranscript { private static final String TAG = "UnicodeTranscript"; private Object[] mLines; private StyleRow[] mColor; private boolean[] mLineWrap; private int mTotalRows; private int mScreenRows; private int mColumns; private int mActiveTranscriptRows = 0; private int mDefaultStyle = 0; private int mScreenFirstRow = 0; private char[] tmpLine; private StyleRow tmpColor; public UnicodeTranscript(int columns, int totalRows, int screenRows, int defaultStyle) { mColumns = columns; mTotalRows = totalRows; mScreenRows = screenRows; mLines = new Object[totalRows]; mColor = new StyleRow[totalRows]; mLineWrap = new boolean[totalRows]; tmpColor = new StyleRow(defaultStyle, mColumns); mDefaultStyle = defaultStyle; } public void setDefaultStyle(int defaultStyle) { mDefaultStyle = defaultStyle; } public int getDefaultStyle() { return mDefaultStyle; } public int getActiveTranscriptRows() { return mActiveTranscriptRows; } public int getActiveRows() { return mActiveTranscriptRows + mScreenRows; } /** * Convert a row value from the public external coordinate system to our * internal private coordinate system. * External coordinate system: * -mActiveTranscriptRows to mScreenRows-1, with the screen being * 0..mScreenRows-1 * Internal coordinate system: the mScreenRows lines starting at * mScreenFirstRow comprise the screen, while the mActiveTranscriptRows * lines ending at mScreenRows-1 form the transcript (as a circular * buffer). * * @param extRow a row in the external coordinate system. * @return The row corresponding to the input argument in the private * coordinate system. */ private int externalToInternalRow(int extRow) { if (extRow < -mActiveTranscriptRows || extRow > mScreenRows) { String errorMessage = "externalToInternalRow "+ extRow + " " + mScreenRows + " " + mActiveTranscriptRows; Log.e(TAG, errorMessage); throw new IllegalArgumentException(errorMessage); } if (extRow >= 0) { return (mScreenFirstRow + extRow) % mTotalRows; } else { if (-extRow > mScreenFirstRow) { return mTotalRows + mScreenFirstRow + extRow; } else { return mScreenFirstRow + extRow; } } } public void setLineWrap(int row) { mLineWrap[externalToInternalRow(row)] = true; } public boolean getLineWrap(int row) { return mLineWrap[externalToInternalRow(row)]; } /** * Resize the screen which this transcript backs. Currently, this * only works if the number of columns does not change. * * @param newColumns The number of columns the screen should have. * @param newRows The number of rows the screen should have. * @param cursor An int[2] containing the cursor location. * @return Whether or not the resize succeeded. If the resize failed, * the caller may "resize" the screen by copying out all the data * and placing it into a new transcript of the correct size. */ public boolean resize(int newColumns, int newRows, int[] cursor) { if (newColumns != mColumns || newRows > mTotalRows) { return false; } int screenRows = mScreenRows; int activeTranscriptRows = mActiveTranscriptRows; int shift = screenRows - newRows; if (shift < -activeTranscriptRows) { // We want to add blank lines at the bottom instead of at the top Object[] lines = mLines; Object[] color = mColor; boolean[] lineWrap = mLineWrap; int screenFirstRow = mScreenFirstRow; int totalRows = mTotalRows; for (int i = 0; i < activeTranscriptRows - shift; ++i) { int index = (screenFirstRow + screenRows + i) % totalRows; lines[index] = null; color[index] = null; lineWrap[index] = false; } shift = -activeTranscriptRows; } else if (shift > 0 && cursor[1] != screenRows - 1) { /* When shrinking the screen, we want to hide blank lines at the bottom in preference to lines at the top of the screen */ Object[] lines = mLines; for (int i = screenRows - 1; i > cursor[1]; --i) { int index = externalToInternalRow(i); if (lines[index] == null) { // Line is blank --shift; if (shift == 0) { break; } else { continue; } } char[] line; if (lines[index] instanceof char[]) { line = (char[]) lines[index]; } else { line = ((FullUnicodeLine) lines[index]).getLine(); } int len = line.length; int j; for (j = 0; j < len; ++j) { if (line[j] == 0) { // We've reached the end of the line j = len; break; } else if (line[j] != ' ') { // Line is not blank break; } } if (j == len) { // Line is blank --shift; if (shift == 0) { break; } else { continue; } } else { // Line not blank -- we keep it and everything above break; } } } if (shift > 0 || (shift < 0 && mScreenFirstRow >= -shift)) { // All we're doing is moving the top of the screen. mScreenFirstRow = (mScreenFirstRow + shift) % mTotalRows; } else if (shift < 0) { // The new top of the screen wraps around the top of the array. mScreenFirstRow = mTotalRows + mScreenFirstRow + shift; } if (mActiveTranscriptRows + shift < 0) { mActiveTranscriptRows = 0; } else { mActiveTranscriptRows += shift; } cursor[1] -= shift; mScreenRows = newRows; return true; } /** * Block copy lines and associated metadata from one location to another * in the circular buffer, taking wraparound into account. * * @param src The first line to be copied. * @param len The number of lines to be copied. * @param shift The offset of the destination from the source. */ private void blockCopyLines(int src, int len, int shift) { int totalRows = mTotalRows; int dst; if (src + shift >= 0) { dst = (src + shift) % totalRows; } else { dst = totalRows + src + shift; } if (src + len <= totalRows && dst + len <= totalRows) { // Fast path -- no wraparound System.arraycopy(mLines, src, mLines, dst, len); System.arraycopy(mColor, src, mColor, dst, len); System.arraycopy(mLineWrap, src, mLineWrap, dst, len); return; } if (shift < 0) { // Do the copy from top to bottom for (int i = 0; i < len; ++i) { mLines[(dst + i) % totalRows] = mLines[(src + i) % totalRows]; mColor[(dst + i) % totalRows] = mColor[(src + i) % totalRows]; mLineWrap[(dst + i) % totalRows] = mLineWrap[(src + i) % totalRows]; } } else { // Do the copy from bottom to top for (int i = len - 1; i >= 0; --i) { mLines[(dst + i) % totalRows] = mLines[(src + i) % totalRows]; mColor[(dst + i) % totalRows] = mColor[(src + i) % totalRows]; mLineWrap[(dst + i) % totalRows] = mLineWrap[(src + i) % totalRows]; } } } /** * Scroll the screen down one line. To scroll the whole screen of a 24 line * screen, the arguments would be (0, 24). * * @param topMargin First line that is scrolled. * @param bottomMargin One line after the last line that is scrolled. * @param style the style for the newly exposed line. */ public void scroll(int topMargin, int bottomMargin, int style) { // Separate out reasons so that stack crawls help us // figure out which condition was violated. if (topMargin > bottomMargin - 1) { throw new IllegalArgumentException(); } if (topMargin < 0) { throw new IllegalArgumentException(); } if (bottomMargin > mScreenRows) { throw new IllegalArgumentException(); } int screenRows = mScreenRows; int totalRows = mTotalRows; if (topMargin == 0 && bottomMargin == screenRows) { // Fast path -- scroll the entire screen mScreenFirstRow = (mScreenFirstRow + 1) % totalRows; if (mActiveTranscriptRows < totalRows - screenRows) { ++mActiveTranscriptRows; } // Blank the bottom margin int blankRow = externalToInternalRow(bottomMargin - 1); mLines[blankRow] = null; mColor[blankRow] = new StyleRow(style, mColumns); mLineWrap[blankRow] = false; return; } int screenFirstRow = mScreenFirstRow; int topMarginInt = externalToInternalRow(topMargin); int bottomMarginInt = externalToInternalRow(bottomMargin); /* Save the scrolled line, move the lines above it on the screen down one line, move the lines on screen below the bottom margin down one line, then insert the scrolled line into the transcript */ Object[] lines = mLines; StyleRow[] color = mColor; boolean[] lineWrap = mLineWrap; Object scrollLine = lines[topMarginInt]; StyleRow scrollColor = color[topMarginInt]; boolean scrollLineWrap = lineWrap[topMarginInt]; blockCopyLines(screenFirstRow, topMargin, 1); blockCopyLines(bottomMarginInt, screenRows - bottomMargin, 1); lines[screenFirstRow] = scrollLine; color[screenFirstRow] = scrollColor; lineWrap[screenFirstRow] = scrollLineWrap; // Update the screen location mScreenFirstRow = (screenFirstRow + 1) % totalRows; if (mActiveTranscriptRows < totalRows - screenRows) { ++mActiveTranscriptRows; } // Blank the bottom margin int blankRow = externalToInternalRow(bottomMargin - 1); lines[blankRow] = null; color[blankRow] = new StyleRow(style, mColumns); lineWrap[blankRow] = false; return; } /** * Block copy characters from one position in the screen to another. The two * positions can overlap. All characters of the source and destination must * be within the bounds of the screen, or else an InvalidParameterException * will be thrown. * * @param sx source X coordinate * @param sy source Y coordinate * @param w width * @param h height * @param dx destination X coordinate * @param dy destination Y coordinate */ public void blockCopy(int sx, int sy, int w, int h, int dx, int dy) { if (sx < 0 || sx + w > mColumns || sy < 0 || sy + h > mScreenRows || dx < 0 || dx + w > mColumns || dy < 0 || dy + h > mScreenRows) { throw new IllegalArgumentException(); } Object[] lines = mLines; StyleRow[] color = mColor; if (sy > dy) { // Move in increasing order for (int y = 0; y < h; y++) { int srcRow = externalToInternalRow(sy + y); int dstRow = externalToInternalRow(dy + y); if (lines[srcRow] instanceof char[] && lines[dstRow] instanceof char[]) { System.arraycopy(lines[srcRow], sx, lines[dstRow], dx, w); } else { // XXX There has to be a faster way to do this ... int extDstRow = dy + y; char[] tmp = getLine(sy + y, sx, sx + w); if (tmp == null) { // Source line was blank blockSet(dx, extDstRow, w, 1, ' ', mDefaultStyle); continue; } char cHigh = 0; int x = 0; int columns = mColumns; for (int i = 0; i < tmp.length; ++i) { if (tmp[i] == 0 || dx + x >= columns) { break; } if (Character.isHighSurrogate(tmp[i])) { cHigh = tmp[i]; continue; } else if (Character.isLowSurrogate(tmp[i])) { int codePoint = Character.toCodePoint(cHigh, tmp[i]); setChar(dx + x, extDstRow, codePoint); x += charWidth(codePoint); } else { setChar(dx + x, extDstRow, tmp[i]); x += charWidth(tmp[i]); } } } color[srcRow].copy(sx, color[dstRow], dx, w); } } else { // Move in decreasing order for (int y = 0; y < h; y++) { int y2 = h - (y + 1); int srcRow = externalToInternalRow(sy + y2); int dstRow = externalToInternalRow(dy + y2); if (lines[srcRow] instanceof char[] && lines[dstRow] instanceof char[]) { System.arraycopy(lines[srcRow], sx, lines[dstRow], dx, w); } else { int extDstRow = dy + y2; char[] tmp = getLine(sy + y2, sx, sx + w); if (tmp == null) { // Source line was blank blockSet(dx, extDstRow, w, 1, ' ', mDefaultStyle); continue; } char cHigh = 0; int x = 0; int columns = mColumns; for (int i = 0; i < tmp.length; ++i) { if (tmp[i] == 0 || dx + x >= columns) { break; } if (Character.isHighSurrogate(tmp[i])) { cHigh = tmp[i]; continue; } else if (Character.isLowSurrogate(tmp[i])) { int codePoint = Character.toCodePoint(cHigh, tmp[i]); setChar(dx + x, extDstRow, codePoint); x += charWidth(codePoint); } else { setChar(dx + x, extDstRow, tmp[i]); x += charWidth(tmp[i]); } } } color[srcRow].copy(sx, color[dstRow], dx, w); } } } /** * Block set characters. All characters must be within the bounds of the * screen, or else and InvalidParemeterException will be thrown. Typically * this is called with a "val" argument of 32 to clear a block of * characters. * * @param sx source X * @param sy source Y * @param w width * @param h height * @param val value to set. */ public void blockSet(int sx, int sy, int w, int h, int val, int style) { if (sx < 0 || sx + w > mColumns || sy < 0 || sy + h > mScreenRows) { Log.e(TAG, "illegal arguments! " + sx + " " + sy + " " + w + " " + h + " " + val + " " + mColumns + " " + mScreenRows); throw new IllegalArgumentException(); } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { setChar(sx + x, sy + y, val, style); } } } /** * Gives the display width of the code point in a monospace font. * * Nonspacing combining marks, format characters, and control characters * have display width zero. East Asian fullwidth and wide characters * have display width two. All other characters have display width one. * * Known issues: * - Proper support for East Asian wide characters requires API >= 8. * - Results are incorrect for individual Hangul jamo (a syllable block * of jamo should be one unit with width 2). This does not affect * precomposed Hangul syllables. * - Assigning all East Asian "ambiguous" characters a width of 1 may not * be correct if Android renders those characters as wide in East Asian * context (as the Unicode standard permits). * * @param codePoint A Unicode code point. * @return The display width of the Unicode code point. */ public static int charWidth(int codePoint) { // Early out for ASCII printable characters if (codePoint > 31 && codePoint < 127) { return 1; } /* HACK: We're using ASCII ESC to save the location of the cursor across screen resizes, so we need to pretend that it has width 1 */ if (codePoint == 27) { return 1; } switch (Character.getType(codePoint)) { case Character.CONTROL: case Character.FORMAT: case Character.NON_SPACING_MARK: case Character.ENCLOSING_MARK: return 0; } if (Character.charCount(codePoint) == 1) { // Android's getEastAsianWidth() only works for BMP characters switch (AndroidCharacterCompat.getEastAsianWidth((char) codePoint)) { case AndroidCharacterCompat.EAST_ASIAN_WIDTH_FULL_WIDTH: case AndroidCharacterCompat.EAST_ASIAN_WIDTH_WIDE: return 2; } } else { // Outside the BMP, only the ideographic planes contain wide chars switch ((codePoint >> 16) & 0xf) { case 2: // Supplementary Ideographic Plane case 3: // Tertiary Ideographic Plane return 2; } } return 1; } public static int charWidth(char cHigh, char cLow) { return charWidth(Character.toCodePoint(cHigh, cLow)); } /** * Gives the display width of a code point in a char array * in a monospace font. * * @param chars The array containing the code point in question. * @param index The index into the array at which the code point starts. * @return The display width of the Unicode code point. */ public static int charWidth(char[] chars, int index) { char c = chars[index]; if (Character.isHighSurrogate(c)) { return charWidth(c, chars[index+1]); } else { return charWidth(c); } } /** * Get the contents of a line (or part of a line) of the transcript. * * The char[] array returned may be part of the internal representation * of the line -- make a copy first if you want to modify it. The last * character requested will be followed by a NUL; the contents of the rest * of the array could potentially be garbage. * * @param row The row number to get (-mActiveTranscriptRows..mScreenRows-1) * @param x1 The first screen position that's wanted * @param x2 One after the last screen position that's wanted * @return A char[] array containing the requested contents */ public char[] getLine(int row, int x1, int x2) { if (row < -mActiveTranscriptRows || row > mScreenRows-1) { throw new IllegalArgumentException(); } int columns = mColumns; row = externalToInternalRow(row); if (mLines[row] == null) { // Line is blank return null; } if (mLines[row] instanceof char[]) { // Line contains only regular-width BMP characters if (x1 == 0 && x2 == columns) { // Want the whole row? Easy. return (char[]) mLines[row]; } else { if (tmpLine == null || tmpLine.length < columns + 1) { tmpLine = new char[columns+1]; } int length = x2 - x1; System.arraycopy(mLines[row], x1, tmpLine, 0, length); tmpLine[length] = 0; return tmpLine; } } // Figure out how long the array needs to be FullUnicodeLine line = (FullUnicodeLine) mLines[row]; char[] rawLine = line.getLine(); x1 = line.findStartOfColumn(x1); if (x2 < columns) { x2 = line.findStartOfColumn(x2); } else { x2 = line.getSpaceUsed(); } int length = x2 - x1; if (tmpLine == null || tmpLine.length < length + 1) { tmpLine = new char[length+1]; } System.arraycopy(rawLine, x1, tmpLine, 0, length); tmpLine[length] = 0; return tmpLine; } public char[] getLine(int row) { return getLine(row, 0, mColumns); } /** * Get color/formatting information for a particular line. * The returned object may be a pointer to a temporary buffer, only good * until the next call to getLineColor. */ public StyleRow getLineColor(int row, int x1, int x2) { if (row < -mActiveTranscriptRows || row > mScreenRows-1) { throw new IllegalArgumentException(); } row = externalToInternalRow(row); StyleRow color = mColor[row]; StyleRow tmp = tmpColor; if (color != null) { if (x1 == 0 && x2 == mColumns) { return color; } color.copy(x1, tmp, 0, x2-x1); return tmp; } else { return null; } } public StyleRow getLineColor(int row) { return getLineColor(row, 0, mColumns); } public boolean getChar(int row, int column) { return getChar(row, column, 0); } public boolean getChar(int row, int column, int charIndex) { return getChar(row, column, charIndex, new char[1], 0); } /** * Get a character at a specific position in the transcript. * * @param row The row of the character to get. * @param column The column of the character to get. * @param charIndex The index of the character in the column to get * (0 for the first character, 1 for the next, etc.) * @param out The char[] array into which the character will be placed. * @param offset The offset in the array at which the character will be placed. * @return Whether or not there are characters following this one in the column. */ public boolean getChar(int row, int column, int charIndex, char[] out, int offset) { if (row < -mActiveTranscriptRows || row > mScreenRows-1) { throw new IllegalArgumentException(); } row = externalToInternalRow(row); if (mLines[row] instanceof char[]) { // Fast path: all regular-width BMP chars in the row char[] line = (char[]) mLines[row]; out[offset] = line[column]; return false; } FullUnicodeLine line = (FullUnicodeLine) mLines[row]; return line.getChar(column, charIndex, out, offset); } private boolean isBasicChar(int codePoint) { return !(charWidth(codePoint) != 1 || Character.charCount(codePoint) != 1); } private char[] allocateBasicLine(int row, int columns) { char[] line = new char[columns]; // Fill the line with blanks for (int i = 0; i < columns; ++i) { line[i] = ' '; } mLines[row] = line; if (mColor[row] == null) { mColor[row] = new StyleRow(0, columns); } return line; } private FullUnicodeLine allocateFullLine(int row, int columns) { FullUnicodeLine line = new FullUnicodeLine(columns); mLines[row] = line; if (mColor[row] == null) { mColor[row] = new StyleRow(0, columns); } return line; } public boolean setChar(int column, int row, int codePoint, int style) { if (!setChar(column, row, codePoint)) { return false; } row = externalToInternalRow(row); mColor[row].set(column, style); return true; } public boolean setChar(int column, int row, int codePoint) { if (row >= mScreenRows || column >= mColumns) { Log.e(TAG, "illegal arguments! " + row + " " + column + " " + mScreenRows + " " + mColumns); throw new IllegalArgumentException(); } row = externalToInternalRow(row); /* * Whether data contains non-BMP or characters with charWidth != 1 * 0 - false; 1 - true; -1 - undetermined */ int basicMode = -1; // Allocate a row on demand if (mLines[row] == null) { if (isBasicChar(codePoint)) { allocateBasicLine(row, mColumns); basicMode = 1; } else { allocateFullLine(row, mColumns); basicMode = 0; } } if (mLines[row] instanceof char[]) { char[] line = (char[]) mLines[row]; if (basicMode == -1) { if (isBasicChar(codePoint)) { basicMode = 1; } else { basicMode = 0; } } if (basicMode == 1) { // Fast path -- just put the char in the array line[column] = (char) codePoint; return true; } // Need to switch to the full-featured mode mLines[row] = new FullUnicodeLine(line); } FullUnicodeLine line = (FullUnicodeLine) mLines[row]; line.setChar(column, codePoint); return true; } } /* * A representation of a line that's capable of handling non-BMP characters, * East Asian wide characters, and combining characters. * * The text of the line is stored in an array of char[], allowing easy * conversion to a String and/or reuse by other string-handling functions. * An array of short[] is used to keep track of the difference between a column * and the starting index corresponding to its contents in the char[] array (so * if column 42 starts at index 45 in the char[] array, the offset stored is 3). * Column 0 always starts at index 0 in the char[] array, so we use that * element of the array to keep track of how much of the char[] array we're * using at the moment. */ class FullUnicodeLine { private static final float SPARE_CAPACITY_FACTOR = 1.5f; private char[] mText; private short[] mOffset; private int mColumns; public FullUnicodeLine(int columns) { commonConstructor(columns); char[] text = mText; // Fill in the line with blanks for (int i = 0; i < columns; ++i) { text[i] = ' '; } // Store the space used mOffset[0] = (short) columns; } public FullUnicodeLine(char[] basicLine) { commonConstructor(basicLine.length); System.arraycopy(basicLine, 0, mText, 0, mColumns); // Store the space used mOffset[0] = (short) basicLine.length; } private void commonConstructor(int columns) { mColumns = columns; mOffset = new short[columns]; mText = new char[(int)(SPARE_CAPACITY_FACTOR*columns)]; } public int getSpaceUsed() { return mOffset[0]; } public char[] getLine() { return mText; } public int findStartOfColumn(int column) { if (column == 0) { return 0; } else { return column + mOffset[column]; } } public boolean getChar(int column, int charIndex, char[] out, int offset) { int pos = findStartOfColumn(column); int length; if (column + 1 < mColumns) { length = findStartOfColumn(column + 1) - pos; } else { length = getSpaceUsed() - pos; } if (charIndex >= length) { throw new IllegalArgumentException(); } out[offset] = mText[pos + charIndex]; return (charIndex + 1 < length); } public void setChar(int column, int codePoint) { int columns = mColumns; if (column < 0 || column >= columns) { throw new IllegalArgumentException(); } char[] text = mText; short[] offset = mOffset; int spaceUsed = offset[0]; int pos = findStartOfColumn(column); int charWidth = UnicodeTranscript.charWidth(codePoint); int oldCharWidth = UnicodeTranscript.charWidth(text, pos); // Get the number of elements in the mText array this column uses now int oldLen; if (column + oldCharWidth < columns) { oldLen = findStartOfColumn(column+oldCharWidth) - pos; } else { oldLen = spaceUsed - pos; } // Find how much space this column will need int newLen = Character.charCount(codePoint); if (charWidth == 0) { /* Combining characters are added to the contents of the column instead of overwriting them, so that they modify the existing contents */ newLen += oldLen; } int shift = newLen - oldLen; // Shift the rest of the line right to make room if necessary if (shift > 0) { if (spaceUsed + shift > text.length) { // We need to grow the array char[] newText = new char[text.length + columns]; System.arraycopy(text, 0, newText, 0, pos); System.arraycopy(text, pos + oldLen, newText, pos + newLen, spaceUsed - pos - oldLen); mText = text = newText; } else { System.arraycopy(text, pos + oldLen, text, pos + newLen, spaceUsed - pos - oldLen); } } // Store the character if (charWidth > 0) { Character.toChars(codePoint, text, pos); } else { /* Store a combining character at the end of the existing contents, so that it modifies them */ Character.toChars(codePoint, text, pos + oldLen); } // Shift the rest of the line left to eliminate gaps if necessary if (shift < 0) { System.arraycopy(text, pos + oldLen, text, pos + newLen, spaceUsed - pos - oldLen); } // Update space used if (shift != 0) { spaceUsed += shift; offset[0] = (short) spaceUsed; } /* * Handle cases where charWidth changes * width 1 -> width 2: should clobber the contents of the next * column (if next column contains wide char, need to pad with a space) * width 2 -> width 1: pad with a space after the new character */ if (oldCharWidth == 2 && charWidth == 1) { // Pad with a space int nextPos = pos + newLen; if (spaceUsed + 1 > text.length) { // Array needs growing char[] newText = new char[text.length + columns]; System.arraycopy(text, 0, newText, 0, nextPos); System.arraycopy(text, nextPos, newText, nextPos + 1, spaceUsed - nextPos); mText = text = newText; } else { System.arraycopy(text, nextPos, text, nextPos + 1, spaceUsed - nextPos); } text[nextPos] = ' '; // Update space used ++offset[0]; // Correct the offset for the next column to reflect width change if (column == 0) { offset[1] = (short) (newLen - 1); } else if (column + 1 < columns) { offset[column + 1] = (short) (offset[column] + newLen - 1); } ++column; ++shift; } else if (oldCharWidth == 1 && charWidth == 2) { if (column == columns - 1) { // A width 2 character doesn't fit in the last column. text[pos] = ' '; offset[0] = (short) (pos + 1); shift = 0; } else if (column == columns - 2) { // Correct offset for the next column to reflect width change offset[column + 1] = (short) (offset[column] - 1); // Truncate the line after this character. offset[0] = (short) (pos + newLen); shift = 0; } else { // Overwrite the contents of the next column. int nextPos = pos + newLen; int nextWidth = UnicodeTranscript.charWidth(text, nextPos); int nextLen; if (column + nextWidth + 1 < columns) { - nextLen = findStartOfColumn(column + nextWidth + 1) - nextPos; + nextLen = findStartOfColumn(column + nextWidth + 1) + shift - nextPos; } else { nextLen = spaceUsed - nextPos; } if (nextWidth == 2) { text[nextPos] = ' '; // Shift the array to match if (nextLen > 1) { System.arraycopy(text, nextPos + nextLen, text, nextPos + 1, spaceUsed - nextPos - nextLen); shift -= nextLen - 1; offset[0] -= nextLen - 1; } } else { // Shift the array leftwards System.arraycopy(text, nextPos + nextLen, text, nextPos, spaceUsed - nextPos - nextLen); shift -= nextLen; // Truncate the line - offset[0] = (short) findStartOfColumn(columns - 1); + offset[0] -= nextLen; } // Correct the offset for the next column to reflect width change if (column == 0) { offset[1] = -1; } else { offset[column + 1] = (short) (offset[column] - 1); } ++column; } } // Update offset table if (shift != 0) { for (int i = column + 1; i < columns; ++i) { offset[i] += shift; } } } }
false
true
public void setChar(int column, int codePoint) { int columns = mColumns; if (column < 0 || column >= columns) { throw new IllegalArgumentException(); } char[] text = mText; short[] offset = mOffset; int spaceUsed = offset[0]; int pos = findStartOfColumn(column); int charWidth = UnicodeTranscript.charWidth(codePoint); int oldCharWidth = UnicodeTranscript.charWidth(text, pos); // Get the number of elements in the mText array this column uses now int oldLen; if (column + oldCharWidth < columns) { oldLen = findStartOfColumn(column+oldCharWidth) - pos; } else { oldLen = spaceUsed - pos; } // Find how much space this column will need int newLen = Character.charCount(codePoint); if (charWidth == 0) { /* Combining characters are added to the contents of the column instead of overwriting them, so that they modify the existing contents */ newLen += oldLen; } int shift = newLen - oldLen; // Shift the rest of the line right to make room if necessary if (shift > 0) { if (spaceUsed + shift > text.length) { // We need to grow the array char[] newText = new char[text.length + columns]; System.arraycopy(text, 0, newText, 0, pos); System.arraycopy(text, pos + oldLen, newText, pos + newLen, spaceUsed - pos - oldLen); mText = text = newText; } else { System.arraycopy(text, pos + oldLen, text, pos + newLen, spaceUsed - pos - oldLen); } } // Store the character if (charWidth > 0) { Character.toChars(codePoint, text, pos); } else { /* Store a combining character at the end of the existing contents, so that it modifies them */ Character.toChars(codePoint, text, pos + oldLen); } // Shift the rest of the line left to eliminate gaps if necessary if (shift < 0) { System.arraycopy(text, pos + oldLen, text, pos + newLen, spaceUsed - pos - oldLen); } // Update space used if (shift != 0) { spaceUsed += shift; offset[0] = (short) spaceUsed; } /* * Handle cases where charWidth changes * width 1 -> width 2: should clobber the contents of the next * column (if next column contains wide char, need to pad with a space) * width 2 -> width 1: pad with a space after the new character */ if (oldCharWidth == 2 && charWidth == 1) { // Pad with a space int nextPos = pos + newLen; if (spaceUsed + 1 > text.length) { // Array needs growing char[] newText = new char[text.length + columns]; System.arraycopy(text, 0, newText, 0, nextPos); System.arraycopy(text, nextPos, newText, nextPos + 1, spaceUsed - nextPos); mText = text = newText; } else { System.arraycopy(text, nextPos, text, nextPos + 1, spaceUsed - nextPos); } text[nextPos] = ' '; // Update space used ++offset[0]; // Correct the offset for the next column to reflect width change if (column == 0) { offset[1] = (short) (newLen - 1); } else if (column + 1 < columns) { offset[column + 1] = (short) (offset[column] + newLen - 1); } ++column; ++shift; } else if (oldCharWidth == 1 && charWidth == 2) { if (column == columns - 1) { // A width 2 character doesn't fit in the last column. text[pos] = ' '; offset[0] = (short) (pos + 1); shift = 0; } else if (column == columns - 2) { // Correct offset for the next column to reflect width change offset[column + 1] = (short) (offset[column] - 1); // Truncate the line after this character. offset[0] = (short) (pos + newLen); shift = 0; } else { // Overwrite the contents of the next column. int nextPos = pos + newLen; int nextWidth = UnicodeTranscript.charWidth(text, nextPos); int nextLen; if (column + nextWidth + 1 < columns) { nextLen = findStartOfColumn(column + nextWidth + 1) - nextPos; } else { nextLen = spaceUsed - nextPos; } if (nextWidth == 2) { text[nextPos] = ' '; // Shift the array to match if (nextLen > 1) { System.arraycopy(text, nextPos + nextLen, text, nextPos + 1, spaceUsed - nextPos - nextLen); shift -= nextLen - 1; offset[0] -= nextLen - 1; } } else { // Shift the array leftwards System.arraycopy(text, nextPos + nextLen, text, nextPos, spaceUsed - nextPos - nextLen); shift -= nextLen; // Truncate the line offset[0] = (short) findStartOfColumn(columns - 1); } // Correct the offset for the next column to reflect width change if (column == 0) { offset[1] = -1; } else { offset[column + 1] = (short) (offset[column] - 1); } ++column; } } // Update offset table if (shift != 0) { for (int i = column + 1; i < columns; ++i) { offset[i] += shift; } } }
public void setChar(int column, int codePoint) { int columns = mColumns; if (column < 0 || column >= columns) { throw new IllegalArgumentException(); } char[] text = mText; short[] offset = mOffset; int spaceUsed = offset[0]; int pos = findStartOfColumn(column); int charWidth = UnicodeTranscript.charWidth(codePoint); int oldCharWidth = UnicodeTranscript.charWidth(text, pos); // Get the number of elements in the mText array this column uses now int oldLen; if (column + oldCharWidth < columns) { oldLen = findStartOfColumn(column+oldCharWidth) - pos; } else { oldLen = spaceUsed - pos; } // Find how much space this column will need int newLen = Character.charCount(codePoint); if (charWidth == 0) { /* Combining characters are added to the contents of the column instead of overwriting them, so that they modify the existing contents */ newLen += oldLen; } int shift = newLen - oldLen; // Shift the rest of the line right to make room if necessary if (shift > 0) { if (spaceUsed + shift > text.length) { // We need to grow the array char[] newText = new char[text.length + columns]; System.arraycopy(text, 0, newText, 0, pos); System.arraycopy(text, pos + oldLen, newText, pos + newLen, spaceUsed - pos - oldLen); mText = text = newText; } else { System.arraycopy(text, pos + oldLen, text, pos + newLen, spaceUsed - pos - oldLen); } } // Store the character if (charWidth > 0) { Character.toChars(codePoint, text, pos); } else { /* Store a combining character at the end of the existing contents, so that it modifies them */ Character.toChars(codePoint, text, pos + oldLen); } // Shift the rest of the line left to eliminate gaps if necessary if (shift < 0) { System.arraycopy(text, pos + oldLen, text, pos + newLen, spaceUsed - pos - oldLen); } // Update space used if (shift != 0) { spaceUsed += shift; offset[0] = (short) spaceUsed; } /* * Handle cases where charWidth changes * width 1 -> width 2: should clobber the contents of the next * column (if next column contains wide char, need to pad with a space) * width 2 -> width 1: pad with a space after the new character */ if (oldCharWidth == 2 && charWidth == 1) { // Pad with a space int nextPos = pos + newLen; if (spaceUsed + 1 > text.length) { // Array needs growing char[] newText = new char[text.length + columns]; System.arraycopy(text, 0, newText, 0, nextPos); System.arraycopy(text, nextPos, newText, nextPos + 1, spaceUsed - nextPos); mText = text = newText; } else { System.arraycopy(text, nextPos, text, nextPos + 1, spaceUsed - nextPos); } text[nextPos] = ' '; // Update space used ++offset[0]; // Correct the offset for the next column to reflect width change if (column == 0) { offset[1] = (short) (newLen - 1); } else if (column + 1 < columns) { offset[column + 1] = (short) (offset[column] + newLen - 1); } ++column; ++shift; } else if (oldCharWidth == 1 && charWidth == 2) { if (column == columns - 1) { // A width 2 character doesn't fit in the last column. text[pos] = ' '; offset[0] = (short) (pos + 1); shift = 0; } else if (column == columns - 2) { // Correct offset for the next column to reflect width change offset[column + 1] = (short) (offset[column] - 1); // Truncate the line after this character. offset[0] = (short) (pos + newLen); shift = 0; } else { // Overwrite the contents of the next column. int nextPos = pos + newLen; int nextWidth = UnicodeTranscript.charWidth(text, nextPos); int nextLen; if (column + nextWidth + 1 < columns) { nextLen = findStartOfColumn(column + nextWidth + 1) + shift - nextPos; } else { nextLen = spaceUsed - nextPos; } if (nextWidth == 2) { text[nextPos] = ' '; // Shift the array to match if (nextLen > 1) { System.arraycopy(text, nextPos + nextLen, text, nextPos + 1, spaceUsed - nextPos - nextLen); shift -= nextLen - 1; offset[0] -= nextLen - 1; } } else { // Shift the array leftwards System.arraycopy(text, nextPos + nextLen, text, nextPos, spaceUsed - nextPos - nextLen); shift -= nextLen; // Truncate the line offset[0] -= nextLen; } // Correct the offset for the next column to reflect width change if (column == 0) { offset[1] = -1; } else { offset[column + 1] = (short) (offset[column] - 1); } ++column; } } // Update offset table if (shift != 0) { for (int i = column + 1; i < columns; ++i) { offset[i] += shift; } } }
diff --git a/waterken/server/src/org/waterken/server/Spawn.java b/waterken/server/src/org/waterken/server/Spawn.java index 5a35d077..c0481c60 100644 --- a/waterken/server/src/org/waterken/server/Spawn.java +++ b/waterken/server/src/org/waterken/server/Spawn.java @@ -1,131 +1,131 @@ // Copyright 2007-2008 Waterken Inc. under the terms of the MIT X license // found at http://www.opensource.org/licenses/mit-license.html package org.waterken.server; import java.io.PrintStream; import org.joe_e.Token; import org.ref_send.log.Anchor; import org.ref_send.promise.Volatile; import org.ref_send.promise.eventual.Eventual; import org.ref_send.var.Receiver; import org.waterken.net.http.HTTPD; import org.waterken.project.ProjectTracer; import org.waterken.remote.Remote; import org.waterken.remote.Remoting; import org.waterken.remote.http.AMP; import org.waterken.uri.Hostname; import org.waterken.uri.URI; import org.waterken.vat.Creator; import org.waterken.vat.Root; import org.waterken.vat.Tracer; import org.waterken.vat.Transaction; import org.waterken.vat.Vat; /** * Command line program to create a new database. */ final class Spawn { private Spawn() {} /** * @param args command line arguments */ static public void main(String[] args) throws Exception { // extract the arguments if (args.length < 2) { final PrintStream log = System.err; log.println("Creates a new persistent object folder."); log.println("use: java -jar spawn.jar " + "<project-name> <factory-typename> <database-label>"); System.exit(-1); return; } final String projectValue = args[0]; final String typename = args[1]; final String label = 2 < args.length ? args[2] : null; // load configured values final String vatURIPathPrefix = Config.read(String.class, "vatURIPathPrefix"); // determine the local address final String hereValue; final Credentials credentials = Proxy.init(); if (null != credentials) { final String host = credentials.getHostname(); Hostname.vet(host); final int portN = Config.read(HTTPD.class, "https").port; final String port = 443 == portN ? "" : ":" + portN; hereValue = "https://" + host + port + "/" + vatURIPathPrefix; } else { final int portN = Config.read(HTTPD.class, "http").port; final String port = 80 == portN ? "" : ":" + portN; hereValue = "http://localhost" + port + "/" + vatURIPathPrefix; } final Proxy clientValue = new Proxy(); // create the database final String r=Config.vat().enter(Vat.change,new Transaction<String>() { public String run(final Root local) throws Exception { final Token deferredValue = new Token(); final Eventual _Value = new Eventual(deferredValue, null, null); final Creator creator = local.fetch(null, Root.creator); final ClassLoader code = creator.load(projectValue); final Tracer tracerValue = ProjectTracer.make(code, code.getParent()); final Root synthetic = new Root() { public String getVatName() { return local.getVatName(); } public Anchor anchor() { return local.anchor(); } - public <T> T + public Object fetch(final Object otherwise, final String name) { - return (T)(Root.project.equals(name) + return Root.project.equals(name) ? projectValue : Root.here.equals(name) ? hereValue : Root.events.equals(name) ? ReadConfig.make(Receiver.class, "events") : Root.tracer.equals(name) ? tracerValue : Remoting.client.equals(name) ? clientValue : Remoting.deferred.equals(name) ? deferredValue : Remoting._.equals(name) ? _Value - : local.fetch(otherwise, name)); + : local.fetch(otherwise, name); } public void link(final String name, final Object value) { throw new AssertionError(); } public String export(final Object value) { throw new AssertionError(); } public String pipeline(final String m) { throw new AssertionError(); } public String getTransactionTag() { throw new AssertionError(); } }; final Class<?> factory = code.loadClass(typename); final Volatile<?> p = Eventual.promised( AMP.publish(synthetic).spawn(label, factory)); return Remote.bind(synthetic, null).run(p.cast()); } }).cast(); System.out.println(URI.resolve(hereValue, r)); } }
false
true
static public void main(String[] args) throws Exception { // extract the arguments if (args.length < 2) { final PrintStream log = System.err; log.println("Creates a new persistent object folder."); log.println("use: java -jar spawn.jar " + "<project-name> <factory-typename> <database-label>"); System.exit(-1); return; } final String projectValue = args[0]; final String typename = args[1]; final String label = 2 < args.length ? args[2] : null; // load configured values final String vatURIPathPrefix = Config.read(String.class, "vatURIPathPrefix"); // determine the local address final String hereValue; final Credentials credentials = Proxy.init(); if (null != credentials) { final String host = credentials.getHostname(); Hostname.vet(host); final int portN = Config.read(HTTPD.class, "https").port; final String port = 443 == portN ? "" : ":" + portN; hereValue = "https://" + host + port + "/" + vatURIPathPrefix; } else { final int portN = Config.read(HTTPD.class, "http").port; final String port = 80 == portN ? "" : ":" + portN; hereValue = "http://localhost" + port + "/" + vatURIPathPrefix; } final Proxy clientValue = new Proxy(); // create the database final String r=Config.vat().enter(Vat.change,new Transaction<String>() { public String run(final Root local) throws Exception { final Token deferredValue = new Token(); final Eventual _Value = new Eventual(deferredValue, null, null); final Creator creator = local.fetch(null, Root.creator); final ClassLoader code = creator.load(projectValue); final Tracer tracerValue = ProjectTracer.make(code, code.getParent()); final Root synthetic = new Root() { public String getVatName() { return local.getVatName(); } public Anchor anchor() { return local.anchor(); } public <T> T fetch(final Object otherwise, final String name) { return (T)(Root.project.equals(name) ? projectValue : Root.here.equals(name) ? hereValue : Root.events.equals(name) ? ReadConfig.make(Receiver.class, "events") : Root.tracer.equals(name) ? tracerValue : Remoting.client.equals(name) ? clientValue : Remoting.deferred.equals(name) ? deferredValue : Remoting._.equals(name) ? _Value : local.fetch(otherwise, name)); } public void link(final String name, final Object value) { throw new AssertionError(); } public String export(final Object value) { throw new AssertionError(); } public String pipeline(final String m) { throw new AssertionError(); } public String getTransactionTag() { throw new AssertionError(); } }; final Class<?> factory = code.loadClass(typename); final Volatile<?> p = Eventual.promised( AMP.publish(synthetic).spawn(label, factory)); return Remote.bind(synthetic, null).run(p.cast()); } }).cast(); System.out.println(URI.resolve(hereValue, r)); }
static public void main(String[] args) throws Exception { // extract the arguments if (args.length < 2) { final PrintStream log = System.err; log.println("Creates a new persistent object folder."); log.println("use: java -jar spawn.jar " + "<project-name> <factory-typename> <database-label>"); System.exit(-1); return; } final String projectValue = args[0]; final String typename = args[1]; final String label = 2 < args.length ? args[2] : null; // load configured values final String vatURIPathPrefix = Config.read(String.class, "vatURIPathPrefix"); // determine the local address final String hereValue; final Credentials credentials = Proxy.init(); if (null != credentials) { final String host = credentials.getHostname(); Hostname.vet(host); final int portN = Config.read(HTTPD.class, "https").port; final String port = 443 == portN ? "" : ":" + portN; hereValue = "https://" + host + port + "/" + vatURIPathPrefix; } else { final int portN = Config.read(HTTPD.class, "http").port; final String port = 80 == portN ? "" : ":" + portN; hereValue = "http://localhost" + port + "/" + vatURIPathPrefix; } final Proxy clientValue = new Proxy(); // create the database final String r=Config.vat().enter(Vat.change,new Transaction<String>() { public String run(final Root local) throws Exception { final Token deferredValue = new Token(); final Eventual _Value = new Eventual(deferredValue, null, null); final Creator creator = local.fetch(null, Root.creator); final ClassLoader code = creator.load(projectValue); final Tracer tracerValue = ProjectTracer.make(code, code.getParent()); final Root synthetic = new Root() { public String getVatName() { return local.getVatName(); } public Anchor anchor() { return local.anchor(); } public Object fetch(final Object otherwise, final String name) { return Root.project.equals(name) ? projectValue : Root.here.equals(name) ? hereValue : Root.events.equals(name) ? ReadConfig.make(Receiver.class, "events") : Root.tracer.equals(name) ? tracerValue : Remoting.client.equals(name) ? clientValue : Remoting.deferred.equals(name) ? deferredValue : Remoting._.equals(name) ? _Value : local.fetch(otherwise, name); } public void link(final String name, final Object value) { throw new AssertionError(); } public String export(final Object value) { throw new AssertionError(); } public String pipeline(final String m) { throw new AssertionError(); } public String getTransactionTag() { throw new AssertionError(); } }; final Class<?> factory = code.loadClass(typename); final Volatile<?> p = Eventual.promised( AMP.publish(synthetic).spawn(label, factory)); return Remote.bind(synthetic, null).run(p.cast()); } }).cast(); System.out.println(URI.resolve(hereValue, r)); }
diff --git a/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java b/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java index a6ca6bf..8080a40 100644 --- a/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java +++ b/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java @@ -1,1335 +1,1336 @@ /* * The MIT License * * Copyright 2012 Universidad de Montemorelos A. C. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package mx.edu.um.academia.dao.impl; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.model.User; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portlet.documentlibrary.model.DLFileEntry; import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil; import com.liferay.portlet.journal.model.JournalArticle; import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil; import java.math.MathContext; import java.math.RoundingMode; import java.util.*; import mx.edu.um.academia.dao.CursoDao; import mx.edu.um.academia.dao.ExamenDao; import mx.edu.um.academia.model.*; import mx.edu.um.academia.utils.Constantes; import net.sf.jasperreports.engine.JasperReport; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.*; import static org.hibernate.type.StandardBasicTypes.STRING; import static org.hibernate.type.StandardBasicTypes.TIMESTAMP; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author J. David Mendoza <[email protected]> */ @Repository @Transactional public class CursoDaoHibernate implements CursoDao { private static final Logger log = LoggerFactory.getLogger(CursoDaoHibernate.class); @Autowired private SessionFactory sessionFactory; @Autowired private ExamenDao examenDao; @Autowired private ResourceBundleMessageSource messages; public CursoDaoHibernate() { log.info("Nueva instancia del dao de cursos"); } private Session currentSession() { return sessionFactory.getCurrentSession(); } @Override public Map<String, Object> lista(Map<String, Object> params) { log.debug("Buscando lista de cursos con params {}", params); if (params == null) { params = new HashMap<>(); } if (!params.containsKey("max") || params.get("max") == null) { params.put("max", 5); } else { params.put("max", Math.min((Integer) params.get("max"), 100)); } if (params.containsKey("pagina") && params.get("pagina") != null) { Long pagina = (Long) params.get("pagina"); Long offset = (pagina - 1) * (Integer) params.get("max"); params.put("offset", offset.intValue()); } if (!params.containsKey("offset") || params.get("offset") == null) { params.put("offset", 0); } Criteria criteria = currentSession().createCriteria(Curso.class); Criteria countCriteria = currentSession().createCriteria(Curso.class); if (params.containsKey("comunidades")) { criteria.add(Restrictions.in("comunidadId", (Set<Integer>) params.get("comunidades"))); countCriteria.add(Restrictions.in("comunidadId", (Set<Integer>) params.get("comunidades"))); } if (params.containsKey("filtro")) { String filtro = (String) params.get("filtro"); Disjunction propiedades = Restrictions.disjunction(); propiedades.add(Restrictions.ilike("codigo", filtro, MatchMode.ANYWHERE)); propiedades.add(Restrictions.ilike("nombre", filtro, MatchMode.ANYWHERE)); criteria.add(propiedades); countCriteria.add(propiedades); } if (params.containsKey("order")) { String campo = (String) params.get("order"); if (params.get("sort").equals("desc")) { criteria.addOrder(Order.desc(campo)); } else { criteria.addOrder(Order.asc(campo)); } } criteria.addOrder(Order.desc("fechaModificacion")); criteria.setFirstResult((Integer) params.get("offset")); criteria.setMaxResults((Integer) params.get("max")); params.put("cursos", criteria.list()); countCriteria.setProjection(Projections.rowCount()); List cantidades = countCriteria.list(); if (cantidades != null) { params.put("cantidad", (Long) cantidades.get(0)); } else { params.put("cantidad", 0L); } return params; } @Override public Curso obtiene(Long cursoId) { log.debug("Obteniendo curso {}", cursoId); return (Curso) currentSession().get(Curso.class, cursoId); } @Override public Curso obtiene(String codigo, Long comunidadId) { log.debug("Obteniendo curso por codigo {} y comunidad {}", codigo, comunidadId); Query query = currentSession().createQuery("select c from Curso c where c.codigo = :codigo and c.comunidadId = :comunidadId"); query.setString("codigo", codigo); query.setLong("comunidadId", comunidadId); return (Curso) query.uniqueResult(); } @Override public Curso crea(Curso curso, User creador) { log.debug("Creando curso {} por usuario", curso, creador); Date fecha = new Date(); curso.setFechaCreacion(fecha); curso.setFechaModificacion(fecha); if (creador != null) { curso.setCreador(creador.getScreenName()); } else { curso.setCreador("admin"); } currentSession().save(curso); currentSession().flush(); Reporte reporte = curso.getReporte(); if (reporte != null) { this.asignaReporte(reporte, curso); } currentSession().flush(); return curso; } @Override public Curso actualiza(Curso otro, User creador) { log.debug("Actualizando curso {} por usuario {}", otro, creador); Curso curso = (Curso) currentSession().get(Curso.class, otro.getId()); currentSession().refresh(curso); Long intro = curso.getIntro(); log.debug("CursoIntro:", curso.getIntro()); BeanUtils.copyProperties(otro, curso, new String[]{"id", "version", "fechaCreacion", "objetos", "intro", "correoId"}); log.debug("CursoIntro:", curso.getIntro()); curso.setIntro(intro); curso.setFechaModificacion(new Date()); if (creador != null) { curso.setCreador(creador.getScreenName()); } else { curso.setCreador("admin"); } currentSession().update(curso); currentSession().flush(); Reporte reporte = curso.getReporte(); if (reporte != null) { this.modificaReporte(reporte, curso); } currentSession().flush(); return curso; } @Override public void asignaIntro(Curso curso) { Query query = currentSession().createQuery("update Curso set intro = :intro where id = :id and version = :version"); query.setLong("intro", curso.getIntro()); query.setLong("id", curso.getId()); query.setLong("version", curso.getVersion()); query.executeUpdate(); } @Override public String elimina(Long cursoId, User creador) { log.debug("Eliminando curso {} por usuario {}", cursoId, creador); // Dando de baja alumnos Query query = currentSession().createQuery("delete from AlumnoCurso where id.curso.id = :cursoId"); query.setLong("cursoId", cursoId); query.executeUpdate(); query = currentSession().createQuery("delete from Reporte where curso.id = :cursoId"); query.setLong("cursoId", cursoId); query.executeUpdate(); query = currentSession().createQuery("delete from PortletCurso where curso.id = :cursoId"); query.setLong("cursoId", cursoId); query.executeUpdate(); // Dando de baja los objetos Curso curso = (Curso) currentSession().get(Curso.class, cursoId); curso.getObjetos().clear(); currentSession().update(curso); if (curso.getIntro() != null) { try { JournalArticleLocalServiceUtil.deleteJournalArticle(curso.getIntro()); } catch (PortalException | SystemException ex) { log.error("No se pudo eliminar el articulo de introduccion", ex); } } if (curso.getCorreoId() != null) { try { JournalArticleLocalServiceUtil.deleteJournalArticle(curso.getCorreoId()); } catch (PortalException | SystemException ex) { log.error("No se pudo eliminar el articulo de correo", ex); } } String nombre = curso.getNombre(); currentSession().delete(curso); return nombre; } @Override public Map<String, Object> objetos(Long id, Set<Long> comunidades) { log.debug("Buscando los objetos del curso {}", id); Curso curso = (Curso) currentSession().get(Curso.class, id); List<ObjetoAprendizaje> objetos = curso.getObjetos(); log.debug("Lista de seleccionados"); for (ObjetoAprendizaje objeto : objetos) { log.debug("Seleccionado: " + objeto.getNombre()); } Map<String, Object> resultado = new HashMap<>(); resultado.put("seleccionados", objetos); Criteria criteria = currentSession().createCriteria(ObjetoAprendizaje.class); criteria.add(Restrictions.in("comunidadId", (Set<Long>) comunidades)); criteria.addOrder(Order.asc("codigo")); log.debug("Lista de disponibles"); List<ObjetoAprendizaje> disponibles = criteria.list(); disponibles.removeAll(objetos); for (ObjetoAprendizaje objeto : disponibles) { log.debug("Disponible: " + objeto.getNombre()); } resultado.put("disponibles", disponibles); log.debug("regresando {}", resultado); return resultado; } @Override public List<ObjetoAprendizaje> objetos(Long id) { log.debug("Buscando los objetos del curso {}", id); Curso curso = (Curso) currentSession().get(Curso.class, id); List<ObjetoAprendizaje> objetos = curso.getObjetos(); for (ObjetoAprendizaje objeto : objetos) { log.debug("Seleccionado: " + objeto.getNombre()); } return objetos; } @Override public void agregaObjetos(Long cursoId, Long[] objetosArray) { log.debug("Agregando objetos {} a curso {}", objetosArray, cursoId); Curso curso = (Curso) currentSession().get(Curso.class, cursoId); curso.getObjetos().clear(); for (Long objetoId : objetosArray) { curso.getObjetos().add((ObjetoAprendizaje) currentSession().load(ObjetoAprendizaje.class, objetoId)); } log.debug("Actualizando curso {}", curso); currentSession().update(curso); currentSession().flush(); } @Override public Map<String, Object> verContenido(Long cursoId) { Curso curso = (Curso) currentSession().get(Curso.class, cursoId); List<ObjetoAprendizaje> objetos = curso.getObjetos(); for (ObjetoAprendizaje objeto : objetos) { for (Contenido contenido : objeto.getContenidos()) { log.debug("{} : {} : {}", new Object[]{curso.getCodigo(), objeto.getCodigo(), contenido.getCodigo()}); } } Map<String, Object> resultado = new HashMap<>(); resultado.put("objetos", objetos); return resultado; } @Override public List<Curso> todos(Set<Long> comunidades) { log.debug("Buscando lista de cursos en las comunidades {}", comunidades); Criteria criteria = currentSession().createCriteria(Curso.class); criteria.add(Restrictions.in("comunidadId", comunidades)); criteria.addOrder(Order.desc("codigo")); return criteria.list(); } @Override public PortletCurso guardaPortlet(Long cursoId, String portletId) { Curso curso = (Curso) currentSession().get(Curso.class, cursoId); PortletCurso portlet = (PortletCurso) currentSession().get(PortletCurso.class, portletId); if (portlet == null) { portlet = new PortletCurso(portletId, curso); currentSession().save(portlet); } else { portlet.setCurso(curso); currentSession().update(portlet); } return portlet; } @Override public PortletCurso obtienePortlet(String portletId) { return (PortletCurso) currentSession().get(PortletCurso.class, portletId); } @Override public Alumno obtieneAlumno(Long id) { return (Alumno) currentSession().get(Alumno.class, id); } @Override public void inscribe(Curso curso, Alumno alumno, Boolean creaUsuario, String estatus) { log.debug("Inscribiendo a alumno {} en curso {}", alumno, curso); if (creaUsuario) { log.debug("Creando alumno primero"); alumno.setComunidad(curso.getComunidadId()); currentSession().save(alumno); } log.debug("Inscribiendo..."); AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk); if (alumnoCurso == null) { alumnoCurso = new AlumnoCurso(alumno, curso, estatus); currentSession().save(alumnoCurso); } else { alumnoCurso.setEstatus(estatus); currentSession().update(alumnoCurso); } currentSession().flush(); } @Override public Boolean estaInscrito(Long cursoId, Long alumnoId) { log.debug("Validando si el alumno {} esta inscrito en {}", alumnoId, cursoId); Curso curso = (Curso) currentSession().load(Curso.class, cursoId); Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId); AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk); boolean resultado = false; if (alumnoCurso != null && (Constantes.INSCRITO.equals(alumnoCurso.getEstatus()) || Constantes.CONCLUIDO.equals(alumnoCurso.getEstatus()))) { resultado = true; } return resultado; } @Override public List<ObjetoAprendizaje> objetosAlumno(Long cursoId, Long alumnoId, ThemeDisplay themeDisplay) { log.debug("Obteniendo objetos de aprendizaje del curso {} para el alumno {}", cursoId, alumnoId); Curso curso = (Curso) currentSession().get(Curso.class, cursoId); log.debug("{}", curso); Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId); log.debug("{}", alumno); AlumnoCursoPK alumnoCursoPK = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, alumnoCursoPK); alumnoCurso.setUltimoAcceso(new Date()); currentSession().update(alumnoCurso); currentSession().flush(); List<ObjetoAprendizaje> objetos = curso.getObjetos(); boolean noAsignado = true; boolean activo = false; Date fecha = new Date(); for (ObjetoAprendizaje objeto : objetos) { boolean bandera = true; AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto); AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2); if (alumnoObjeto == null) { alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto); currentSession().save(alumnoObjeto); currentSession().flush(); } for (Contenido contenido : objeto.getContenidos()) { log.debug("Cargando contenido {} del objeto {} : activo : {}", new Object[]{contenido, objeto, contenido.getActivo()}); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido == null) { alumnoContenido = new AlumnoContenido(alumno, contenido); currentSession().save(alumnoContenido); currentSession().flush(); } log.debug("Buscando {} : {}", bandera, alumnoContenido.getTerminado()); if (bandera && alumnoContenido.getTerminado() == null && !activo) { this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay); log.debug("Activando a {}", contenido.getNombre()); contenido.setActivo(bandera); activo = true; alumnoContenido.setIniciado(fecha); currentSession().update(alumnoContenido); if (alumnoObjeto.getIniciado() == null) { alumnoObjeto.setIniciado(fecha); currentSession().update(alumnoObjeto); } currentSession().flush(); bandera = false; noAsignado = false; } log.debug("Asignando el contenido {} : activo : {}", contenido.getNombre(), contenido.getActivo()); contenido.setAlumno(alumnoContenido); } } if (noAsignado) { log.debug("No asignado >> asignando"); for (ObjetoAprendizaje objeto : objetos) { boolean bandera = true; AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto); AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2); if (alumnoObjeto == null) { alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto); currentSession().save(alumnoObjeto); currentSession().flush(); } for (Contenido contenido : objeto.getContenidos()) { log.debug("Cargando contenido {} del objeto {}", contenido, objeto); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido == null) { alumnoContenido = new AlumnoContenido(alumno, contenido); currentSession().save(alumnoContenido); currentSession().flush(); } if (bandera && !activo) { this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay); log.debug("Activando a {}", contenido.getNombre()); contenido.setActivo(true); activo = true; alumnoContenido.setIniciado(fecha); currentSession().update(alumnoContenido); if (alumnoObjeto.getIniciado() == null) { alumnoObjeto.setIniciado(fecha); currentSession().update(alumnoObjeto); } currentSession().flush(); bandera = false; } contenido.setAlumno(alumnoContenido); } } } return objetos; } @Override public List<ObjetoAprendizaje> objetosAlumno(Long cursoId, Long contenidoId, Long alumnoId, ThemeDisplay themeDisplay) { log.debug("Obteniendo objetos de aprendizaje del curso {} para el alumno {}", cursoId, alumnoId); Curso curso = (Curso) currentSession().get(Curso.class, cursoId); log.debug("{}", curso); Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId); log.debug("{}", alumno); AlumnoCursoPK alumnoCursoPK = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, alumnoCursoPK); alumnoCurso.setUltimoAcceso(new Date()); currentSession().update(alumnoCurso); currentSession().flush(); List<ObjetoAprendizaje> objetos = curso.getObjetos(); boolean terminado = true; boolean noAsignado = true; boolean activo = false; Date fecha = new Date(); for (ObjetoAprendizaje objeto : objetos) { AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto); AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2); if (alumnoObjeto == null) { alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto); currentSession().save(alumnoObjeto); currentSession().flush(); } for (Contenido contenido : objeto.getContenidos()) { log.debug("Cargando contenido {} del objeto {}", contenido, objeto); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido == null) { alumnoContenido = new AlumnoContenido(alumno, contenido); currentSession().save(alumnoContenido); currentSession().flush(); } if (contenidoId == contenido.getId() && terminado) { this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay); contenido.setActivo(true); noAsignado = false; activo = true; log.debug("Validando si ha sido iniciado {}", alumnoContenido.getIniciado()); if (alumnoContenido.getIniciado() == null) { alumnoContenido.setIniciado(fecha); currentSession().update(alumnoContenido); if (alumnoObjeto.getIniciado() == null) { alumnoObjeto.setIniciado(fecha); currentSession().update(alumnoObjeto); } currentSession().flush(); } } if (alumnoContenido.getTerminado() == null) { terminado = false; } contenido.setAlumno(alumnoContenido); } } if (noAsignado) { for (ObjetoAprendizaje objeto : objetos) { boolean bandera = true; AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto); AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2); if (alumnoObjeto == null) { alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto); currentSession().save(alumnoObjeto); currentSession().flush(); } for (Contenido contenido : objeto.getContenidos()) { AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido == null) { alumnoContenido = new AlumnoContenido(alumno, contenido); currentSession().save(alumnoContenido); currentSession().flush(); } if (bandera && alumnoContenido.getTerminado() == null && !activo) { this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay); contenido.setActivo(bandera); bandera = false; activo = true; noAsignado = false; if (alumnoContenido.getIniciado() == null) { alumnoContenido.setIniciado(fecha); currentSession().update(alumnoContenido); if (alumnoObjeto.getIniciado() == null) { alumnoObjeto.setIniciado(fecha); currentSession().update(alumnoObjeto); } currentSession().flush(); } } contenido.setAlumno(alumnoContenido); } } } if (noAsignado) { for (ObjetoAprendizaje objeto : objetos) { boolean bandera = true; AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto); AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2); if (alumnoObjeto == null) { alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto); currentSession().save(alumnoObjeto); currentSession().flush(); } for (Contenido contenido : objeto.getContenidos()) { AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido == null) { alumnoContenido = new AlumnoContenido(alumno, contenido); currentSession().save(alumnoContenido); currentSession().flush(); } if (bandera && !activo) { this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay); contenido.setActivo(bandera); alumnoContenido.setIniciado(fecha); currentSession().update(alumnoContenido); if (alumnoObjeto.getIniciado() == null) { alumnoObjeto.setIniciado(fecha); currentSession().update(alumnoObjeto); } currentSession().flush(); bandera = false; activo = true; } contenido.setAlumno(alumnoContenido); } } } return objetos; } @Override public List<ObjetoAprendizaje> objetosAlumnoSiguiente(Long cursoId, Long alumnoId, ThemeDisplay themeDisplay) { log.debug("Obteniendo siguiente contenido curso {} para el alumno {}", cursoId, alumnoId); Curso curso = (Curso) currentSession().get(Curso.class, cursoId); log.debug("{}", curso); Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId); log.debug("{}", alumno); AlumnoCursoPK alumnoCursoPK = new AlumnoCursoPK(alumno, curso); AlumnoCurso ac = (AlumnoCurso) currentSession().get(AlumnoCurso.class, alumnoCursoPK); ac.setUltimoAcceso(new Date()); currentSession().update(ac); currentSession().flush(); List<ObjetoAprendizaje> objetos = curso.getObjetos(); boolean noAsignado = true; boolean activo = false; Date fecha = new Date(); for (ObjetoAprendizaje objeto : objetos) { boolean bandera = true; AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto); AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2); if (alumnoObjeto == null) { alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto); currentSession().save(alumnoObjeto); currentSession().flush(); } for (Contenido contenido : objeto.getContenidos()) { log.debug("Cargando contenido {} del objeto {}", contenido, objeto); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido == null) { alumnoContenido = new AlumnoContenido(alumno, contenido); currentSession().save(alumnoContenido); currentSession().flush(); } if (bandera && alumnoContenido.getTerminado() == null && !activo) { if (alumnoContenido.getIniciado() == null) { this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay); contenido.setActivo(bandera); activo = true; alumnoContenido.setIniciado(fecha); currentSession().update(alumnoContenido); if (alumnoObjeto.getIniciado() == null) { alumnoObjeto.setIniciado(fecha); currentSession().update(alumnoObjeto); } currentSession().flush(); bandera = false; noAsignado = false; } else { alumnoContenido.setTerminado(fecha); currentSession().update(alumnoContenido); currentSession().flush(); } } contenido.setAlumno(alumnoContenido); } if (!activo) { alumnoObjeto.setTerminado(fecha); currentSession().update(alumnoObjeto); } } if (noAsignado) { log.debug("Asignando contenido"); for (ObjetoAprendizaje objeto : objetos) { boolean bandera = true; for (Contenido contenido : objeto.getContenidos()) { AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido == null) { alumnoContenido = new AlumnoContenido(alumno, contenido); currentSession().save(alumnoContenido); currentSession().flush(); } if (bandera && !activo) { this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay); contenido.setActivo(bandera); activo = true; if (alumnoContenido.getIniciado() == null) { alumnoContenido.setIniciado(fecha); } else { AlumnoCursoPK pk2 = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk2); alumnoCurso.setEstatus(Constantes.CONCLUIDO); alumnoCurso.setFechaConclusion(fecha); currentSession().update(alumnoCurso); AlumnoObjetoAprendizajePK pk3 = new AlumnoObjetoAprendizajePK(alumno, objeto); AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk3); alumnoObjeto.setTerminado(fecha); currentSession().update(alumnoObjeto); currentSession().flush(); } currentSession().update(alumnoContenido); currentSession().flush(); bandera = false; } contenido.setAlumno(alumnoContenido); } } } return objetos; } @Override public List<AlumnoCurso> alumnos(Long cursoId) { log.debug("Lista de alumnos del curso {}", cursoId); Query query = currentSession().createQuery("select a from AlumnoCurso a where a.id.curso.id = :cursoId"); query.setLong("cursoId", cursoId); return query.list(); } @Override public void inscribe(Long cursoId, Long alumnoId) { log.debug("Inscribe alumno {} a curso {}", alumnoId, cursoId); Curso curso = (Curso) currentSession().get(Curso.class, cursoId); Alumno alumno = (Alumno) currentSession().get(Alumno.class, alumnoId); if (alumno == null) { try { User usuario = UserLocalServiceUtil.getUser(alumnoId); alumno = new Alumno(usuario); alumno.setComunidad(curso.getComunidadId()); currentSession().save(alumno); currentSession().flush(); } catch (PortalException | SystemException ex) { log.error("No se pudo obtener el usuario", ex); } } AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk); if (alumnoCurso == null) { alumnoCurso = new AlumnoCurso(pk, Constantes.INSCRITO); currentSession().save(alumnoCurso); } else { alumnoCurso.setEstatus(Constantes.INSCRITO); alumnoCurso.setFecha(new Date()); currentSession().update(alumnoCurso); } } @Override public Map<String, Object> alumnos(Map<String, Object> params) { Long cursoId = (Long) params.get("cursoId"); Query query = currentSession().createQuery("select a from AlumnoCurso a join fetch a.id.curso where a.id.curso.id = :cursoId"); query.setLong("cursoId", cursoId); List<AlumnoCurso> alumnos = query.list(); for (AlumnoCurso alumnoCurso : alumnos) { alumnoCurso.setSaldo(alumnoCurso.getId().getCurso().getPrecio()); } params.put("alumnos", alumnos); Curso curso = (Curso) currentSession().get(Curso.class, cursoId); params.put("curso", curso); try { log.debug("Buscando usuarios en la empresa {}", params.get("companyId")); List<User> usuarios = UserLocalServiceUtil.getCompanyUsers((Long) params.get("companyId"), QueryUtil.ALL_POS, QueryUtil.ALL_POS); List<User> lista = new ArrayList<>(); for (User user : usuarios) { if (!user.isDefaultUser()) { lista.add(user); } } params.put("disponibles", lista); } catch (SystemException e) { log.error("No se pudo obtener lista de usuarios", e); } return params; } private void asignaContenido(Long cursoId, AlumnoContenido alumnoContenido, Contenido contenido, ThemeDisplay themeDisplay) { try { StringBuilder sb2 = new StringBuilder(); sb2.append("admin"); sb2.append(cursoId); sb2.append(contenido.getId()); sb2.append(Constantes.SALT); JournalArticle ja; switch (contenido.getTipo()) { case Constantes.ARTICULATE: StringBuilder sb = new StringBuilder(); sb.append("<iframe src='/academia-portlet"); sb.append("/conteni2"); sb.append("/admin"); sb.append("/").append(cursoId); sb.append("/").append(contenido.getId()); sb.append("/").append(DigestUtils.shaHex(sb2.toString())); sb.append("/player.html"); sb.append("' style='width:100%;height:600px;'></iframe>"); contenido.setTexto(sb.toString()); break; case Constantes.STORYLINE: sb = new StringBuilder(); sb.append("<iframe src='/academia-portlet"); sb.append("/conteni2"); sb.append("/admin"); sb.append("/").append(cursoId); sb.append("/").append(contenido.getId()); sb.append("/").append(DigestUtils.shaHex(sb2.toString())); sb.append("/story.html"); sb.append("' style='width:100%;height:650px;'></iframe>"); contenido.setTexto(sb.toString()); break; case Constantes.TEXTO: ja = JournalArticleLocalServiceUtil.getArticle(contenido.getContenidoId()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); contenido.setTexto(texto); } break; case Constantes.VIDEO: log.debug("Buscando el video con el id {}", contenido.getContenidoId()); DLFileEntry fileEntry = DLFileEntryLocalServiceUtil.getDLFileEntry(contenido.getContenidoId()); if (fileEntry != null) { StringBuilder videoLink = new StringBuilder(); videoLink.append("/documents/"); videoLink.append(fileEntry.getGroupId()); videoLink.append("/"); videoLink.append(fileEntry.getFolderId()); videoLink.append("/"); videoLink.append(fileEntry.getTitle()); contenido.setTexto(videoLink.toString()); } break; case Constantes.EXAMEN: Examen examen = contenido.getExamen(); if (examen.getContenido() != null) { ja = JournalArticleLocalServiceUtil.getArticle(examen.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); contenido.setTexto(texto); } } List<Pregunta> preguntas = new ArrayList<>(); for (Pregunta pregunta : examenDao.preguntas(examen.getId())) { for (Respuesta respuesta : pregunta.getRespuestas()) { if (respuesta.getContenido() != null) { ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); respuesta.setTexto(texto); } } else { String texto = messages.getMessage("respuesta.requiere.texto", new String[]{respuesta.getNombre()}, themeDisplay.getLocale()); respuesta.setTexto(texto); } } if (pregunta.getContenido() != null) { ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); pregunta.setTexto(texto); } } else { String texto = messages.getMessage("pregunta.requiere.texto", new String[]{pregunta.getNombre()}, themeDisplay.getLocale()); pregunta.setTexto(texto); } preguntas.add(pregunta); } if (preguntas.size() > 0) { for (Pregunta pregunta : preguntas) { log.debug("{} ||| {}", pregunta, pregunta.getTexto()); } examen.setOtrasPreguntas(preguntas); } break; } log.debug("Validando si ha sido iniciado {}", alumnoContenido.getIniciado()); if (alumnoContenido.getIniciado() == null) { alumnoContenido.setIniciado(new Date()); currentSession().update(alumnoContenido); currentSession().flush(); } } catch (PortalException | SystemException e) { log.error("No se pudo obtener el texto del contenido", e); } } @Override public Examen obtieneExamen(Long examenId) { Examen examen = (Examen) currentSession().get(Examen.class, examenId); return examen; } @Override public Map<String, Object> califica(Map<String, String[]> params, ThemeDisplay themeDisplay, User usuario) { try { Examen examen = (Examen) currentSession().get(Examen.class, new Long(params.get("examenId")[0])); Integer totalExamen = 0; Integer totalUsuario = 0; Set<Pregunta> incorrectas = new LinkedHashSet<>(); for (ExamenPregunta examenPregunta : examen.getPreguntas()) { Pregunta pregunta = examenPregunta.getId().getPregunta(); log.debug("{}({}:{}) > Multiple : {} || Por pregunta : {}", new Object[]{pregunta.getNombre(), pregunta.getId(), examen.getId(), pregunta.getEsMultiple(), examenPregunta.getPorPregunta()}); if (pregunta.getEsMultiple() && examenPregunta.getPorPregunta()) { // Cuando puede tener muchas respuestas y los puntos son por pregunta log.debug("ENTRO 1"); totalExamen += examenPregunta.getPuntos(); String[] respuestas = params.get(pregunta.getId().toString()); List<String> correctas = new ArrayList<>(); if (respuestas.length == pregunta.getCorrectas().size()) { boolean vaBien = true; for (Respuesta correcta : pregunta.getCorrectas()) { boolean encontre = false; for (String respuesta : respuestas) { if (respuesta.equals(correcta.getId().toString())) { encontre = true; correctas.add(respuesta); break; } } if (!encontre) { vaBien = false; } } if (vaBien) { totalUsuario += examenPregunta.getPuntos(); } else { // pon respuesta incorrecta for (String respuestaId : respuestas) { if (!correctas.contains(respuestaId)) { Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId)); JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); respuesta.setTexto(texto); } pregunta.getRespuestas().add(respuesta); } } JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); pregunta.setTexto(texto); } incorrectas.add(pregunta); } } } else { // Cuando puede tener muchas respuestas pero los puntos son por respuesta // Tambien cuando es una sola respuesta la correcta log.debug("ENTRO 2"); String[] respuestas = params.get(pregunta.getId().toString()); List<String> correctas = new ArrayList<>(); if (respuestas.length <= pregunta.getCorrectas().size()) { log.debug("ENTRO 3"); respuestasLoop: for (Respuesta correcta : pregunta.getCorrectas()) { log.debug("Pregunta: {} | Examen: {} | Alumno: {}", new Object[] {examenPregunta.getPuntos(), totalExamen, totalUsuario}); totalExamen += examenPregunta.getPuntos(); for (String respuesta : respuestas) { if (respuesta.equals(correcta.getId().toString())) { totalUsuario += examenPregunta.getPuntos(); correctas.add(respuesta); continue respuestasLoop; } } } if (correctas.size() < pregunta.getCorrectas().size()) { // pon respuesta incorrecta for (String respuestaId : respuestas) { if (!correctas.contains(respuestaId)) { Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId)); JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); respuesta.setTexto(texto); } pregunta.getRespuestas().add(respuesta); } } JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); pregunta.setTexto(texto); } incorrectas.add(pregunta); } } } log.debug("Pregunta {} : Respuesta {} : Usuario {}", new Object[]{pregunta.getId(), pregunta.getCorrectas(), params.get(pregunta.getId().toString())}); } Map<String, Object> resultados = new HashMap<>(); resultados.put("examen", examen); resultados.put("totalExamen", totalExamen); resultados.put("totalUsuario", totalUsuario); resultados.put("totales", new String[]{totalUsuario.toString(), totalExamen.toString(), examen.getPuntos().toString()}); if (examen.getPuntos() != null && totalUsuario < examen.getPuntos()) { resultados.put("messageTitle", "desaprobado"); resultados.put("messageType", "alert-error"); Long contenidoId = new Long(params.get("contenidoId")[0]); Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId()); Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido != null && alumnoContenido.getTerminado() != null) { + alumnoContenido.setIniciado(null); alumnoContenido.setTerminado(null); currentSession().update(alumnoContenido); currentSession().flush(); } } else { resultados.put("messageTitle", "aprobado"); resultados.put("messageType", "alert-success"); for (String key : params.keySet()) { log.debug("{} : {}", key, params.get(key)); } Long contenidoId = new Long(params.get("contenidoId")[0]); Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId()); Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido != null) { alumnoContenido.setTerminado(new Date()); currentSession().update(alumnoContenido); currentSession().flush(); } } if (incorrectas.size() > 0) { resultados.put("incorrectas", incorrectas); } return resultados; } catch (PortalException | SystemException e) { log.error("No se pudo calificar el examen", e); } return null; } @Override public Boolean haConcluido(Long alumnoId, Long cursoId) { Curso curso = (Curso) currentSession().load(Curso.class, cursoId); Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId); AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk); boolean resultado = false; if (alumnoCurso.getEstatus().equals(Constantes.CONCLUIDO)) { resultado = true; } return resultado; } @Override public List<AlumnoCurso> obtieneCursos(Long alumnoId) { log.debug("Buscando los cursos del alumno {}", alumnoId); Query query = currentSession().createQuery("select ac from AlumnoCurso ac " + "join fetch ac.id.curso " + "where ac.id.alumno.id = :alumnoId " + "order by fecha desc"); query.setLong("alumnoId", alumnoId); return query.list(); } @Override public AlumnoCurso obtieneAlumnoCurso(Long alumnoId, Long cursoId) { log.debug("Buscando el curso con {} y {}", alumnoId, cursoId); Query query = currentSession().createQuery("select ac from AlumnoCurso ac " + "join fetch ac.id.alumno " + "join fetch ac.id.curso " + "where ac.id.alumno.id = :alumnoId " + "and ac.id.curso.id = :cursoId"); query.setLong("alumnoId", alumnoId); query.setLong("cursoId", cursoId); AlumnoCurso alumnoCurso = (AlumnoCurso) query.uniqueResult(); if (alumnoCurso != null) { alumnoCurso.setUltimoAcceso(new Date()); currentSession().save(alumnoCurso); currentSession().flush(); } log.debug("Regresando el alumnoCurso {}", alumnoCurso); return alumnoCurso; } public void asignaReporte(Reporte reporte, Curso curso) { reporte.setNombre(curso.getCodigo()); reporte.setCurso(curso); Date fecha = new Date(); reporte.setFechaModificacion(fecha); reporte.setFechaCreacion(fecha); currentSession().save(reporte); } public void modificaReporte(Reporte reporte, Curso curso) { Query query = currentSession().createQuery("select r from Reporte r where r.curso.id = :cursoId"); query.setLong("cursoId", curso.getId()); Reporte otro = (Reporte) query.uniqueResult(); if (otro != null) { otro.setCompilado(reporte.getCompilado()); otro.setNombre(curso.getCodigo()); Date fecha = new Date(); otro.setFechaModificacion(fecha); currentSession().update(otro); } else { this.asignaReporte(reporte, curso); } } @Override public JasperReport obtieneReporte(Long cursoId) { Query query = currentSession().createQuery("select r from Reporte r where r.curso.id = :cursoId"); query.setLong("cursoId", cursoId); Reporte reporte = (Reporte) query.uniqueResult(); JasperReport jr = reporte.getReporte(); return jr; } @Override public Map<String, Object> todosAlumnos(Map<String, Object> params) { MathContext mc = new MathContext(16, RoundingMode.HALF_UP); Long comunidadId = (Long) params.get("comunidadId"); Query query = currentSession().createQuery("select a from AlumnoCurso a " + "join fetch a.id.alumno " + "join fetch a.id.curso " + "where a.id.curso.comunidadId = :comunidadId"); query.setLong("comunidadId", comunidadId); List<AlumnoCurso> lista = query.list(); Map<String, AlumnoCurso> map = new TreeMap<>(); for (AlumnoCurso alumnoCurso : lista) { AlumnoCurso a = map.get(alumnoCurso.getAlumno().getUsuario()); if (a == null) { a = alumnoCurso; try { boolean cambio = false; User user = UserLocalServiceUtil.getUser(alumnoCurso.getId().getAlumno().getId()); Alumno alumno = a.getAlumno(); if (!alumno.getCorreo().equals(user.getEmailAddress())) { alumno.setCorreo(user.getEmailAddress()); cambio = true; } if (!alumno.getNombreCompleto().equals(user.getFullName())) { alumno.setNombreCompleto(user.getFullName()); cambio = true; } if (!alumno.getUsuario().equals(user.getScreenName())) { alumno.setUsuario(user.getScreenName()); cambio = true; } if (cambio) { currentSession().update(alumno); } } catch (PortalException | SystemException ex) { log.error("No se pudo obtener al usuario", ex); } } StringBuilder sb = new StringBuilder(); if (StringUtils.isNotBlank(a.getCursos())) { sb.append(a.getCursos()); sb.append(", "); } sb.append(alumnoCurso.getCurso().getCodigo()); a.setCursos(sb.toString()); a.setSaldo(a.getSaldo().add(alumnoCurso.getCurso().getPrecio(), mc).setScale(2, RoundingMode.HALF_UP)); map.put(alumnoCurso.getAlumno().getUsuario(), a); } params.put("alumnos", map.values()); return params; } @Override public void bajaAlumno(Long alumnoId, Long cursoId) { log.debug("Baja a alumno {} de curso {}", alumnoId, cursoId); Curso curso = (Curso) currentSession().load(Curso.class, cursoId); Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId); AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso); AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().load(AlumnoCurso.class, pk); currentSession().delete(alumnoCurso); } @Override public void asignaCorreo(Curso curso) { Query query = currentSession().createQuery("update Curso set correoId = :correoId where id = :id and version = :version"); query.setLong("correoId", curso.getCorreoId()); query.setLong("id", curso.getId()); query.setLong("version", curso.getVersion()); query.executeUpdate(); } @Override public Salon obtieneSalon(Long cursoId) { log.debug("Obtiene salon por el curso {}", cursoId); Query query = currentSession().createQuery("select s from Salon s where s.curso.id = :cursoId"); query.setLong("cursoId", cursoId); return (Salon) query.uniqueResult(); } @Override public Salon creaSalon(Salon salon) { log.debug("Creando salon {}", salon); currentSession().save(salon); return salon; } @Override public Salon obtieneSalonPorId(Long salonId) { log.debug("Obtiene salon por su id {}", salonId); Salon salon = (Salon) currentSession().get(Salon.class, salonId); return salon; } @Override public Salon actualizaSalon(Salon salon) { log.debug("Actualizando el salon {}", salon); currentSession().update(salon); return salon; } @Override public void eliminaSalon(Salon salon) { log.debug("Eliminando salon {}", salon); currentSession().delete(salon); } @Override public void actualizaObjetos(Long cursoId, Long[] objetos) { log.debug("Actualizando objetos {} del curso {}", objetos, cursoId); Curso curso = (Curso) currentSession().get(Curso.class, cursoId); curso.getObjetos().clear(); currentSession().update(curso); currentSession().flush(); if (objetos != null) { for (Long objetoId : objetos) { curso.getObjetos().add((ObjetoAprendizaje) currentSession().load(ObjetoAprendizaje.class, objetoId)); } currentSession().update(curso); currentSession().flush(); } } @Override public List<ObjetoAprendizaje> buscaObjetos(Long cursoId, String filtro) { Query query = currentSession().createQuery("select comunidadId from Curso where id = :cursoId"); query.setLong("cursoId", cursoId); Long comunidadId = (Long) query.uniqueResult(); query = currentSession().createQuery("select o.id from Curso c inner join c.objetos as o where c.id = :cursoId"); query.setLong("cursoId", cursoId); List<Long> ids = query.list(); Criteria criteria = currentSession().createCriteria(ObjetoAprendizaje.class); if (comunidadId != 23461L) { criteria.add(Restrictions.eq("comunidadId", comunidadId)); } if (ids != null && ids.size() > 0) { criteria.add(Restrictions.not(Restrictions.in("id", ids))); } Disjunction propiedades = Restrictions.disjunction(); propiedades.add(Restrictions.ilike("codigo", filtro, MatchMode.ANYWHERE)); propiedades.add(Restrictions.ilike("nombre", filtro, MatchMode.ANYWHERE)); criteria.add(propiedades); criteria.addOrder(Order.asc("codigo")); return criteria.list(); } @Override public List<Map> contenidos(Long alumnoId, Long cursoId) { String s = "SELECT o.nombre as objetoNombre, ao.iniciado as objetoIniciado, ao.terminado as objetoTerminado, c.nombre as contenidoNombre, ac.iniciado as contenidoIniciado, ac.terminado as contenidoTerminado " + "FROM aca_cursos_aca_objetos co, aca_objetos_aca_contenidos oc, aca_alumno_objeto ao, aca_alumno_contenido ac, aca_objetos o, aca_contenidos c " + "where co.cursos_id = :cursoId " + "and co.objetos_id = oc.objetos_id " + "and co.objetos_id = ao.objeto_id " + "and ao.alumno_id = ac.alumno_id " + "and oc.contenidos_id = ac.contenido_id " + "and co.objetos_id = o.id " + "and ac.contenido_id = c.id " + "and ao.alumno_id = :alumnoId " + "order by co.orden, oc.orden"; SQLQuery query = currentSession().createSQLQuery(s); query.setLong("cursoId", cursoId); query.setLong("alumnoId", alumnoId); query.addScalar("objetoNombre", STRING); query.addScalar("objetoIniciado", TIMESTAMP); query.addScalar("objetoTerminado", TIMESTAMP); query.addScalar("contenidoNombre", STRING); query.addScalar("contenidoIniciado", TIMESTAMP); query.addScalar("contenidoTerminado", TIMESTAMP); query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); return query.list(); } }
true
true
public Map<String, Object> califica(Map<String, String[]> params, ThemeDisplay themeDisplay, User usuario) { try { Examen examen = (Examen) currentSession().get(Examen.class, new Long(params.get("examenId")[0])); Integer totalExamen = 0; Integer totalUsuario = 0; Set<Pregunta> incorrectas = new LinkedHashSet<>(); for (ExamenPregunta examenPregunta : examen.getPreguntas()) { Pregunta pregunta = examenPregunta.getId().getPregunta(); log.debug("{}({}:{}) > Multiple : {} || Por pregunta : {}", new Object[]{pregunta.getNombre(), pregunta.getId(), examen.getId(), pregunta.getEsMultiple(), examenPregunta.getPorPregunta()}); if (pregunta.getEsMultiple() && examenPregunta.getPorPregunta()) { // Cuando puede tener muchas respuestas y los puntos son por pregunta log.debug("ENTRO 1"); totalExamen += examenPregunta.getPuntos(); String[] respuestas = params.get(pregunta.getId().toString()); List<String> correctas = new ArrayList<>(); if (respuestas.length == pregunta.getCorrectas().size()) { boolean vaBien = true; for (Respuesta correcta : pregunta.getCorrectas()) { boolean encontre = false; for (String respuesta : respuestas) { if (respuesta.equals(correcta.getId().toString())) { encontre = true; correctas.add(respuesta); break; } } if (!encontre) { vaBien = false; } } if (vaBien) { totalUsuario += examenPregunta.getPuntos(); } else { // pon respuesta incorrecta for (String respuestaId : respuestas) { if (!correctas.contains(respuestaId)) { Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId)); JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); respuesta.setTexto(texto); } pregunta.getRespuestas().add(respuesta); } } JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); pregunta.setTexto(texto); } incorrectas.add(pregunta); } } } else { // Cuando puede tener muchas respuestas pero los puntos son por respuesta // Tambien cuando es una sola respuesta la correcta log.debug("ENTRO 2"); String[] respuestas = params.get(pregunta.getId().toString()); List<String> correctas = new ArrayList<>(); if (respuestas.length <= pregunta.getCorrectas().size()) { log.debug("ENTRO 3"); respuestasLoop: for (Respuesta correcta : pregunta.getCorrectas()) { log.debug("Pregunta: {} | Examen: {} | Alumno: {}", new Object[] {examenPregunta.getPuntos(), totalExamen, totalUsuario}); totalExamen += examenPregunta.getPuntos(); for (String respuesta : respuestas) { if (respuesta.equals(correcta.getId().toString())) { totalUsuario += examenPregunta.getPuntos(); correctas.add(respuesta); continue respuestasLoop; } } } if (correctas.size() < pregunta.getCorrectas().size()) { // pon respuesta incorrecta for (String respuestaId : respuestas) { if (!correctas.contains(respuestaId)) { Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId)); JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); respuesta.setTexto(texto); } pregunta.getRespuestas().add(respuesta); } } JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); pregunta.setTexto(texto); } incorrectas.add(pregunta); } } } log.debug("Pregunta {} : Respuesta {} : Usuario {}", new Object[]{pregunta.getId(), pregunta.getCorrectas(), params.get(pregunta.getId().toString())}); } Map<String, Object> resultados = new HashMap<>(); resultados.put("examen", examen); resultados.put("totalExamen", totalExamen); resultados.put("totalUsuario", totalUsuario); resultados.put("totales", new String[]{totalUsuario.toString(), totalExamen.toString(), examen.getPuntos().toString()}); if (examen.getPuntos() != null && totalUsuario < examen.getPuntos()) { resultados.put("messageTitle", "desaprobado"); resultados.put("messageType", "alert-error"); Long contenidoId = new Long(params.get("contenidoId")[0]); Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId()); Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido != null && alumnoContenido.getTerminado() != null) { alumnoContenido.setTerminado(null); currentSession().update(alumnoContenido); currentSession().flush(); } } else { resultados.put("messageTitle", "aprobado"); resultados.put("messageType", "alert-success"); for (String key : params.keySet()) { log.debug("{} : {}", key, params.get(key)); } Long contenidoId = new Long(params.get("contenidoId")[0]); Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId()); Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido != null) { alumnoContenido.setTerminado(new Date()); currentSession().update(alumnoContenido); currentSession().flush(); } } if (incorrectas.size() > 0) { resultados.put("incorrectas", incorrectas); } return resultados; } catch (PortalException | SystemException e) { log.error("No se pudo calificar el examen", e); } return null; }
public Map<String, Object> califica(Map<String, String[]> params, ThemeDisplay themeDisplay, User usuario) { try { Examen examen = (Examen) currentSession().get(Examen.class, new Long(params.get("examenId")[0])); Integer totalExamen = 0; Integer totalUsuario = 0; Set<Pregunta> incorrectas = new LinkedHashSet<>(); for (ExamenPregunta examenPregunta : examen.getPreguntas()) { Pregunta pregunta = examenPregunta.getId().getPregunta(); log.debug("{}({}:{}) > Multiple : {} || Por pregunta : {}", new Object[]{pregunta.getNombre(), pregunta.getId(), examen.getId(), pregunta.getEsMultiple(), examenPregunta.getPorPregunta()}); if (pregunta.getEsMultiple() && examenPregunta.getPorPregunta()) { // Cuando puede tener muchas respuestas y los puntos son por pregunta log.debug("ENTRO 1"); totalExamen += examenPregunta.getPuntos(); String[] respuestas = params.get(pregunta.getId().toString()); List<String> correctas = new ArrayList<>(); if (respuestas.length == pregunta.getCorrectas().size()) { boolean vaBien = true; for (Respuesta correcta : pregunta.getCorrectas()) { boolean encontre = false; for (String respuesta : respuestas) { if (respuesta.equals(correcta.getId().toString())) { encontre = true; correctas.add(respuesta); break; } } if (!encontre) { vaBien = false; } } if (vaBien) { totalUsuario += examenPregunta.getPuntos(); } else { // pon respuesta incorrecta for (String respuestaId : respuestas) { if (!correctas.contains(respuestaId)) { Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId)); JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); respuesta.setTexto(texto); } pregunta.getRespuestas().add(respuesta); } } JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); pregunta.setTexto(texto); } incorrectas.add(pregunta); } } } else { // Cuando puede tener muchas respuestas pero los puntos son por respuesta // Tambien cuando es una sola respuesta la correcta log.debug("ENTRO 2"); String[] respuestas = params.get(pregunta.getId().toString()); List<String> correctas = new ArrayList<>(); if (respuestas.length <= pregunta.getCorrectas().size()) { log.debug("ENTRO 3"); respuestasLoop: for (Respuesta correcta : pregunta.getCorrectas()) { log.debug("Pregunta: {} | Examen: {} | Alumno: {}", new Object[] {examenPregunta.getPuntos(), totalExamen, totalUsuario}); totalExamen += examenPregunta.getPuntos(); for (String respuesta : respuestas) { if (respuesta.equals(correcta.getId().toString())) { totalUsuario += examenPregunta.getPuntos(); correctas.add(respuesta); continue respuestasLoop; } } } if (correctas.size() < pregunta.getCorrectas().size()) { // pon respuesta incorrecta for (String respuestaId : respuestas) { if (!correctas.contains(respuestaId)) { Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId)); JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); respuesta.setTexto(texto); } pregunta.getRespuestas().add(respuesta); } } JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido()); if (ja != null) { String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay); pregunta.setTexto(texto); } incorrectas.add(pregunta); } } } log.debug("Pregunta {} : Respuesta {} : Usuario {}", new Object[]{pregunta.getId(), pregunta.getCorrectas(), params.get(pregunta.getId().toString())}); } Map<String, Object> resultados = new HashMap<>(); resultados.put("examen", examen); resultados.put("totalExamen", totalExamen); resultados.put("totalUsuario", totalUsuario); resultados.put("totales", new String[]{totalUsuario.toString(), totalExamen.toString(), examen.getPuntos().toString()}); if (examen.getPuntos() != null && totalUsuario < examen.getPuntos()) { resultados.put("messageTitle", "desaprobado"); resultados.put("messageType", "alert-error"); Long contenidoId = new Long(params.get("contenidoId")[0]); Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId()); Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido != null && alumnoContenido.getTerminado() != null) { alumnoContenido.setIniciado(null); alumnoContenido.setTerminado(null); currentSession().update(alumnoContenido); currentSession().flush(); } } else { resultados.put("messageTitle", "aprobado"); resultados.put("messageType", "alert-success"); for (String key : params.keySet()) { log.debug("{} : {}", key, params.get(key)); } Long contenidoId = new Long(params.get("contenidoId")[0]); Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId()); Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId); AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido); AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk); if (alumnoContenido != null) { alumnoContenido.setTerminado(new Date()); currentSession().update(alumnoContenido); currentSession().flush(); } } if (incorrectas.size() > 0) { resultados.put("incorrectas", incorrectas); } return resultados; } catch (PortalException | SystemException e) { log.error("No se pudo calificar el examen", e); } return null; }
diff --git a/src/com/cooliris/media/Gallery.java b/src/com/cooliris/media/Gallery.java index 361d16b..62d47e2 100644 --- a/src/com/cooliris/media/Gallery.java +++ b/src/com/cooliris/media/Gallery.java @@ -1,396 +1,403 @@ package com.cooliris.media; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashMap; import java.util.TimeZone; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.provider.MediaStore.Images; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import android.media.MediaScannerConnection; import com.cooliris.cache.CacheService; import com.cooliris.wallpaper.RandomDataSource; import com.cooliris.wallpaper.Slideshow; public final class Gallery extends Activity { public static final TimeZone CURRENT_TIME_ZONE = TimeZone.getDefault(); public static float PIXEL_DENSITY = 0.0f; public static final int CROP_MSG_INTERNAL = 100; private static final String TAG = "Gallery"; private static final int CROP_MSG = 10; private RenderView mRenderView = null; private GridLayer mGridLayer; private final Handler mHandler = new Handler(); private ReverseGeocoder mReverseGeocoder; private boolean mPause; private MediaScannerConnection mConnection; private WakeLock mWakeLock; private HashMap<String, Boolean> mAccountsEnabled = new HashMap<String, Boolean>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final boolean imageManagerHasStorage = ImageManager.quickHasStorage(); + boolean slideshowIntent = false; + if (isViewIntent()) { + Bundle extras = getIntent().getExtras(); + if (extras != null) { + slideshowIntent = extras.getBoolean("slideshow", false); + } + } if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI) - && getIntent().getExtras().getBoolean("slideshow", false)) { + && slideshowIntent) { if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); finish(); } else { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "GridView.Slideshow.All"); mWakeLock.acquire(); Slideshow slideshow = new Slideshow(this); slideshow.setDataSource(new RandomDataSource()); setContentView(slideshow); } return; } CacheService.computeDirtySets(this); final boolean isCacheReady = CacheService.isCacheReady(false); if (PIXEL_DENSITY == 0.0f) { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); PIXEL_DENSITY = metrics.density; } mReverseGeocoder = new ReverseGeocoder(this); mRenderView = new RenderView(this); mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4), mRenderView); mRenderView.setRootLayer(mGridLayer); setContentView(mRenderView); // Creating the DataSource objects. final PicasaDataSource picasaDataSource = new PicasaDataSource(this); final LocalDataSource localDataSource = new LocalDataSource(this); final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource); // Depending upon the intent, we assign the right dataSource. if (!isPickIntent() && !isViewIntent()) { if (imageManagerHasStorage) { mGridLayer.setDataSource(combinedDataSource); } else { mGridLayer.setDataSource(picasaDataSource); } if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); } else if (!isCacheReady) { Toast.makeText(this, getResources().getString(R.string.loading_new), Toast.LENGTH_LONG).show(); } } else if (!isViewIntent()) { final Intent intent = getIntent(); if (intent != null) { final String type = intent.resolveType(this); boolean includeImages = isImageType(type); boolean includeVideos = isVideoType(type); ((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos); if (includeImages) { if (imageManagerHasStorage) { mGridLayer.setDataSource(combinedDataSource); } else { mGridLayer.setDataSource(picasaDataSource); } } else { mGridLayer.setDataSource(localDataSource); } mGridLayer.setPickIntent(true); if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG).show(); } } } else { // View intent for images. Uri uri = getIntent().getData(); boolean slideshow = getIntent().getBooleanExtra("slideshow", false); final SingleDataSource singleDataSource = new SingleDataSource(this, uri.toString(), slideshow); final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource); mGridLayer.setDataSource(singleCombinedDataSource); mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri)); if (singleDataSource.isSingleImage()) { mGridLayer.setSingleImage(false); } else if (slideshow) { mGridLayer.setSingleImage(true); mGridLayer.startSlideshow(); } } // We record the set of enabled accounts for picasa. mAccountsEnabled = PicasaDataSource.getAccountStatus(this); Log.i(TAG, "onCreate"); } public ReverseGeocoder getReverseGeocoder() { return mReverseGeocoder; } public Handler getHandler() { return mHandler; } @Override public void onRestart() { super.onRestart(); } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); CacheService.computeDirtySets(this); CacheService.startCache(this, false); if (mRenderView != null) { mRenderView.onResume(); } if (mPause) { // We check to see if the authenticated accounts have changed, and // if so, reload the datasource. HashMap<String, Boolean> accountsEnabled = PicasaDataSource.getAccountStatus(this); String[] keys = new String[accountsEnabled.size()]; keys = accountsEnabled.keySet().toArray(keys); int numKeys = keys.length; for (int i = 0; i < numKeys; ++i) { String key = keys[i]; boolean newValue = accountsEnabled.get(key).booleanValue(); boolean oldValue = false; Boolean oldValObj = mAccountsEnabled.get(key); if (oldValObj != null) { oldValue = oldValObj.booleanValue(); } if (oldValue != newValue) { // Reload the datasource. if (mGridLayer != null) mGridLayer.setDataSource(mGridLayer.getDataSource()); break; } } mAccountsEnabled = accountsEnabled; mPause = false; } } @Override public void onPause() { super.onPause(); if (mRenderView != null) mRenderView.onPause(); mPause = true; } public boolean isPaused() { return mPause; } @Override public void onStop() { super.onStop(); if (mGridLayer != null) mGridLayer.stop(); if (mReverseGeocoder != null) { mReverseGeocoder.flushCache(); } LocalDataSource.sThumbnailCache.flush(); LocalDataSource.sThumbnailCacheVideo.flush(); PicasaDataSource.sThumbnailCache.flush(); CacheService.startCache(this, true); } @Override public void onDestroy() { // Force GLThread to exit. setContentView(R.layout.main); if (mGridLayer != null) { DataSource dataSource = mGridLayer.getDataSource(); if (dataSource != null) { dataSource.shutdown(); } mGridLayer.shutdown(); } if (mWakeLock != null) { if (mWakeLock.isHeld()) { mWakeLock.release(); } mWakeLock = null; } if (mReverseGeocoder != null) mReverseGeocoder.shutdown(); if (mRenderView != null) { mRenderView.shutdown(); mRenderView = null; } mGridLayer = null; super.onDestroy(); Log.i(TAG, "onDestroy"); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mGridLayer != null) { mGridLayer.markDirty(30); } if (mRenderView != null) mRenderView.requestRender(); Log.i(TAG, "onConfigurationChanged"); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mRenderView != null) { return mRenderView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); } else { return super.onKeyDown(keyCode, event); } } private boolean isPickIntent() { String action = getIntent().getAction(); return (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)); } private boolean isViewIntent() { String action = getIntent().getAction(); return Intent.ACTION_VIEW.equals(action); } private boolean isImageType(String type) { return type.equals("vnd.android.cursor.dir/image") || type.equals("image/*"); } private boolean isVideoType(String type) { return type.equals("vnd.android.cursor.dir/video") || type.equals("video/*"); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case CROP_MSG: { if (resultCode == RESULT_OK) { setResult(resultCode, data); finish(); } break; } case CROP_MSG_INTERNAL: { // We cropped an image, we must try to set the focus of the camera // to that image. if (resultCode == RESULT_OK) { String contentUri = data.getAction(); if (mGridLayer != null) { mGridLayer.focusItem(contentUri); } } break; } } } @Override public void onLowMemory() { if (mRenderView != null) { mRenderView.handleLowMemory(); } } public void launchCropperOrFinish(final MediaItem item) { final Bundle myExtras = getIntent().getExtras(); String cropValue = myExtras != null ? myExtras.getString("crop") : null; final String contentUri = item.mContentUri; if (cropValue != null) { Bundle newExtras = new Bundle(); if (cropValue.equals("circle")) { newExtras.putString("circleCrop", "true"); } Intent cropIntent = new Intent(); cropIntent.setData(Uri.parse(contentUri)); cropIntent.setClass(this, CropImage.class); cropIntent.putExtras(newExtras); // Pass through any extras that were passed in. cropIntent.putExtras(myExtras); startActivityForResult(cropIntent, CROP_MSG); } else { if (contentUri.startsWith("http://")) { // This is a http uri, we must save it locally first and // generate a content uri from it. final ProgressDialog dialog = ProgressDialog.show(this, this.getResources().getString(R.string.initializing), getResources().getString(R.string.running_face_detection), true, false); if (contentUri != null) { MediaScannerConnection.MediaScannerConnectionClient client = new MediaScannerConnection.MediaScannerConnectionClient() { public void onMediaScannerConnected() { if (mConnection != null) { try { final String path = UriTexture.writeHttpDataInDirectory(Gallery.this, contentUri, LocalDataSource.DOWNLOAD_BUCKET_NAME); if (path != null) { mConnection.scanFile(path, item.mMimeType); } else { shutdown(""); } } catch (Exception e) { shutdown(""); } } } public void onScanCompleted(String path, Uri uri) { shutdown(uri.toString()); } public void shutdown(String uri) { dialog.dismiss(); performReturn(myExtras, uri.toString()); if (mConnection != null) { mConnection.disconnect(); } } }; MediaScannerConnection connection = new MediaScannerConnection(Gallery.this, client); connection.connect(); mConnection = connection; } } else { performReturn(myExtras, contentUri); } } } private void performReturn(Bundle myExtras, String contentUri) { Intent result = new Intent(null, Uri.parse(contentUri)); if (myExtras != null && myExtras.getBoolean("return-data")) { // The size of a transaction should be below 100K. Bitmap bitmap = null; try { bitmap = UriTexture.createFromUri(this, contentUri, 1024, 1024, 0, null); } catch (IOException e) { ; } catch (URISyntaxException e) { ; } if (bitmap != null) { result.putExtra("data", bitmap); } } setResult(RESULT_OK, result); finish(); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final boolean imageManagerHasStorage = ImageManager.quickHasStorage(); if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI) && getIntent().getExtras().getBoolean("slideshow", false)) { if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); finish(); } else { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "GridView.Slideshow.All"); mWakeLock.acquire(); Slideshow slideshow = new Slideshow(this); slideshow.setDataSource(new RandomDataSource()); setContentView(slideshow); } return; } CacheService.computeDirtySets(this); final boolean isCacheReady = CacheService.isCacheReady(false); if (PIXEL_DENSITY == 0.0f) { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); PIXEL_DENSITY = metrics.density; } mReverseGeocoder = new ReverseGeocoder(this); mRenderView = new RenderView(this); mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4), mRenderView); mRenderView.setRootLayer(mGridLayer); setContentView(mRenderView); // Creating the DataSource objects. final PicasaDataSource picasaDataSource = new PicasaDataSource(this); final LocalDataSource localDataSource = new LocalDataSource(this); final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource); // Depending upon the intent, we assign the right dataSource. if (!isPickIntent() && !isViewIntent()) { if (imageManagerHasStorage) { mGridLayer.setDataSource(combinedDataSource); } else { mGridLayer.setDataSource(picasaDataSource); } if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); } else if (!isCacheReady) { Toast.makeText(this, getResources().getString(R.string.loading_new), Toast.LENGTH_LONG).show(); } } else if (!isViewIntent()) { final Intent intent = getIntent(); if (intent != null) { final String type = intent.resolveType(this); boolean includeImages = isImageType(type); boolean includeVideos = isVideoType(type); ((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos); if (includeImages) { if (imageManagerHasStorage) { mGridLayer.setDataSource(combinedDataSource); } else { mGridLayer.setDataSource(picasaDataSource); } } else { mGridLayer.setDataSource(localDataSource); } mGridLayer.setPickIntent(true); if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG).show(); } } } else { // View intent for images. Uri uri = getIntent().getData(); boolean slideshow = getIntent().getBooleanExtra("slideshow", false); final SingleDataSource singleDataSource = new SingleDataSource(this, uri.toString(), slideshow); final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource); mGridLayer.setDataSource(singleCombinedDataSource); mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri)); if (singleDataSource.isSingleImage()) { mGridLayer.setSingleImage(false); } else if (slideshow) { mGridLayer.setSingleImage(true); mGridLayer.startSlideshow(); } } // We record the set of enabled accounts for picasa. mAccountsEnabled = PicasaDataSource.getAccountStatus(this); Log.i(TAG, "onCreate"); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final boolean imageManagerHasStorage = ImageManager.quickHasStorage(); boolean slideshowIntent = false; if (isViewIntent()) { Bundle extras = getIntent().getExtras(); if (extras != null) { slideshowIntent = extras.getBoolean("slideshow", false); } } if (isViewIntent() && getIntent().getData().equals(Images.Media.EXTERNAL_CONTENT_URI) && slideshowIntent) { if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); finish(); } else { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "GridView.Slideshow.All"); mWakeLock.acquire(); Slideshow slideshow = new Slideshow(this); slideshow.setDataSource(new RandomDataSource()); setContentView(slideshow); } return; } CacheService.computeDirtySets(this); final boolean isCacheReady = CacheService.isCacheReady(false); if (PIXEL_DENSITY == 0.0f) { DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); PIXEL_DENSITY = metrics.density; } mReverseGeocoder = new ReverseGeocoder(this); mRenderView = new RenderView(this); mGridLayer = new GridLayer(this, (int) (96.0f * PIXEL_DENSITY), (int) (72.0f * PIXEL_DENSITY), new GridLayoutInterface(4), mRenderView); mRenderView.setRootLayer(mGridLayer); setContentView(mRenderView); // Creating the DataSource objects. final PicasaDataSource picasaDataSource = new PicasaDataSource(this); final LocalDataSource localDataSource = new LocalDataSource(this); final ConcatenatedDataSource combinedDataSource = new ConcatenatedDataSource(localDataSource, picasaDataSource); // Depending upon the intent, we assign the right dataSource. if (!isPickIntent() && !isViewIntent()) { if (imageManagerHasStorage) { mGridLayer.setDataSource(combinedDataSource); } else { mGridLayer.setDataSource(picasaDataSource); } if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); } else if (!isCacheReady) { Toast.makeText(this, getResources().getString(R.string.loading_new), Toast.LENGTH_LONG).show(); } } else if (!isViewIntent()) { final Intent intent = getIntent(); if (intent != null) { final String type = intent.resolveType(this); boolean includeImages = isImageType(type); boolean includeVideos = isVideoType(type); ((LocalDataSource) localDataSource).setMimeFilter(!includeImages, !includeVideos); if (includeImages) { if (imageManagerHasStorage) { mGridLayer.setDataSource(combinedDataSource); } else { mGridLayer.setDataSource(picasaDataSource); } } else { mGridLayer.setDataSource(localDataSource); } mGridLayer.setPickIntent(true); if (!imageManagerHasStorage) { Toast.makeText(this, getResources().getString(R.string.no_sd_card), Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, getResources().getString(R.string.pick_prompt), Toast.LENGTH_LONG).show(); } } } else { // View intent for images. Uri uri = getIntent().getData(); boolean slideshow = getIntent().getBooleanExtra("slideshow", false); final SingleDataSource singleDataSource = new SingleDataSource(this, uri.toString(), slideshow); final ConcatenatedDataSource singleCombinedDataSource = new ConcatenatedDataSource(singleDataSource, picasaDataSource); mGridLayer.setDataSource(singleCombinedDataSource); mGridLayer.setViewIntent(true, Utils.getBucketNameFromUri(uri)); if (singleDataSource.isSingleImage()) { mGridLayer.setSingleImage(false); } else if (slideshow) { mGridLayer.setSingleImage(true); mGridLayer.startSlideshow(); } } // We record the set of enabled accounts for picasa. mAccountsEnabled = PicasaDataSource.getAccountStatus(this); Log.i(TAG, "onCreate"); }
diff --git a/src/de/shandschuh/sparserss/EntryActivity.java b/src/de/shandschuh/sparserss/EntryActivity.java index 865f6c1..432db72 100644 --- a/src/de/shandschuh/sparserss/EntryActivity.java +++ b/src/de/shandschuh/sparserss/EntryActivity.java @@ -1,105 +1,105 @@ /** * Sparse rss * * Copyright (c) 2010 Stefan Handschuh * * 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 de.shandschuh.sparserss; import java.text.DateFormat; import java.util.Date; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.widget.Button; import android.widget.TextView; import de.shandschuh.sparserss.provider.FeedData; public class EntryActivity extends Activity { private static final String NEWLINE = "\n"; private static final String BR = "<br/>"; private static final String TEXT_HTML = "text/html"; private static final String UTF8 = "utf-8"; private Cursor entryCursor; private int titlePosition; private int datePosition; private int abstractPosition; private int linkPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.entry); Uri uri = getIntent().getData(); ContentValues values = new ContentValues(); values.put(FeedData.EntryColumns.READDATE, System.currentTimeMillis()); getContentResolver().update(uri, values, new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null); entryCursor = managedQuery(uri, null, null, null, null); titlePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.TITLE); datePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.DATE); abstractPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.ABSTRACT); linkPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.LINK); reload(); } private void reload() { if (entryCursor.moveToFirst()) { String abstractText = entryCursor.getString(abstractPosition); if (abstractText == null) { finish(); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(entryCursor.getString(linkPosition)))); } else { setTitle(entryCursor.getString(titlePosition)); ((TextView) findViewById(R.id.entry_date)).setText(DateFormat.getDateTimeInstance().format(new Date(entryCursor.getLong(datePosition)))); // loadData does not recognize the encoding without correct html-header - ((WebView) findViewById(R.id.entry_abstract)).loadDataWithBaseURL(null, abstractText.replace(NEWLINE, BR), TEXT_HTML, UTF8, null); + ((WebView) findViewById(R.id.entry_abstract)).loadDataWithBaseURL(null, abstractText.indexOf('<') > -1 && abstractText.indexOf('>') > -1 ? abstractText : abstractText.replace(NEWLINE, BR), TEXT_HTML, UTF8, null); ((Button) findViewById(R.id.url_button)).setOnClickListener(new OnClickListener() { public void onClick(View view) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(entryCursor.getString(linkPosition)))); } }); } } } }
true
true
private void reload() { if (entryCursor.moveToFirst()) { String abstractText = entryCursor.getString(abstractPosition); if (abstractText == null) { finish(); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(entryCursor.getString(linkPosition)))); } else { setTitle(entryCursor.getString(titlePosition)); ((TextView) findViewById(R.id.entry_date)).setText(DateFormat.getDateTimeInstance().format(new Date(entryCursor.getLong(datePosition)))); // loadData does not recognize the encoding without correct html-header ((WebView) findViewById(R.id.entry_abstract)).loadDataWithBaseURL(null, abstractText.replace(NEWLINE, BR), TEXT_HTML, UTF8, null); ((Button) findViewById(R.id.url_button)).setOnClickListener(new OnClickListener() { public void onClick(View view) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(entryCursor.getString(linkPosition)))); } }); } } }
private void reload() { if (entryCursor.moveToFirst()) { String abstractText = entryCursor.getString(abstractPosition); if (abstractText == null) { finish(); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(entryCursor.getString(linkPosition)))); } else { setTitle(entryCursor.getString(titlePosition)); ((TextView) findViewById(R.id.entry_date)).setText(DateFormat.getDateTimeInstance().format(new Date(entryCursor.getLong(datePosition)))); // loadData does not recognize the encoding without correct html-header ((WebView) findViewById(R.id.entry_abstract)).loadDataWithBaseURL(null, abstractText.indexOf('<') > -1 && abstractText.indexOf('>') > -1 ? abstractText : abstractText.replace(NEWLINE, BR), TEXT_HTML, UTF8, null); ((Button) findViewById(R.id.url_button)).setOnClickListener(new OnClickListener() { public void onClick(View view) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(entryCursor.getString(linkPosition)))); } }); } } }
diff --git a/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/EditClientFromMobileTest.java b/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/EditClientFromMobileTest.java index 6937e771..0bfc110d 100644 --- a/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/EditClientFromMobileTest.java +++ b/ghana-national-web/src/test/java/org/motechproject/ghana/national/functional/mobile/EditClientFromMobileTest.java @@ -1,71 +1,70 @@ package org.motechproject.ghana.national.functional.mobile; import org.apache.commons.collections.MapUtils; import org.motechproject.functional.framework.XformHttpClient; import org.testng.annotations.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.motechproject.functional.framework.XformHttpClient.XFormParser; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertNull; public class EditClientFromMobileTest { @Test public void shouldCheckForMandatoryFields() throws Exception { final XformHttpClient.XformResponse xformResponse = XformHttpClient.execute("http://localhost:8080/ghana-national-web/formupload", "NurseDataEntry", XFormParser.parse("edit-client-template.xml", MapUtils.EMPTY_MAP)); final List<XformHttpClient.Error> errors = xformResponse.getErrors(); assertEquals(errors.size(), 1); final Map<String, List<String>> errorsMap = errors.iterator().next().getErrors(); assertThat(errorsMap.get("staffId"), hasItem("is mandatory")); assertThat(errorsMap.get("updatePatientFacilityId"), hasItem("is mandatory")); assertThat(errorsMap.get("motechId"), hasItem("is mandatory")); assertThat(errorsMap.get("date"), hasItem("is mandatory")); } @Test public void shouldGiveErrorIfIdsAreNotFound() throws Exception { final XformHttpClient.XformResponse xformResponse = XformHttpClient.execute("http://localhost:8080/ghana-national-web/formupload", "NurseDataEntry", XFormParser.parse("edit-client-template.xml", new HashMap<String, String>() {{ put("facilityId", "testFacilityId"); put("motechId" , "testMotechId"); put("staffId" , "testStaffId"); put("motherMotechId" , "testMotherMotechId"); }})); final List<XformHttpClient.Error> errors = xformResponse.getErrors(); assertEquals(errors.size(), 1); final Map<String, List<String>> errorsMap = errors.iterator().next().getErrors(); - assertThat(errorsMap.get("date"), hasItem("not found")); assertThat(errorsMap.get("facilityId"), hasItem("not found")); assertThat(errorsMap.get("staffId"), hasItem("not found")); assertThat(errorsMap.get("motechId"), hasItem("not found")); } @Test public void shouldNotGiveErrorForFirstNameIfGiven() throws Exception { final XformHttpClient.XformResponse xformResponse = XformHttpClient.execute("http://localhost:8080/ghana-national-web/formupload", "NurseDataEntry", XFormParser.parse("edit-client-template.xml", new HashMap<String, String>() {{ put("firstName", "Joe"); }})); final List<XformHttpClient.Error> errors = xformResponse.getErrors(); assertEquals(errors.size(), 1); final Map<String, List<String>> errorsMap = errors.iterator().next().getErrors(); assertNull(errorsMap.get("firstName")); } }
true
true
public void shouldGiveErrorIfIdsAreNotFound() throws Exception { final XformHttpClient.XformResponse xformResponse = XformHttpClient.execute("http://localhost:8080/ghana-national-web/formupload", "NurseDataEntry", XFormParser.parse("edit-client-template.xml", new HashMap<String, String>() {{ put("facilityId", "testFacilityId"); put("motechId" , "testMotechId"); put("staffId" , "testStaffId"); put("motherMotechId" , "testMotherMotechId"); }})); final List<XformHttpClient.Error> errors = xformResponse.getErrors(); assertEquals(errors.size(), 1); final Map<String, List<String>> errorsMap = errors.iterator().next().getErrors(); assertThat(errorsMap.get("date"), hasItem("not found")); assertThat(errorsMap.get("facilityId"), hasItem("not found")); assertThat(errorsMap.get("staffId"), hasItem("not found")); assertThat(errorsMap.get("motechId"), hasItem("not found")); }
public void shouldGiveErrorIfIdsAreNotFound() throws Exception { final XformHttpClient.XformResponse xformResponse = XformHttpClient.execute("http://localhost:8080/ghana-national-web/formupload", "NurseDataEntry", XFormParser.parse("edit-client-template.xml", new HashMap<String, String>() {{ put("facilityId", "testFacilityId"); put("motechId" , "testMotechId"); put("staffId" , "testStaffId"); put("motherMotechId" , "testMotherMotechId"); }})); final List<XformHttpClient.Error> errors = xformResponse.getErrors(); assertEquals(errors.size(), 1); final Map<String, List<String>> errorsMap = errors.iterator().next().getErrors(); assertThat(errorsMap.get("facilityId"), hasItem("not found")); assertThat(errorsMap.get("staffId"), hasItem("not found")); assertThat(errorsMap.get("motechId"), hasItem("not found")); }
diff --git a/src/main/java/com/nullblock/vemacs/perplayer/tasks/CheckPlayerTask.java b/src/main/java/com/nullblock/vemacs/perplayer/tasks/CheckPlayerTask.java index 1ec5ba0..4db4202 100644 --- a/src/main/java/com/nullblock/vemacs/perplayer/tasks/CheckPlayerTask.java +++ b/src/main/java/com/nullblock/vemacs/perplayer/tasks/CheckPlayerTask.java @@ -1,72 +1,75 @@ package com.nullblock.vemacs.perplayer.tasks; import java.util.Iterator; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.entity.Entity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import com.nullblock.vemacs.perplayer.PerPlayer; import com.nullblock.vemacs.perplayer.threads.MonitorThread; public class CheckPlayerTask extends BukkitRunnable { private Player player; private int radius; private int limit; private int safe; private int pass; private int delaytick = 20; public CheckPlayerTask(Player player, int radius, int limit, int safe) { this.player = player; this.radius = radius; this.limit = limit; this.safe = safe; } public void run() { if ((!MonitorThread.threadcounter.contains(player.getName())) && (!(player == null))) { List<Entity> entities = player.getNearbyEntities(radius, radius, radius); Iterator cleanup = entities.iterator(); while (cleanup.hasNext()) { Entity checked = (Entity) cleanup.next(); if (!(checked instanceof Monster)) { cleanup.remove(); } } if (entities.size() > limit) { Bukkit.getPluginManager() .getPlugin("PerPlayer") .getLogger() .info(player.getName() + " hit the limit of " + limit + " monsters within a radius of " + radius + " blocks!"); - for (int i = 0; i < Math.ceil((entities.size() - safe) / 10); i++) { + for (int i = 0; i < Math.ceil((entities.size() - safe) / (Bukkit + .getPluginManager() + .getPlugin("PerPlayer").getConfig() + .getInt("pass"))); i++) { Bukkit.getServer() .getScheduler() .runTaskLater( Bukkit.getPluginManager().getPlugin( "PerPlayer"), new DepopTask(entities, Bukkit .getPluginManager() .getPlugin("PerPlayer").getConfig() .getInt("pass")), delaytick * i); } MonitorThread.threadcounter.add(player.getName()); Bukkit.getServer() .getScheduler() .runTaskLater( Bukkit.getPluginManager() .getPlugin("PerPlayer"), new RemoveList(player), (long) (delaytick * Math.ceil((entities.size() - safe))) / 10); } } } }
true
true
public void run() { if ((!MonitorThread.threadcounter.contains(player.getName())) && (!(player == null))) { List<Entity> entities = player.getNearbyEntities(radius, radius, radius); Iterator cleanup = entities.iterator(); while (cleanup.hasNext()) { Entity checked = (Entity) cleanup.next(); if (!(checked instanceof Monster)) { cleanup.remove(); } } if (entities.size() > limit) { Bukkit.getPluginManager() .getPlugin("PerPlayer") .getLogger() .info(player.getName() + " hit the limit of " + limit + " monsters within a radius of " + radius + " blocks!"); for (int i = 0; i < Math.ceil((entities.size() - safe) / 10); i++) { Bukkit.getServer() .getScheduler() .runTaskLater( Bukkit.getPluginManager().getPlugin( "PerPlayer"), new DepopTask(entities, Bukkit .getPluginManager() .getPlugin("PerPlayer").getConfig() .getInt("pass")), delaytick * i); } MonitorThread.threadcounter.add(player.getName()); Bukkit.getServer() .getScheduler() .runTaskLater( Bukkit.getPluginManager() .getPlugin("PerPlayer"), new RemoveList(player), (long) (delaytick * Math.ceil((entities.size() - safe))) / 10); } } }
public void run() { if ((!MonitorThread.threadcounter.contains(player.getName())) && (!(player == null))) { List<Entity> entities = player.getNearbyEntities(radius, radius, radius); Iterator cleanup = entities.iterator(); while (cleanup.hasNext()) { Entity checked = (Entity) cleanup.next(); if (!(checked instanceof Monster)) { cleanup.remove(); } } if (entities.size() > limit) { Bukkit.getPluginManager() .getPlugin("PerPlayer") .getLogger() .info(player.getName() + " hit the limit of " + limit + " monsters within a radius of " + radius + " blocks!"); for (int i = 0; i < Math.ceil((entities.size() - safe) / (Bukkit .getPluginManager() .getPlugin("PerPlayer").getConfig() .getInt("pass"))); i++) { Bukkit.getServer() .getScheduler() .runTaskLater( Bukkit.getPluginManager().getPlugin( "PerPlayer"), new DepopTask(entities, Bukkit .getPluginManager() .getPlugin("PerPlayer").getConfig() .getInt("pass")), delaytick * i); } MonitorThread.threadcounter.add(player.getName()); Bukkit.getServer() .getScheduler() .runTaskLater( Bukkit.getPluginManager() .getPlugin("PerPlayer"), new RemoveList(player), (long) (delaytick * Math.ceil((entities.size() - safe))) / 10); } } }
diff --git a/core/java/android/widget/RelativeLayout.java b/core/java/android/widget/RelativeLayout.java index 24c0e2a4..e19a93dc 100644 --- a/core/java/android/widget/RelativeLayout.java +++ b/core/java/android/widget/RelativeLayout.java @@ -1,1449 +1,1453 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget; import com.android.internal.R; import android.content.Context; import android.content.res.TypedArray; import android.content.res.Resources; import android.graphics.Rect; import android.util.AttributeSet; import android.util.SparseArray; import android.util.Poolable; import android.util.Pool; import android.util.Pools; import android.util.PoolableManager; import static android.util.Log.d; import android.view.Gravity; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.widget.RemoteViews.RemoteView; import java.util.Comparator; import java.util.SortedSet; import java.util.TreeSet; import java.util.LinkedList; import java.util.HashSet; import java.util.ArrayList; /** * A Layout where the positions of the children can be described in relation to each other or to the * parent. For the sake of efficiency, the relations between views are evaluated in one pass, so if * view Y is dependent on the position of view X, make sure the view X comes first in the layout. * * <p> * Note that you cannot have a circular dependency between the size of the RelativeLayout and the * position of its children. For example, you cannot have a RelativeLayout whose height is set to * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT WRAP_CONTENT} and a child set to * {@link #ALIGN_PARENT_BOTTOM}. * </p> * * <p> * Also see {@link android.widget.RelativeLayout.LayoutParams RelativeLayout.LayoutParams} for * layout attributes * </p> * * @attr ref android.R.styleable#RelativeLayout_gravity * @attr ref android.R.styleable#RelativeLayout_ignoreGravity */ @RemoteView public class RelativeLayout extends ViewGroup { private static final String LOG_TAG = "RelativeLayout"; private static final boolean DEBUG_GRAPH = false; public static final int TRUE = -1; /** * Rule that aligns a child's right edge with another child's left edge. */ public static final int LEFT_OF = 0; /** * Rule that aligns a child's left edge with another child's right edge. */ public static final int RIGHT_OF = 1; /** * Rule that aligns a child's bottom edge with another child's top edge. */ public static final int ABOVE = 2; /** * Rule that aligns a child's top edge with another child's bottom edge. */ public static final int BELOW = 3; /** * Rule that aligns a child's baseline with another child's baseline. */ public static final int ALIGN_BASELINE = 4; /** * Rule that aligns a child's left edge with another child's left edge. */ public static final int ALIGN_LEFT = 5; /** * Rule that aligns a child's top edge with another child's top edge. */ public static final int ALIGN_TOP = 6; /** * Rule that aligns a child's right edge with another child's right edge. */ public static final int ALIGN_RIGHT = 7; /** * Rule that aligns a child's bottom edge with another child's bottom edge. */ public static final int ALIGN_BOTTOM = 8; /** * Rule that aligns the child's left edge with its RelativeLayout * parent's left edge. */ public static final int ALIGN_PARENT_LEFT = 9; /** * Rule that aligns the child's top edge with its RelativeLayout * parent's top edge. */ public static final int ALIGN_PARENT_TOP = 10; /** * Rule that aligns the child's right edge with its RelativeLayout * parent's right edge. */ public static final int ALIGN_PARENT_RIGHT = 11; /** * Rule that aligns the child's bottom edge with its RelativeLayout * parent's bottom edge. */ public static final int ALIGN_PARENT_BOTTOM = 12; /** * Rule that centers the child with respect to the bounds of its * RelativeLayout parent. */ public static final int CENTER_IN_PARENT = 13; /** * Rule that centers the child horizontally with respect to the * bounds of its RelativeLayout parent. */ public static final int CENTER_HORIZONTAL = 14; /** * Rule that centers the child vertically with respect to the * bounds of its RelativeLayout parent. */ public static final int CENTER_VERTICAL = 15; private static final int VERB_COUNT = 16; private View mBaselineView = null; private boolean mHasBaselineAlignedChild; private int mGravity = Gravity.LEFT | Gravity.TOP; private final Rect mContentBounds = new Rect(); private final Rect mSelfBounds = new Rect(); private int mIgnoreGravity; private SortedSet<View> mTopToBottomLeftToRightSet = null; private boolean mDirtyHierarchy; private View[] mSortedHorizontalChildren = new View[0]; private View[] mSortedVerticalChildren = new View[0]; private final DependencyGraph mGraph = new DependencyGraph(); public RelativeLayout(Context context) { super(context); } public RelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); initFromAttributes(context, attrs); } public RelativeLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initFromAttributes(context, attrs); } private void initFromAttributes(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RelativeLayout); mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, View.NO_ID); mGravity = a.getInt(R.styleable.RelativeLayout_gravity, mGravity); a.recycle(); } /** * Defines which View is ignored when the gravity is applied. This setting has no * effect if the gravity is <code>Gravity.LEFT | Gravity.TOP</code>. * * @param viewId The id of the View to be ignored by gravity, or 0 if no View * should be ignored. * * @see #setGravity(int) * * @attr ref android.R.styleable#RelativeLayout_ignoreGravity */ @android.view.RemotableViewMethod public void setIgnoreGravity(int viewId) { mIgnoreGravity = viewId; } /** * Describes how the child views are positioned. Defaults to * <code>Gravity.LEFT | Gravity.TOP</code>. * * @param gravity See {@link android.view.Gravity} * * @see #setHorizontalGravity(int) * @see #setVerticalGravity(int) * * @attr ref android.R.styleable#RelativeLayout_gravity */ @android.view.RemotableViewMethod public void setGravity(int gravity) { if (mGravity != gravity) { if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { gravity |= Gravity.LEFT; } if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { gravity |= Gravity.TOP; } mGravity = gravity; requestLayout(); } } @android.view.RemotableViewMethod public void setHorizontalGravity(int horizontalGravity) { final int gravity = horizontalGravity & Gravity.HORIZONTAL_GRAVITY_MASK; if ((mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != gravity) { mGravity = (mGravity & ~Gravity.HORIZONTAL_GRAVITY_MASK) | gravity; requestLayout(); } } @android.view.RemotableViewMethod public void setVerticalGravity(int verticalGravity) { final int gravity = verticalGravity & Gravity.VERTICAL_GRAVITY_MASK; if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != gravity) { mGravity = (mGravity & ~Gravity.VERTICAL_GRAVITY_MASK) | gravity; requestLayout(); } } @Override public int getBaseline() { return mBaselineView != null ? mBaselineView.getBaseline() : super.getBaseline(); } @Override public void requestLayout() { super.requestLayout(); mDirtyHierarchy = true; } private void sortChildren() { int count = getChildCount(); if (mSortedVerticalChildren.length != count) mSortedVerticalChildren = new View[count]; if (mSortedHorizontalChildren.length != count) mSortedHorizontalChildren = new View[count]; final DependencyGraph graph = mGraph; graph.clear(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); graph.add(child); } if (DEBUG_GRAPH) { d(LOG_TAG, "=== Sorted vertical children"); graph.log(getResources(), ABOVE, BELOW, ALIGN_BASELINE, ALIGN_TOP, ALIGN_BOTTOM); d(LOG_TAG, "=== Sorted horizontal children"); graph.log(getResources(), LEFT_OF, RIGHT_OF, ALIGN_LEFT, ALIGN_RIGHT); } graph.getSortedViews(mSortedVerticalChildren, ABOVE, BELOW, ALIGN_BASELINE, ALIGN_TOP, ALIGN_BOTTOM); graph.getSortedViews(mSortedHorizontalChildren, LEFT_OF, RIGHT_OF, ALIGN_LEFT, ALIGN_RIGHT); if (DEBUG_GRAPH) { d(LOG_TAG, "=== Ordered list of vertical children"); for (View view : mSortedVerticalChildren) { DependencyGraph.printViewId(getResources(), view); } d(LOG_TAG, "=== Ordered list of horizontal children"); for (View view : mSortedHorizontalChildren) { DependencyGraph.printViewId(getResources(), view); } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mDirtyHierarchy) { mDirtyHierarchy = false; sortChildren(); } int myWidth = -1; int myHeight = -1; int width = 0; int height = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // Record our dimensions if they are known; if (widthMode != MeasureSpec.UNSPECIFIED) { myWidth = widthSize; } if (heightMode != MeasureSpec.UNSPECIFIED) { myHeight = heightSize; } if (widthMode == MeasureSpec.EXACTLY) { width = myWidth; } if (heightMode == MeasureSpec.EXACTLY) { height = myHeight; } mHasBaselineAlignedChild = false; View ignore = null; int gravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; final boolean horizontalGravity = gravity != Gravity.LEFT && gravity != 0; gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; final boolean verticalGravity = gravity != Gravity.TOP && gravity != 0; int left = Integer.MAX_VALUE; int top = Integer.MAX_VALUE; int right = Integer.MIN_VALUE; int bottom = Integer.MIN_VALUE; boolean offsetHorizontalAxis = false; boolean offsetVerticalAxis = false; if ((horizontalGravity || verticalGravity) && mIgnoreGravity != View.NO_ID) { ignore = findViewById(mIgnoreGravity); } final boolean isWrapContentWidth = widthMode != MeasureSpec.EXACTLY; final boolean isWrapContentHeight = heightMode != MeasureSpec.EXACTLY; View[] views = mSortedHorizontalChildren; int count = views.length; for (int i = 0; i < count; i++) { View child = views[i]; if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); applyHorizontalSizeRules(params, myWidth); measureChildHorizontal(child, params, myWidth, myHeight); if (positionChildHorizontal(child, params, myWidth, isWrapContentWidth)) { offsetHorizontalAxis = true; } } } views = mSortedVerticalChildren; count = views.length; for (int i = 0; i < count; i++) { View child = views[i]; if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); applyVerticalSizeRules(params, myHeight); measureChild(child, params, myWidth, myHeight); if (positionChildVertical(child, params, myHeight, isWrapContentHeight)) { offsetVerticalAxis = true; } if (isWrapContentWidth) { width = Math.max(width, params.mRight); } if (isWrapContentHeight) { height = Math.max(height, params.mBottom); } if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } if (mHasBaselineAlignedChild) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); alignBaseline(child, params); if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } } if (isWrapContentWidth) { // Width already has left padding in it since it was calculated by looking at // the right of each child view width += mPaddingRight; if (mLayoutParams.width >= 0) { width = Math.max(width, mLayoutParams.width); } width = Math.max(width, getSuggestedMinimumWidth()); width = resolveSize(width, widthMeasureSpec); if (offsetHorizontalAxis) { - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); final int[] rules = params.getRules(); if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) { centerHorizontal(child, params, width); } } } } } if (isWrapContentHeight) { // Height already has top padding in it since it was calculated by looking at // the bottom of each child view height += mPaddingBottom; if (mLayoutParams.height >= 0) { height = Math.max(height, mLayoutParams.height); } height = Math.max(height, getSuggestedMinimumHeight()); height = resolveSize(height, heightMeasureSpec); if (offsetVerticalAxis) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); final int[] rules = params.getRules(); if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) { centerVertical(child, params, height); } } } } } if (horizontalGravity || verticalGravity) { final Rect selfBounds = mSelfBounds; selfBounds.set(mPaddingLeft, mPaddingTop, width - mPaddingRight, height - mPaddingBottom); final Rect contentBounds = mContentBounds; Gravity.apply(mGravity, right - left, bottom - top, selfBounds, contentBounds); final int horizontalOffset = contentBounds.left - left; final int verticalOffset = contentBounds.top - top; if (horizontalOffset != 0 || verticalOffset != 0) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE && child != ignore) { LayoutParams params = (LayoutParams) child.getLayoutParams(); - params.mLeft += horizontalOffset; - params.mRight += horizontalOffset; - params.mTop += verticalOffset; - params.mBottom += verticalOffset; + if (horizontalGravity) { + params.mLeft += horizontalOffset; + params.mRight += horizontalOffset; + } + if (verticalGravity) { + params.mTop += verticalOffset; + params.mBottom += verticalOffset; + } } } } } setMeasuredDimension(width, height); } private void alignBaseline(View child, LayoutParams params) { int[] rules = params.getRules(); int anchorBaseline = getRelatedViewBaseline(rules, ALIGN_BASELINE); if (anchorBaseline != -1) { LayoutParams anchorParams = getRelatedViewParams(rules, ALIGN_BASELINE); if (anchorParams != null) { int offset = anchorParams.mTop + anchorBaseline; int baseline = child.getBaseline(); if (baseline != -1) { offset -= baseline; } int height = params.mBottom - params.mTop; params.mTop = offset; params.mBottom = params.mTop + height; } } if (mBaselineView == null) { mBaselineView = child; } else { LayoutParams lp = (LayoutParams) mBaselineView.getLayoutParams(); if (params.mTop < lp.mTop || (params.mTop == lp.mTop && params.mLeft < lp.mLeft)) { mBaselineView = child; } } } /** * Measure a child. The child should have left, top, right and bottom information * stored in its LayoutParams. If any of these values is -1 it means that the view * can extend up to the corresponding edge. * * @param child Child to measure * @param params LayoutParams associated with child * @param myWidth Width of the the RelativeLayout * @param myHeight Height of the RelativeLayout */ private void measureChild(View child, LayoutParams params, int myWidth, int myHeight) { int childWidthMeasureSpec = getChildMeasureSpec(params.mLeft, params.mRight, params.width, params.leftMargin, params.rightMargin, mPaddingLeft, mPaddingRight, myWidth); int childHeightMeasureSpec = getChildMeasureSpec(params.mTop, params.mBottom, params.height, params.topMargin, params.bottomMargin, mPaddingTop, mPaddingBottom, myHeight); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } private void measureChildHorizontal(View child, LayoutParams params, int myWidth, int myHeight) { int childWidthMeasureSpec = getChildMeasureSpec(params.mLeft, params.mRight, params.width, params.leftMargin, params.rightMargin, mPaddingLeft, mPaddingRight, myWidth); int childHeightMeasureSpec; if (params.width == LayoutParams.FILL_PARENT) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(myHeight, MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(myHeight, MeasureSpec.AT_MOST); } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } /** * Get a measure spec that accounts for all of the constraints on this view. * This includes size contstraints imposed by the RelativeLayout as well as * the View's desired dimension. * * @param childStart The left or top field of the child's layout params * @param childEnd The right or bottom field of the child's layout params * @param childSize The child's desired size (the width or height field of * the child's layout params) * @param startMargin The left or top margin * @param endMargin The right or bottom margin * @param startPadding mPaddingLeft or mPaddingTop * @param endPadding mPaddingRight or mPaddingBottom * @param mySize The width or height of this view (the RelativeLayout) * @return MeasureSpec for the child */ private int getChildMeasureSpec(int childStart, int childEnd, int childSize, int startMargin, int endMargin, int startPadding, int endPadding, int mySize) { int childSpecMode = 0; int childSpecSize = 0; // Figure out start and end bounds. int tempStart = childStart; int tempEnd = childEnd; // If the view did not express a layout constraint for an edge, use // view's margins and our padding if (tempStart < 0) { tempStart = startPadding + startMargin; } if (tempEnd < 0) { tempEnd = mySize - endPadding - endMargin; } // Figure out maximum size available to this view int maxAvailable = tempEnd - tempStart; if (childStart >= 0 && childEnd >= 0) { // Constraints fixed both edges, so child must be an exact size childSpecMode = MeasureSpec.EXACTLY; childSpecSize = maxAvailable; } else { if (childSize >= 0) { // Child wanted an exact size. Give as much as possible childSpecMode = MeasureSpec.EXACTLY; if (maxAvailable >= 0) { // We have a maxmum size in this dimension. childSpecSize = Math.min(maxAvailable, childSize); } else { // We can grow in this dimension. childSpecSize = childSize; } } else if (childSize == LayoutParams.FILL_PARENT) { // Child wanted to be as big as possible. Give all availble // space childSpecMode = MeasureSpec.EXACTLY; childSpecSize = maxAvailable; } else if (childSize == LayoutParams.WRAP_CONTENT) { // Child wants to wrap content. Use AT_MOST // to communicate available space if we know // our max size if (maxAvailable >= 0) { // We have a maxmum size in this dimension. childSpecMode = MeasureSpec.AT_MOST; childSpecSize = maxAvailable; } else { // We can grow in this dimension. Child can be as big as it // wants childSpecMode = MeasureSpec.UNSPECIFIED; childSpecSize = 0; } } } return MeasureSpec.makeMeasureSpec(childSpecSize, childSpecMode); } private boolean positionChildHorizontal(View child, LayoutParams params, int myWidth, boolean wrapContent) { int[] rules = params.getRules(); if (params.mLeft < 0 && params.mRight >= 0) { // Right is fixed, but left varies params.mLeft = params.mRight - child.getMeasuredWidth(); } else if (params.mLeft >= 0 && params.mRight < 0) { // Left is fixed, but right varies params.mRight = params.mLeft + child.getMeasuredWidth(); } else if (params.mLeft < 0 && params.mRight < 0) { // Both left and right vary if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) { if (!wrapContent) { centerHorizontal(child, params, myWidth); } else { params.mLeft = mPaddingLeft + params.leftMargin; params.mRight = params.mLeft + child.getMeasuredWidth(); } return true; } else { params.mLeft = mPaddingLeft + params.leftMargin; params.mRight = params.mLeft + child.getMeasuredWidth(); } } return false; } private boolean positionChildVertical(View child, LayoutParams params, int myHeight, boolean wrapContent) { int[] rules = params.getRules(); if (params.mTop < 0 && params.mBottom >= 0) { // Bottom is fixed, but top varies params.mTop = params.mBottom - child.getMeasuredHeight(); } else if (params.mTop >= 0 && params.mBottom < 0) { // Top is fixed, but bottom varies params.mBottom = params.mTop + child.getMeasuredHeight(); } else if (params.mTop < 0 && params.mBottom < 0) { // Both top and bottom vary if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) { if (!wrapContent) { centerVertical(child, params, myHeight); } else { params.mTop = mPaddingTop + params.topMargin; params.mBottom = params.mTop + child.getMeasuredHeight(); } return true; } else { params.mTop = mPaddingTop + params.topMargin; params.mBottom = params.mTop + child.getMeasuredHeight(); } } return false; } private void applyHorizontalSizeRules(LayoutParams childParams, int myWidth) { int[] rules = childParams.getRules(); RelativeLayout.LayoutParams anchorParams; // -1 indicated a "soft requirement" in that direction. For example: // left=10, right=-1 means the view must start at 10, but can go as far as it wants to the right // left =-1, right=10 means the view must end at 10, but can go as far as it wants to the left // left=10, right=20 means the left and right ends are both fixed childParams.mLeft = -1; childParams.mRight = -1; anchorParams = getRelatedViewParams(rules, LEFT_OF); if (anchorParams != null) { childParams.mRight = anchorParams.mLeft - (anchorParams.leftMargin + childParams.rightMargin); } else if (childParams.alignWithParent && rules[LEFT_OF] != 0) { if (myWidth >= 0) { childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin; } else { // FIXME uh oh... } } anchorParams = getRelatedViewParams(rules, RIGHT_OF); if (anchorParams != null) { childParams.mLeft = anchorParams.mRight + (anchorParams.rightMargin + childParams.leftMargin); } else if (childParams.alignWithParent && rules[RIGHT_OF] != 0) { childParams.mLeft = mPaddingLeft + childParams.leftMargin; } anchorParams = getRelatedViewParams(rules, ALIGN_LEFT); if (anchorParams != null) { childParams.mLeft = anchorParams.mLeft + childParams.leftMargin; } else if (childParams.alignWithParent && rules[ALIGN_LEFT] != 0) { childParams.mLeft = mPaddingLeft + childParams.leftMargin; } anchorParams = getRelatedViewParams(rules, ALIGN_RIGHT); if (anchorParams != null) { childParams.mRight = anchorParams.mRight - childParams.rightMargin; } else if (childParams.alignWithParent && rules[ALIGN_RIGHT] != 0) { if (myWidth >= 0) { childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin; } else { // FIXME uh oh... } } if (0 != rules[ALIGN_PARENT_LEFT]) { childParams.mLeft = mPaddingLeft + childParams.leftMargin; } if (0 != rules[ALIGN_PARENT_RIGHT]) { if (myWidth >= 0) { childParams.mRight = myWidth - mPaddingRight - childParams.rightMargin; } else { // FIXME uh oh... } } } private void applyVerticalSizeRules(LayoutParams childParams, int myHeight) { int[] rules = childParams.getRules(); RelativeLayout.LayoutParams anchorParams; childParams.mTop = -1; childParams.mBottom = -1; anchorParams = getRelatedViewParams(rules, ABOVE); if (anchorParams != null) { childParams.mBottom = anchorParams.mTop - (anchorParams.topMargin + childParams.bottomMargin); } else if (childParams.alignWithParent && rules[ABOVE] != 0) { if (myHeight >= 0) { childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin; } else { // FIXME uh oh... } } anchorParams = getRelatedViewParams(rules, BELOW); if (anchorParams != null) { childParams.mTop = anchorParams.mBottom + (anchorParams.bottomMargin + childParams.topMargin); } else if (childParams.alignWithParent && rules[BELOW] != 0) { childParams.mTop = mPaddingTop + childParams.topMargin; } anchorParams = getRelatedViewParams(rules, ALIGN_TOP); if (anchorParams != null) { childParams.mTop = anchorParams.mTop + childParams.topMargin; } else if (childParams.alignWithParent && rules[ALIGN_TOP] != 0) { childParams.mTop = mPaddingTop + childParams.topMargin; } anchorParams = getRelatedViewParams(rules, ALIGN_BOTTOM); if (anchorParams != null) { childParams.mBottom = anchorParams.mBottom - childParams.bottomMargin; } else if (childParams.alignWithParent && rules[ALIGN_BOTTOM] != 0) { if (myHeight >= 0) { childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin; } else { // FIXME uh oh... } } if (0 != rules[ALIGN_PARENT_TOP]) { childParams.mTop = mPaddingTop + childParams.topMargin; } if (0 != rules[ALIGN_PARENT_BOTTOM]) { if (myHeight >= 0) { childParams.mBottom = myHeight - mPaddingBottom - childParams.bottomMargin; } else { // FIXME uh oh... } } if (rules[ALIGN_BASELINE] != 0) { mHasBaselineAlignedChild = true; } } private View getRelatedView(int[] rules, int relation) { int id = rules[relation]; if (id != 0) { DependencyGraph.Node node = mGraph.mKeyNodes.get(id); if (node == null) return null; View v = node.view; // Find the first non-GONE view up the chain while (v.getVisibility() == View.GONE) { rules = ((LayoutParams) v.getLayoutParams()).getRules(); node = mGraph.mKeyNodes.get((rules[relation])); if (node == null) return null; v = node.view; } return v; } return null; } private LayoutParams getRelatedViewParams(int[] rules, int relation) { View v = getRelatedView(rules, relation); if (v != null) { ViewGroup.LayoutParams params = v.getLayoutParams(); if (params instanceof LayoutParams) { return (LayoutParams) v.getLayoutParams(); } } return null; } private int getRelatedViewBaseline(int[] rules, int relation) { View v = getRelatedView(rules, relation); if (v != null) { return v.getBaseline(); } return -1; } private void centerHorizontal(View child, LayoutParams params, int myWidth) { int childWidth = child.getMeasuredWidth(); int left = (myWidth - childWidth) / 2; params.mLeft = left; params.mRight = left + childWidth; } private void centerVertical(View child, LayoutParams params, int myHeight) { int childHeight = child.getMeasuredHeight(); int top = (myHeight - childHeight) / 2; params.mTop = top; params.mBottom = top + childHeight; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // The layout has actually already been performed and the positions // cached. Apply the cached values to the children. int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { RelativeLayout.LayoutParams st = (RelativeLayout.LayoutParams) child.getLayoutParams(); child.layout(st.mLeft, st.mTop, st.mRight, st.mBottom); } } } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new RelativeLayout.LayoutParams(getContext(), attrs); } /** * Returns a set of layout parameters with a width of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, * a height of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} and no spanning. */ @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } // Override to allow type-checking of LayoutParams. @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof RelativeLayout.LayoutParams; } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { if (mTopToBottomLeftToRightSet == null) { mTopToBottomLeftToRightSet = new TreeSet<View>(new TopToBottomLeftToRightComparator()); } // sort children top-to-bottom and left-to-right for (int i = 0, count = getChildCount(); i < count; i++) { mTopToBottomLeftToRightSet.add(getChildAt(i)); } for (View view : mTopToBottomLeftToRightSet) { if (view.dispatchPopulateAccessibilityEvent(event)) { mTopToBottomLeftToRightSet.clear(); return true; } } mTopToBottomLeftToRightSet.clear(); return false; } /** * Compares two views in left-to-right and top-to-bottom fashion. */ private class TopToBottomLeftToRightComparator implements Comparator<View> { public int compare(View first, View second) { // top - bottom int topDifference = first.getTop() - second.getTop(); if (topDifference != 0) { return topDifference; } // left - right int leftDifference = first.getLeft() - second.getLeft(); if (leftDifference != 0) { return leftDifference; } // break tie by height int heightDiference = first.getHeight() - second.getHeight(); if (heightDiference != 0) { return heightDiference; } // break tie by width int widthDiference = first.getWidth() - second.getWidth(); if (widthDiference != 0) { return widthDiference; } return 0; } } /** * Per-child layout information associated with RelativeLayout. * * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignWithParentIfMissing * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toLeftOf * @attr ref android.R.styleable#RelativeLayout_Layout_layout_toRightOf * @attr ref android.R.styleable#RelativeLayout_Layout_layout_above * @attr ref android.R.styleable#RelativeLayout_Layout_layout_below * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBaseline * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignLeft * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignTop * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignRight * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignBottom * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentLeft * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentTop * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentRight * @attr ref android.R.styleable#RelativeLayout_Layout_layout_alignParentBottom * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerInParent * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerHorizontal * @attr ref android.R.styleable#RelativeLayout_Layout_layout_centerVertical */ public static class LayoutParams extends ViewGroup.MarginLayoutParams { @ViewDebug.ExportedProperty(resolveId = true, indexMapping = { @ViewDebug.IntToString(from = ABOVE, to = "above"), @ViewDebug.IntToString(from = ALIGN_BASELINE, to = "alignBaseline"), @ViewDebug.IntToString(from = ALIGN_BOTTOM, to = "alignBottom"), @ViewDebug.IntToString(from = ALIGN_LEFT, to = "alignLeft"), @ViewDebug.IntToString(from = ALIGN_PARENT_BOTTOM, to = "alignParentBottom"), @ViewDebug.IntToString(from = ALIGN_PARENT_LEFT, to = "alignParentLeft"), @ViewDebug.IntToString(from = ALIGN_PARENT_RIGHT, to = "alignParentRight"), @ViewDebug.IntToString(from = ALIGN_PARENT_TOP, to = "alignParentTop"), @ViewDebug.IntToString(from = ALIGN_RIGHT, to = "alignRight"), @ViewDebug.IntToString(from = ALIGN_TOP, to = "alignTop"), @ViewDebug.IntToString(from = BELOW, to = "below"), @ViewDebug.IntToString(from = CENTER_HORIZONTAL, to = "centerHorizontal"), @ViewDebug.IntToString(from = CENTER_IN_PARENT, to = "center"), @ViewDebug.IntToString(from = CENTER_VERTICAL, to = "centerVertical"), @ViewDebug.IntToString(from = LEFT_OF, to = "leftOf"), @ViewDebug.IntToString(from = RIGHT_OF, to = "rightOf") }, mapping = { @ViewDebug.IntToString(from = TRUE, to = "true"), @ViewDebug.IntToString(from = 0, to = "false/NO_ID") }) private int[] mRules = new int[VERB_COUNT]; private int mLeft, mTop, mRight, mBottom; /** * When true, uses the parent as the anchor if the anchor doesn't exist or if * the anchor's visibility is GONE. */ @ViewDebug.ExportedProperty public boolean alignWithParent; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); TypedArray a = c.obtainStyledAttributes(attrs, com.android.internal.R.styleable.RelativeLayout_Layout); final int[] rules = mRules; final int N = a.getIndexCount(); for (int i = 0; i < N; i++) { int attr = a.getIndex(i); switch (attr) { case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignWithParentIfMissing: alignWithParent = a.getBoolean(attr, false); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toLeftOf: rules[LEFT_OF] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_toRightOf: rules[RIGHT_OF] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_above: rules[ABOVE] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_below: rules[BELOW] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBaseline: rules[ALIGN_BASELINE] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignLeft: rules[ALIGN_LEFT] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignTop: rules[ALIGN_TOP] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignRight: rules[ALIGN_RIGHT] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignBottom: rules[ALIGN_BOTTOM] = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentLeft: rules[ALIGN_PARENT_LEFT] = a.getBoolean(attr, false) ? TRUE : 0; break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentTop: rules[ALIGN_PARENT_TOP] = a.getBoolean(attr, false) ? TRUE : 0; break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentRight: rules[ALIGN_PARENT_RIGHT] = a.getBoolean(attr, false) ? TRUE : 0; break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_alignParentBottom: rules[ALIGN_PARENT_BOTTOM] = a.getBoolean(attr, false) ? TRUE : 0; break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerInParent: rules[CENTER_IN_PARENT] = a.getBoolean(attr, false) ? TRUE : 0; break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerHorizontal: rules[CENTER_HORIZONTAL] = a.getBoolean(attr, false) ? TRUE : 0; break; case com.android.internal.R.styleable.RelativeLayout_Layout_layout_centerVertical: rules[CENTER_VERTICAL] = a.getBoolean(attr, false) ? TRUE : 0; break; } } a.recycle(); } public LayoutParams(int w, int h) { super(w, h); } /** * {@inheritDoc} */ public LayoutParams(ViewGroup.LayoutParams source) { super(source); } /** * {@inheritDoc} */ public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } @Override public String debug(String output) { return output + "ViewGroup.LayoutParams={ width=" + sizeToString(width) + ", height=" + sizeToString(height) + " }"; } /** * Adds a layout rule to be interpreted by the RelativeLayout. This * method should only be used for constraints that don't refer to another sibling * (e.g., CENTER_IN_PARENT) or take a boolean value ({@link RelativeLayout#TRUE} * for true or - for false). To specify a verb that takes a subject, use * {@link #addRule(int, int)} instead. * * @param verb One of the verbs defined by * {@link android.widget.RelativeLayout RelativeLayout}, such as * ALIGN_WITH_PARENT_LEFT. * @see #addRule(int, int) */ public void addRule(int verb) { mRules[verb] = TRUE; } /** * Adds a layout rule to be interpreted by the RelativeLayout. Use this for * verbs that take a target, such as a sibling (ALIGN_RIGHT) or a boolean * value (VISIBLE). * * @param verb One of the verbs defined by * {@link android.widget.RelativeLayout RelativeLayout}, such as * ALIGN_WITH_PARENT_LEFT. * @param anchor The id of another view to use as an anchor, * or a boolean value(represented as {@link RelativeLayout#TRUE}) * for true or 0 for false). For verbs that don't refer to another sibling * (for example, ALIGN_WITH_PARENT_BOTTOM) just use -1. * @see #addRule(int) */ public void addRule(int verb, int anchor) { mRules[verb] = anchor; } /** * Retrieves a complete list of all supported rules, where the index is the rule * verb, and the element value is the value specified, or "false" if it was never * set. * * @return the supported rules * @see #addRule(int, int) */ public int[] getRules() { return mRules; } } private static class DependencyGraph { /** * List of all views in the graph. */ private ArrayList<Node> mNodes = new ArrayList<Node>(); /** * List of nodes in the graph. Each node is identified by its * view id (see View#getId()). */ private SparseArray<Node> mKeyNodes = new SparseArray<Node>(); /** * Temporary data structure used to build the list of roots * for this graph. */ private LinkedList<Node> mRoots = new LinkedList<Node>(); /** * Clears the graph. */ void clear() { final ArrayList<Node> nodes = mNodes; final int count = nodes.size(); for (int i = 0; i < count; i++) { nodes.get(i).release(); } nodes.clear(); mKeyNodes.clear(); mRoots.clear(); } /** * Adds a view to the graph. * * @param view The view to be added as a node to the graph. */ void add(View view) { final int id = view.getId(); final Node node = Node.acquire(view); if (id != View.NO_ID) { mKeyNodes.put(id, node); } mNodes.add(node); } /** * Builds a sorted list of views. The sorting order depends on the dependencies * between the view. For instance, if view C needs view A to be processed first * and view A needs view B to be processed first, the dependency graph * is: B -> A -> C. The sorted array will contain views B, A and C in this order. * * @param sorted The sorted list of views. The length of this array must * be equal to getChildCount(). * @param rules The list of rules to take into account. */ void getSortedViews(View[] sorted, int... rules) { final LinkedList<Node> roots = findRoots(rules); int index = 0; while (roots.size() > 0) { final Node node = roots.removeFirst(); final View view = node.view; final int key = view.getId(); sorted[index++] = view; final HashSet<Node> dependents = node.dependents; for (Node dependent : dependents) { final SparseArray<Node> dependencies = dependent.dependencies; dependencies.remove(key); if (dependencies.size() == 0) { roots.add(dependent); } } } if (index < sorted.length) { throw new IllegalStateException("Circular dependencies cannot exist" + " in RelativeLayout"); } } /** * Finds the roots of the graph. A root is a node with no dependency and * with [0..n] dependents. * * @param rulesFilter The list of rules to consider when building the * dependencies * * @return A list of node, each being a root of the graph */ private LinkedList<Node> findRoots(int[] rulesFilter) { final SparseArray<Node> keyNodes = mKeyNodes; final ArrayList<Node> nodes = mNodes; final int count = nodes.size(); // Find roots can be invoked several times, so make sure to clear // all dependents and dependencies before running the algorithm for (int i = 0; i < count; i++) { final Node node = nodes.get(i); node.dependents.clear(); node.dependencies.clear(); } // Builds up the dependents and dependencies for each node of the graph for (int i = 0; i < count; i++) { final Node node = nodes.get(i); final LayoutParams layoutParams = (LayoutParams) node.view.getLayoutParams(); final int[] rules = layoutParams.mRules; final int rulesCount = rulesFilter.length; // Look only the the rules passed in parameter, this way we build only the // dependencies for a specific set of rules for (int j = 0; j < rulesCount; j++) { final int rule = rules[rulesFilter[j]]; if (rule > 0) { // The node this node depends on final Node dependency = keyNodes.get(rule); // Skip unknowns and self dependencies if (dependency == null || dependency == node) { continue; } // Add the current node as a dependent dependency.dependents.add(node); // Add a dependency to the current node node.dependencies.put(rule, dependency); } } } final LinkedList<Node> roots = mRoots; roots.clear(); // Finds all the roots in the graph: all nodes with no dependencies for (int i = 0; i < count; i++) { final Node node = nodes.get(i); if (node.dependencies.size() == 0) roots.add(node); } return roots; } /** * Prints the dependency graph for the specified rules. * * @param resources The context's resources to print the ids. * @param rules The list of rules to take into account. */ void log(Resources resources, int... rules) { final LinkedList<Node> roots = findRoots(rules); for (Node node : roots) { printNode(resources, node); } } static void printViewId(Resources resources, View view) { if (view.getId() != View.NO_ID) { d(LOG_TAG, resources.getResourceEntryName(view.getId())); } else { d(LOG_TAG, "NO_ID"); } } private static void appendViewId(Resources resources, Node node, StringBuilder buffer) { if (node.view.getId() != View.NO_ID) { buffer.append(resources.getResourceEntryName(node.view.getId())); } else { buffer.append("NO_ID"); } } private static void printNode(Resources resources, Node node) { if (node.dependents.size() == 0) { printViewId(resources, node.view); } else { for (Node dependent : node.dependents) { StringBuilder buffer = new StringBuilder(); appendViewId(resources, node, buffer); printdependents(resources, dependent, buffer); } } } private static void printdependents(Resources resources, Node node, StringBuilder buffer) { buffer.append(" -> "); appendViewId(resources, node, buffer); if (node.dependents.size() == 0) { d(LOG_TAG, buffer.toString()); } else { for (Node dependent : node.dependents) { StringBuilder subBuffer = new StringBuilder(buffer); printdependents(resources, dependent, subBuffer); } } } /** * A node in the dependency graph. A node is a view, its list of dependencies * and its list of dependents. * * A node with no dependent is considered a root of the graph. */ static class Node implements Poolable<Node> { /** * The view representing this node in the layout. */ View view; /** * The list of dependents for this node; a dependent is a node * that needs this node to be processed first. */ final HashSet<Node> dependents = new HashSet<Node>(); /** * The list of dependencies for this node. */ final SparseArray<Node> dependencies = new SparseArray<Node>(); /* * START POOL IMPLEMENTATION */ // The pool is static, so all nodes instances are shared across // activities, that's why we give it a rather high limit private static final int POOL_LIMIT = 100; private static final Pool<Node> sPool = Pools.synchronizedPool( Pools.finitePool(new PoolableManager<Node>() { public Node newInstance() { return new Node(); } public void onAcquired(Node element) { } public void onReleased(Node element) { } }, POOL_LIMIT) ); private Node mNext; public void setNextPoolable(Node element) { mNext = element; } public Node getNextPoolable() { return mNext; } static Node acquire(View view) { final Node node = sPool.acquire(); node.view = view; return node; } void release() { view = null; dependents.clear(); dependencies.clear(); sPool.release(this); } /* * END POOL IMPLEMENTATION */ } } }
false
true
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mDirtyHierarchy) { mDirtyHierarchy = false; sortChildren(); } int myWidth = -1; int myHeight = -1; int width = 0; int height = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // Record our dimensions if they are known; if (widthMode != MeasureSpec.UNSPECIFIED) { myWidth = widthSize; } if (heightMode != MeasureSpec.UNSPECIFIED) { myHeight = heightSize; } if (widthMode == MeasureSpec.EXACTLY) { width = myWidth; } if (heightMode == MeasureSpec.EXACTLY) { height = myHeight; } mHasBaselineAlignedChild = false; View ignore = null; int gravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; final boolean horizontalGravity = gravity != Gravity.LEFT && gravity != 0; gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; final boolean verticalGravity = gravity != Gravity.TOP && gravity != 0; int left = Integer.MAX_VALUE; int top = Integer.MAX_VALUE; int right = Integer.MIN_VALUE; int bottom = Integer.MIN_VALUE; boolean offsetHorizontalAxis = false; boolean offsetVerticalAxis = false; if ((horizontalGravity || verticalGravity) && mIgnoreGravity != View.NO_ID) { ignore = findViewById(mIgnoreGravity); } final boolean isWrapContentWidth = widthMode != MeasureSpec.EXACTLY; final boolean isWrapContentHeight = heightMode != MeasureSpec.EXACTLY; View[] views = mSortedHorizontalChildren; int count = views.length; for (int i = 0; i < count; i++) { View child = views[i]; if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); applyHorizontalSizeRules(params, myWidth); measureChildHorizontal(child, params, myWidth, myHeight); if (positionChildHorizontal(child, params, myWidth, isWrapContentWidth)) { offsetHorizontalAxis = true; } } } views = mSortedVerticalChildren; count = views.length; for (int i = 0; i < count; i++) { View child = views[i]; if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); applyVerticalSizeRules(params, myHeight); measureChild(child, params, myWidth, myHeight); if (positionChildVertical(child, params, myHeight, isWrapContentHeight)) { offsetVerticalAxis = true; } if (isWrapContentWidth) { width = Math.max(width, params.mRight); } if (isWrapContentHeight) { height = Math.max(height, params.mBottom); } if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } if (mHasBaselineAlignedChild) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); alignBaseline(child, params); if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } } if (isWrapContentWidth) { // Width already has left padding in it since it was calculated by looking at // the right of each child view width += mPaddingRight; if (mLayoutParams.width >= 0) { width = Math.max(width, mLayoutParams.width); } width = Math.max(width, getSuggestedMinimumWidth()); width = resolveSize(width, widthMeasureSpec); if (offsetHorizontalAxis) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); final int[] rules = params.getRules(); if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) { centerHorizontal(child, params, width); } } } } } if (isWrapContentHeight) { // Height already has top padding in it since it was calculated by looking at // the bottom of each child view height += mPaddingBottom; if (mLayoutParams.height >= 0) { height = Math.max(height, mLayoutParams.height); } height = Math.max(height, getSuggestedMinimumHeight()); height = resolveSize(height, heightMeasureSpec); if (offsetVerticalAxis) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); final int[] rules = params.getRules(); if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) { centerVertical(child, params, height); } } } } } if (horizontalGravity || verticalGravity) { final Rect selfBounds = mSelfBounds; selfBounds.set(mPaddingLeft, mPaddingTop, width - mPaddingRight, height - mPaddingBottom); final Rect contentBounds = mContentBounds; Gravity.apply(mGravity, right - left, bottom - top, selfBounds, contentBounds); final int horizontalOffset = contentBounds.left - left; final int verticalOffset = contentBounds.top - top; if (horizontalOffset != 0 || verticalOffset != 0) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE && child != ignore) { LayoutParams params = (LayoutParams) child.getLayoutParams(); params.mLeft += horizontalOffset; params.mRight += horizontalOffset; params.mTop += verticalOffset; params.mBottom += verticalOffset; } } } } setMeasuredDimension(width, height); }
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mDirtyHierarchy) { mDirtyHierarchy = false; sortChildren(); } int myWidth = -1; int myHeight = -1; int width = 0; int height = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // Record our dimensions if they are known; if (widthMode != MeasureSpec.UNSPECIFIED) { myWidth = widthSize; } if (heightMode != MeasureSpec.UNSPECIFIED) { myHeight = heightSize; } if (widthMode == MeasureSpec.EXACTLY) { width = myWidth; } if (heightMode == MeasureSpec.EXACTLY) { height = myHeight; } mHasBaselineAlignedChild = false; View ignore = null; int gravity = mGravity & Gravity.HORIZONTAL_GRAVITY_MASK; final boolean horizontalGravity = gravity != Gravity.LEFT && gravity != 0; gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; final boolean verticalGravity = gravity != Gravity.TOP && gravity != 0; int left = Integer.MAX_VALUE; int top = Integer.MAX_VALUE; int right = Integer.MIN_VALUE; int bottom = Integer.MIN_VALUE; boolean offsetHorizontalAxis = false; boolean offsetVerticalAxis = false; if ((horizontalGravity || verticalGravity) && mIgnoreGravity != View.NO_ID) { ignore = findViewById(mIgnoreGravity); } final boolean isWrapContentWidth = widthMode != MeasureSpec.EXACTLY; final boolean isWrapContentHeight = heightMode != MeasureSpec.EXACTLY; View[] views = mSortedHorizontalChildren; int count = views.length; for (int i = 0; i < count; i++) { View child = views[i]; if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); applyHorizontalSizeRules(params, myWidth); measureChildHorizontal(child, params, myWidth, myHeight); if (positionChildHorizontal(child, params, myWidth, isWrapContentWidth)) { offsetHorizontalAxis = true; } } } views = mSortedVerticalChildren; count = views.length; for (int i = 0; i < count; i++) { View child = views[i]; if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); applyVerticalSizeRules(params, myHeight); measureChild(child, params, myWidth, myHeight); if (positionChildVertical(child, params, myHeight, isWrapContentHeight)) { offsetVerticalAxis = true; } if (isWrapContentWidth) { width = Math.max(width, params.mRight); } if (isWrapContentHeight) { height = Math.max(height, params.mBottom); } if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } if (mHasBaselineAlignedChild) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); alignBaseline(child, params); if (child != ignore || verticalGravity) { left = Math.min(left, params.mLeft - params.leftMargin); top = Math.min(top, params.mTop - params.topMargin); } if (child != ignore || horizontalGravity) { right = Math.max(right, params.mRight + params.rightMargin); bottom = Math.max(bottom, params.mBottom + params.bottomMargin); } } } } if (isWrapContentWidth) { // Width already has left padding in it since it was calculated by looking at // the right of each child view width += mPaddingRight; if (mLayoutParams.width >= 0) { width = Math.max(width, mLayoutParams.width); } width = Math.max(width, getSuggestedMinimumWidth()); width = resolveSize(width, widthMeasureSpec); if (offsetHorizontalAxis) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); final int[] rules = params.getRules(); if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_HORIZONTAL] != 0) { centerHorizontal(child, params, width); } } } } } if (isWrapContentHeight) { // Height already has top padding in it since it was calculated by looking at // the bottom of each child view height += mPaddingBottom; if (mLayoutParams.height >= 0) { height = Math.max(height, mLayoutParams.height); } height = Math.max(height, getSuggestedMinimumHeight()); height = resolveSize(height, heightMeasureSpec); if (offsetVerticalAxis) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { LayoutParams params = (LayoutParams) child.getLayoutParams(); final int[] rules = params.getRules(); if (rules[CENTER_IN_PARENT] != 0 || rules[CENTER_VERTICAL] != 0) { centerVertical(child, params, height); } } } } } if (horizontalGravity || verticalGravity) { final Rect selfBounds = mSelfBounds; selfBounds.set(mPaddingLeft, mPaddingTop, width - mPaddingRight, height - mPaddingBottom); final Rect contentBounds = mContentBounds; Gravity.apply(mGravity, right - left, bottom - top, selfBounds, contentBounds); final int horizontalOffset = contentBounds.left - left; final int verticalOffset = contentBounds.top - top; if (horizontalOffset != 0 || verticalOffset != 0) { for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE && child != ignore) { LayoutParams params = (LayoutParams) child.getLayoutParams(); if (horizontalGravity) { params.mLeft += horizontalOffset; params.mRight += horizontalOffset; } if (verticalGravity) { params.mTop += verticalOffset; params.mBottom += verticalOffset; } } } } } setMeasuredDimension(width, height); }
diff --git a/src/com/example/classproject/HelloWorldTest.java b/src/com/example/classproject/HelloWorldTest.java index 979eef5..6f29c9f 100644 --- a/src/com/example/classproject/HelloWorldTest.java +++ b/src/com/example/classproject/HelloWorldTest.java @@ -1,112 +1,113 @@ package com.example.classproject; import org.junit.Test; import java.io.*; import static org.junit.Assert.*; public class HelloWorldTest { @Test public void testCanReadInputFromStream() { ByteArrayInputStream input = getInputStream("something"); try { String result = HelloWorld.readInput(input); assertEquals("something", result); } catch (Exception e) { fail("exception" + e.getMessage()); } } @Test public void testPrintsCorrectStory() { ByteArrayInputStream input = getInputStream("1"); String text = null; try { text = readFile("story/1.txt"); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream output = new ByteArrayOutputStream(); System.setOut(new PrintStream(output)); try { HelloWorld.runProgram("dummy.txt", input); String outputString = output.toString(); +// assertEquals("", outputString); boolean contains = outputString.contains(text); assertTrue(contains); } catch (IOException e) { // fail("exception: " + e.getMessage()); e.printStackTrace(); } } private String readFile(String filename) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File(filename))); String line; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } return builder.toString(); } @Test public void testValidateReturnsTrueIfOk() { String goodInput = "1"; assertTrue(HelloWorld.validateInput(goodInput)); } @Test public void testValidateDoesNotThrowForNonNumeric() { String badInput = "hello"; assertFalse(HelloWorld.validateInput(badInput)); } @Test public void testValidateReturnsFalseIfOutOfStoryRange() { String badInput = "5"; assertFalse(HelloWorld.validateInput(badInput)); } @Test public void runProgramPrintsAnErrorIfUserInputDoesNotValidate() { ByteArrayInputStream input = getInputStream("b"); ByteArrayOutputStream output = new ByteArrayOutputStream(); System.setOut(new PrintStream(output)); try { HelloWorld.promptForInput(input); assertTrue(output.toString().contains("That doesn't look right. Please try again.")); } catch (IOException e) { fail(e.getMessage()); } } @Test public void testShouldPaginateText() { ByteArrayInputStream input = getInputStream("\n"); String firstChunk = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"; String prompt = "Please press enter to view more."; String secondChunk = "11\n12\n13\n14\n\n"; ByteArrayOutputStream output = new ByteArrayOutputStream(); System.setOut(new PrintStream(output)); try { HelloWorld.printText(firstChunk + secondChunk, input); } catch (IOException e) { fail(e.getMessage()); } assertTrue(output.toString().startsWith(firstChunk)); assertTrue(output.toString().contains(prompt)); assertTrue(output.toString().endsWith(secondChunk)); } private ByteArrayInputStream getInputStream(String inputStream) { return new ByteArrayInputStream(inputStream.getBytes()); } }
true
true
public void testPrintsCorrectStory() { ByteArrayInputStream input = getInputStream("1"); String text = null; try { text = readFile("story/1.txt"); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream output = new ByteArrayOutputStream(); System.setOut(new PrintStream(output)); try { HelloWorld.runProgram("dummy.txt", input); String outputString = output.toString(); boolean contains = outputString.contains(text); assertTrue(contains); } catch (IOException e) { // fail("exception: " + e.getMessage()); e.printStackTrace(); } }
public void testPrintsCorrectStory() { ByteArrayInputStream input = getInputStream("1"); String text = null; try { text = readFile("story/1.txt"); } catch (IOException e) { e.printStackTrace(); } ByteArrayOutputStream output = new ByteArrayOutputStream(); System.setOut(new PrintStream(output)); try { HelloWorld.runProgram("dummy.txt", input); String outputString = output.toString(); // assertEquals("", outputString); boolean contains = outputString.contains(text); assertTrue(contains); } catch (IOException e) { // fail("exception: " + e.getMessage()); e.printStackTrace(); } }
diff --git a/elements-harvester/src/main/java/uk/co/symplectic/utils/ExecutorServiceUtils.java b/elements-harvester/src/main/java/uk/co/symplectic/utils/ExecutorServiceUtils.java index aba735a..b6ea0cc 100644 --- a/elements-harvester/src/main/java/uk/co/symplectic/utils/ExecutorServiceUtils.java +++ b/elements-harvester/src/main/java/uk/co/symplectic/utils/ExecutorServiceUtils.java @@ -1,201 +1,204 @@ /******************************************************************************* * Copyright (c) 2012 Symplectic Ltd. All rights reserved. * 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 uk.co.symplectic.utils; import org.apache.commons.lang.StringUtils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; public final class ExecutorServiceUtils { private static Map<String, Integer> maxProcessorsPerPool = new HashMap<String, Integer>(); private ExecutorServiceUtils() { } public static void setMaxProcessorsForPool(String poolName, int size) { maxProcessorsPerPool.put(poolName.toLowerCase(), size); } public static long getCompletedTaskCount(ExecutorService service) { if (service instanceof ThreadPoolExecutor) { return ((ThreadPoolExecutor)service).getCompletedTaskCount(); } return -1; } public static long getTaskCount(ExecutorService service) { if (service instanceof ThreadPoolExecutor) { return ((ThreadPoolExecutor)service).getTaskCount(); } return -1; } public static ExecutorServiceWrapper newFixedThreadPool(String poolName) { int poolSize = Runtime.getRuntime().availableProcessors(); int maxPoolSize = -1; if (!StringUtils.isEmpty(poolName)) { - maxPoolSize = maxProcessorsPerPool.get(poolName.toLowerCase()); + Integer maxPoolSizeObject = maxProcessorsPerPool.get(poolName.toLowerCase()); + if (maxPoolSizeObject != null) { + maxPoolSize = maxPoolSizeObject; + } } if (maxPoolSize > 0 && maxPoolSize < poolSize) { poolSize = maxPoolSize; } /** * Uses a ThreadFactory to create Daemon threads. * * By doing so, when the program exits the main() method - and regardless of whether * System.exit() has been called - Java will not treat the active threads as blocking * the termination. * * This means that the shutdown hook (which is added below) will be run, causing the * graceful termination of the ExecutorService, and the running tasks. * * Without Daemon threads, the program will not terminate, nor will the shutdown hooks be called * unless System.exit is called explicitly. */ ExecutorService service = Executors.newFixedThreadPool(poolSize, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); return thread; } }); if (service != null) { ExecutorServiceWrapper wrapper = new ExecutorServiceWrapper(service); /** * Shutdown hook to gracefully terminate the ExecutorService. Gives any existing tasks a chance to * complete before forcing termination. */ Runtime.getRuntime().addShutdownHook(new ShutdownHook(wrapper)); return wrapper; } return null; } static void shutdown(ExecutorService service, ExecutorShutdownParams params) { if (params == null) { params = new ExecutorShutdownParams(); } service.shutdown(); try { int stalledCount = 0; long lastCompletedTasks = 0; while (!service.awaitTermination(params.getShutdownWaitCycleInSecs(), TimeUnit.SECONDS)) { long completedTasks = ExecutorServiceUtils.getCompletedTaskCount(service); if (completedTasks > -1 && completedTasks == lastCompletedTasks) { System.err.println("Waiting for shutdown of translation service. Completed " + completedTasks + " tasks out of " + ExecutorServiceUtils.getTaskCount(service)); stalledCount++; if (stalledCount > params.getMaxStalledShutdownCycles()) { System.err.println("Waited " + params.getShutdownStalledWaitTimeInSecs() + " seconds without progress. Abandoning."); service.shutdownNow(); if (!service.awaitTermination(params.getShutdownWaitCycleInSecs(), TimeUnit.SECONDS)) { break; } } } else { stalledCount = 0; } lastCompletedTasks = completedTasks; } } catch (InterruptedException e) { e.printStackTrace(); } } private static class ShutdownHook extends Thread { private ExecutorServiceWrapper wrapper; ShutdownHook(ExecutorServiceWrapper wrapper) { this.wrapper = wrapper; } @Override public void run() { wrapper.shutdown(); } } public static class ExecutorServiceWrapper { private ExecutorService service; private ExecutorShutdownParams shutdownParams = new ExecutorShutdownParams(); private boolean shutdownCalled = false; ExecutorServiceWrapper(ExecutorService service) { this.service = service; } public ExecutorService service() { return service; } public ExecutorShutdownParams shutdownParams() { return shutdownParams; } public void shutdown() { if (!shutdownCalled) { shutdownCalled = true; ExecutorServiceUtils.shutdown(service, shutdownParams); } } } public static class ExecutorShutdownParams { private int shutdownStalledWaitTimeInSecs = 300; /* 5 minutes */ private int shutdownWaitCycleInSecs = 30; private int maxStalledShutdownCycles = shutdownStalledWaitTimeInSecs / shutdownWaitCycleInSecs; public ExecutorShutdownParams() {} public ExecutorShutdownParams(int shutdownStalledWaitTimeInSecs) { this.shutdownStalledWaitTimeInSecs = shutdownStalledWaitTimeInSecs; maxStalledShutdownCycles = shutdownStalledWaitTimeInSecs / shutdownWaitCycleInSecs; } public ExecutorShutdownParams(int shutdownStalledWaitTimeInSecs, int shutdownWaitCycleInSecs) { this.shutdownStalledWaitTimeInSecs = shutdownStalledWaitTimeInSecs; this.shutdownWaitCycleInSecs = shutdownWaitCycleInSecs; maxStalledShutdownCycles = shutdownStalledWaitTimeInSecs / shutdownWaitCycleInSecs; } public int getMaxStalledShutdownCycles() { return maxStalledShutdownCycles; } public int getShutdownStalledWaitTimeInSecs() { return shutdownStalledWaitTimeInSecs; } public int getShutdownWaitCycleInSecs() { return shutdownWaitCycleInSecs; } public void setShutdownStalledWaitTimeInSecs(int secs) { shutdownStalledWaitTimeInSecs = secs; maxStalledShutdownCycles = shutdownStalledWaitTimeInSecs / shutdownWaitCycleInSecs; } public void setShutdownWaitCycleInSecs(int secs) { shutdownWaitCycleInSecs = secs; maxStalledShutdownCycles = shutdownStalledWaitTimeInSecs / shutdownWaitCycleInSecs; } } }
true
true
public static ExecutorServiceWrapper newFixedThreadPool(String poolName) { int poolSize = Runtime.getRuntime().availableProcessors(); int maxPoolSize = -1; if (!StringUtils.isEmpty(poolName)) { maxPoolSize = maxProcessorsPerPool.get(poolName.toLowerCase()); } if (maxPoolSize > 0 && maxPoolSize < poolSize) { poolSize = maxPoolSize; } /** * Uses a ThreadFactory to create Daemon threads. * * By doing so, when the program exits the main() method - and regardless of whether * System.exit() has been called - Java will not treat the active threads as blocking * the termination. * * This means that the shutdown hook (which is added below) will be run, causing the * graceful termination of the ExecutorService, and the running tasks. * * Without Daemon threads, the program will not terminate, nor will the shutdown hooks be called * unless System.exit is called explicitly. */ ExecutorService service = Executors.newFixedThreadPool(poolSize, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); return thread; } }); if (service != null) { ExecutorServiceWrapper wrapper = new ExecutorServiceWrapper(service); /** * Shutdown hook to gracefully terminate the ExecutorService. Gives any existing tasks a chance to * complete before forcing termination. */ Runtime.getRuntime().addShutdownHook(new ShutdownHook(wrapper)); return wrapper; } return null; }
public static ExecutorServiceWrapper newFixedThreadPool(String poolName) { int poolSize = Runtime.getRuntime().availableProcessors(); int maxPoolSize = -1; if (!StringUtils.isEmpty(poolName)) { Integer maxPoolSizeObject = maxProcessorsPerPool.get(poolName.toLowerCase()); if (maxPoolSizeObject != null) { maxPoolSize = maxPoolSizeObject; } } if (maxPoolSize > 0 && maxPoolSize < poolSize) { poolSize = maxPoolSize; } /** * Uses a ThreadFactory to create Daemon threads. * * By doing so, when the program exits the main() method - and regardless of whether * System.exit() has been called - Java will not treat the active threads as blocking * the termination. * * This means that the shutdown hook (which is added below) will be run, causing the * graceful termination of the ExecutorService, and the running tasks. * * Without Daemon threads, the program will not terminate, nor will the shutdown hooks be called * unless System.exit is called explicitly. */ ExecutorService service = Executors.newFixedThreadPool(poolSize, new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); return thread; } }); if (service != null) { ExecutorServiceWrapper wrapper = new ExecutorServiceWrapper(service); /** * Shutdown hook to gracefully terminate the ExecutorService. Gives any existing tasks a chance to * complete before forcing termination. */ Runtime.getRuntime().addShutdownHook(new ShutdownHook(wrapper)); return wrapper; } return null; }
diff --git a/src/com/implix/jsonrpc/JsonHttpUrlConnection.java b/src/com/implix/jsonrpc/JsonHttpUrlConnection.java index c4ab784..9e7cec5 100644 --- a/src/com/implix/jsonrpc/JsonHttpUrlConnection.java +++ b/src/com/implix/jsonrpc/JsonHttpUrlConnection.java @@ -1,141 +1,140 @@ package com.implix.jsonrpc; import android.os.Build; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; /** * Created with IntelliJ IDEA. * User: jbogacki * Date: 29.03.2013 * Time: 13:14 * To change this template use File | Settings | File Templates. */ public class JsonHttpUrlConnection implements JsonConnection { JsonRpcImplementation rpc; int reconnections = 3; int connectTimeout = 15000; int methodTimeout = 10000; public JsonHttpUrlConnection(JsonRpcImplementation rpc) { this.rpc = rpc; disableConnectionReuseIfNecessary(); } private void disableConnectionReuseIfNecessary() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { System.setProperty("http.keepAlive", "false"); } } @Override public HttpURLConnection get(String url, String request, int timeout, JsonTimeStat timeStat) throws Exception { HttpURLConnection urlConnection = null; for (int i = 1; i <= reconnections; i++) { try { urlConnection = (HttpURLConnection) new URL(url + request).openConnection(); break; } catch (IOException e) { if (i == reconnections) { throw e; } } } if (rpc.getAuthKey() != null) { urlConnection.addRequestProperty("Authorization", rpc.getAuthKey()); } urlConnection.setConnectTimeout(connectTimeout); if (timeout == 0) { timeout = methodTimeout; } urlConnection.setReadTimeout(timeout); timeStat.setTimeout(timeout); if ((rpc.getDebugFlags() & JsonRpc.REQUEST_DEBUG) > 0) { JsonLoggerImpl.longLog("REQ(GET)", request); } urlConnection.getInputStream(); timeStat.tickConnectionTime(); return urlConnection; } @Override public HttpURLConnection post(String url, Object request, int timeout,JsonTimeStat timeStat) throws Exception { HttpURLConnection urlConnection = null; for (int i = 1; i <= reconnections; i++) { try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); break; } catch (IOException e) { if (i == reconnections) { throw e; } } } urlConnection.addRequestProperty("Content-Type", "application/json"); if (rpc.getAuthKey() != null) { urlConnection.addRequestProperty("Authorization", rpc.getAuthKey()); } urlConnection.setConnectTimeout(connectTimeout); if (timeout == 0) { timeout = methodTimeout; } timeStat.setTimeout(timeout); urlConnection.setReadTimeout(timeout); urlConnection.setDoOutput(true); if ((rpc.getDebugFlags() & JsonRpc.REQUEST_DEBUG) > 0) { String req = rpc.getParser().toJson(request); JsonLoggerImpl.longLog("REQ", req); - urlConnection.setFixedLengthStreamingMode(req.length()); OutputStream stream = urlConnection.getOutputStream(); timeStat.tickConnectionTime(); Writer writer = new BufferedWriter(new OutputStreamWriter(stream)); writer.write(req); writer.close(); } else { OutputStream stream = urlConnection.getOutputStream(); timeStat.tickConnectionTime(); Writer writer = new BufferedWriter(new OutputStreamWriter(stream)); rpc.getParser().toJson(request, writer); writer.close(); } timeStat.tickSendTime(); return urlConnection; } @Override public void setMaxConnections(int max) { System.setProperty("http.maxConnections", max + ""); } public void setReconnections(int reconnections) { this.reconnections = reconnections; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getMethodTimeout() { return methodTimeout; } public void setMethodTimeout(int methodTimeout) { this.methodTimeout = methodTimeout; } }
true
true
public HttpURLConnection post(String url, Object request, int timeout,JsonTimeStat timeStat) throws Exception { HttpURLConnection urlConnection = null; for (int i = 1; i <= reconnections; i++) { try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); break; } catch (IOException e) { if (i == reconnections) { throw e; } } } urlConnection.addRequestProperty("Content-Type", "application/json"); if (rpc.getAuthKey() != null) { urlConnection.addRequestProperty("Authorization", rpc.getAuthKey()); } urlConnection.setConnectTimeout(connectTimeout); if (timeout == 0) { timeout = methodTimeout; } timeStat.setTimeout(timeout); urlConnection.setReadTimeout(timeout); urlConnection.setDoOutput(true); if ((rpc.getDebugFlags() & JsonRpc.REQUEST_DEBUG) > 0) { String req = rpc.getParser().toJson(request); JsonLoggerImpl.longLog("REQ", req); urlConnection.setFixedLengthStreamingMode(req.length()); OutputStream stream = urlConnection.getOutputStream(); timeStat.tickConnectionTime(); Writer writer = new BufferedWriter(new OutputStreamWriter(stream)); writer.write(req); writer.close(); } else { OutputStream stream = urlConnection.getOutputStream(); timeStat.tickConnectionTime(); Writer writer = new BufferedWriter(new OutputStreamWriter(stream)); rpc.getParser().toJson(request, writer); writer.close(); } timeStat.tickSendTime(); return urlConnection; }
public HttpURLConnection post(String url, Object request, int timeout,JsonTimeStat timeStat) throws Exception { HttpURLConnection urlConnection = null; for (int i = 1; i <= reconnections; i++) { try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); break; } catch (IOException e) { if (i == reconnections) { throw e; } } } urlConnection.addRequestProperty("Content-Type", "application/json"); if (rpc.getAuthKey() != null) { urlConnection.addRequestProperty("Authorization", rpc.getAuthKey()); } urlConnection.setConnectTimeout(connectTimeout); if (timeout == 0) { timeout = methodTimeout; } timeStat.setTimeout(timeout); urlConnection.setReadTimeout(timeout); urlConnection.setDoOutput(true); if ((rpc.getDebugFlags() & JsonRpc.REQUEST_DEBUG) > 0) { String req = rpc.getParser().toJson(request); JsonLoggerImpl.longLog("REQ", req); OutputStream stream = urlConnection.getOutputStream(); timeStat.tickConnectionTime(); Writer writer = new BufferedWriter(new OutputStreamWriter(stream)); writer.write(req); writer.close(); } else { OutputStream stream = urlConnection.getOutputStream(); timeStat.tickConnectionTime(); Writer writer = new BufferedWriter(new OutputStreamWriter(stream)); rpc.getParser().toJson(request, writer); writer.close(); } timeStat.tickSendTime(); return urlConnection; }
diff --git a/src/org/rscdaemon/client/mudclient.java b/src/org/rscdaemon/client/mudclient.java index babb6e2..1cf2a41 100644 --- a/src/org/rscdaemon/client/mudclient.java +++ b/src/org/rscdaemon/client/mudclient.java @@ -1,9932 +1,9932 @@ package org.rscdaemon.client; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Properties; import java.util.Map.Entry; import javax.imageio.ImageIO; import org.rscdaemon.client.cache.CacheManager; import org.rscdaemon.client.entityhandling.EntityHandler; import org.rscdaemon.client.gui.OneonOne; import org.rscdaemon.client.gui.QuestionMenuScreen; import org.rscdaemon.client.gui.SmithingScreen; import org.rscdaemon.client.interfaces.InterfaceGUI; import org.rscdaemon.client.interfaces.InterfaceHandler; import org.rscdaemon.client.model.Display; import org.rscdaemon.client.model.Resolutions; import org.rscdaemon.client.model.Sprite; import org.rscdaemon.client.util.Config; import org.rscdaemon.client.util.DataConversions; import org.rscdaemon.client.util.Downloader; import defs.ItemDef; import defs.NPCDef; public class mudclient extends GameWindowMiddleMan { public static Properties config = Config.loadConfig(); InterfaceGUI smithingscreen = null; InterfaceGUI questionmenu = null; // configuration boolean needsClear = false; public static final int SPRITE_MEDIA_START = 2000; public static final int SPRITE_UTIL_START = 2100; public static final int SPRITE_ITEM_START = 2150; public static final int SPRITE_LOGO_START = 3150; public static int SPRITE_PROJECTILE_START = 3160; public static final int SPRITE_TEXTURE_START = 3220; public static ArrayList<String> messages = new ArrayList<String>(); public static int currentChat = 0; public static HashMap<String, File> dataFiles = new HashMap<String, File>(); boolean lastUp = false; private boolean menusLoaded = false; private int cameraVertical = 912; private boolean fog = false; private long startTime = 0; private long serverStartTime = 0; private int fatigue; private String serverLocation = ""; private String localhost; private int prayerMenuIndex = 0; private int magicMenuIndex = 0; private boolean showRoof = true; private boolean autoScreenshot = true; private long expGained = 0; private boolean hasWorldInfo = false; private boolean recording = false; private LinkedList<BufferedImage> frames = new LinkedList<BufferedImage>(); private boolean ignoreNext = false; private int fogVar = 0; private int fps = 50; private int cur_fps; private long lastFps = 0L; private String newQuestNames[] = {}; private final String questName[] = { "Cook's Assistant", "Sheep Shearer", "Black knight's fortress", "Imp catcher", "Vampire slayer", "Romeo & Juliet", "The restless ghost", "Doric's quest", "The knight's sword", "Witch's potion", "Goblin diplomacy", "Ernest the chicken", "Demon Slayer", "Pirate's treasure", "Prince Ali Rescue", "Shield of Arrav", "Dragon Slayer" };// command // == // 233 private byte questStage[] = {}; private Menu questMenu; public File dataFile = null; private int questMenuHandle; private int questPoints = 0;// camera error public static boolean showPackets = false; static mudclient mc; public static final void main(String[] args) throws Exception {// Duel with mc = new mudclient(); mc.appletMode = false; mc.setLogo(Toolkit.getDefaultToolkit().getImage( Config.CONF_DIR + File.separator + "Loading.rscd")); mc.createWindow(mc.windowWidth, mc.windowHeight + 15 - 8, "Angel Development", false); mc.fog = false; /** * Edit this part to have more messages Stand */ mc.messagesArray = new String[5]; mc.messagesTimeout = new int[mc.messagesArray.length]; } public static Resolutions reso = new Resolutions(); public static boolean LOOT_ENABLED = true; private boolean handleCommand(String s) { try { int firstSpace = s.indexOf(" "); String cmd = s; String[] args = new String[0]; if (firstSpace != -1) { cmd = s.substring(0, firstSpace).trim(); args = s.substring(firstSpace + 1).trim().split(" "); } if (cmd.equals("noloot")) { if (!LOOT_ENABLED) { displayMessage("Ground items have been enabled.", 3, 0); LOOT_ENABLED = true; } else { displayMessage( "Ground items have been visually disabled, to enable repeat this command.", 3, 0); LOOT_ENABLED = false; } } if (cmd.equals("offer")) { int id, amount; try { id = Integer.parseInt(args[0]); amount = Integer.parseInt(args[1]); boolean done = false; if (showTradeWindow) { if (tradeMyItemCount >= 12) { displayMessage( "@cya@Your trade offer is currently full", 3, 0); return true; } if (inventoryCount(id) < amount) { displayMessage("@cya@You do not have that many " + EntityHandler.getItemDef(id).getName() + " to offer", 3, 0); return true; } if (!EntityHandler.getItemDef(id).isStackable() && amount > 1) { displayMessage( "@cya@You can only offer 1 non stackable at a time", 3, 0); return true; } for (int c = 0; c < tradeMyItemCount; c++) { if (tradeMyItems[c] == id) { if (EntityHandler.getItemDef(id).isStackable()) { if (inventoryCount(id) < (tradeMyItemsCount[c] + amount)) { displayMessage( "@cya@You do not have that many" + EntityHandler .getItemDef(id) .getName() + " to offer", 3, 0); return true; } tradeMyItemsCount[c] += amount; done = true; } break; } } if (!done) { tradeMyItems[tradeMyItemCount] = id; tradeMyItemsCount[tradeMyItemCount] = amount; tradeMyItemCount++; } super.streamClass.createPacket(70); super.streamClass.addByte(tradeMyItemCount); for (int c = 0; c < tradeMyItemCount; c++) { super.streamClass.add2ByteInt(tradeMyItems[c]); super.streamClass.add4ByteInt(tradeMyItemsCount[c]); } super.streamClass.formatPacket(); tradeOtherAccepted = false; tradeWeAccepted = false; } else if (showDuelWindow) { if (duelMyItemCount >= 12) { displayMessage( "@cya@Your duel offer is currently full", 3, 0); return true; } if (inventoryCount(id) < amount) { displayMessage("@cya@You do not have that many" + EntityHandler.getItemDef(id).getName() + " to offer", 3, 0); return true; } if (!EntityHandler.getItemDef(id).isStackable() && amount > 1) { displayMessage( "@cya@You can only offer 1 non stackable at a time", 3, 0); return true; } for (int c = 0; c < duelMyItemCount; c++) { if (duelMyItems[c] == id) { if (EntityHandler.getItemDef(id).isStackable()) { if (inventoryCount(id) < (duelMyItemsCount[c] + amount)) { displayMessage( "@cya@You do not have that many" + EntityHandler .getItemDef(id) .getName() + " to offer", 3, 0); return true; } duelMyItemsCount[c] += amount; done = true; } break; } } if (!done) { duelMyItems[duelMyItemCount] = id; duelMyItemsCount[duelMyItemCount] = amount; duelMyItemCount++; } super.streamClass.createPacket(123); super.streamClass.addByte(duelMyItemCount); for (int c = 0; c < duelMyItemCount; c++) { super.streamClass.add2ByteInt(duelMyItems[c]); super.streamClass.add4ByteInt(duelMyItemsCount[c]); } super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } else { displayMessage( "@cya@You aren't in a trade/stake, there is nothing to offer to.", 3, 0); } } catch (Exception e) { e.printStackTrace(); displayMessage("@cya@Invalid args!", 3, 0); } return true; } return false; } catch (Exception e) { System.err.println("CAUGHT HERE"); e.printStackTrace(); return false; } } private static String timeSince(long time) { try { int seconds = (int) ((System.currentTimeMillis() - time) / 1000); int minutes = (int) (seconds / 60); int hours = (int) (minutes / 60); int days = (int) (hours / 24); return days + " days " + (hours % 24) + " hours " + (minutes % 60) + " mins"; } catch (Exception e) { return ""; } } private BufferedImage getImage() throws IOException { BufferedImage bufferedImage = new BufferedImage(windowWidth, windowHeight + 11, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); g2d.drawImage(gameGraphics.image, 0, 0, this); g2d.dispose(); return bufferedImage; } private File getEmptyFile(boolean movie) throws IOException { String charName = DataOperations.longToString(DataOperations .stringLength12ToLong(currentUser)); File file = new File(Config.MEDIA_DIR + File.separator + charName); if (!file.exists() || !file.isDirectory()) { file.mkdir(); } String folder = file.getPath() + File.separator; file = null; for (int suffix = 0; file == null || file.exists(); suffix++) { file = movie ? new File(folder + "movie" + suffix + ".mov") : new File(folder + "screenshot" + suffix + ".png"); } return file; } private boolean takeScreenshot(boolean verbose) { try { File file = getEmptyFile(false); ImageIO.write(getImage(), "png", file); if (verbose) { handleServerMessage("Screenshot saved as " + file.getName() + "."); } return true; } catch (IOException e) { e.printStackTrace(); if (verbose) { handleServerMessage("Error saving screenshot."); } return false; } } final void adjustPoints(int atk, int def, int str, int range) { return; } final void method45(int i, int j, int k, int l, int i1, int j1, int k1) { Mob mob = npcArray[i1]; int l1 = mob.currentSprite + (cameraRotation + 16) / 32 & 7; boolean flag = false; int i2 = l1; if (i2 == 5) { i2 = 3; flag = true; } else if (i2 == 6) { i2 = 2; flag = true; } else if (i2 == 7) { i2 = 1; flag = true; } int j2 = i2 * 3 + walkModel[(mob.stepCount / EntityHandler.getNpcDef(mob.type) .getWalkModel()) % 4]; if (mob.currentSprite == 8) { i2 = 5; l1 = 2; flag = false; i -= (EntityHandler.getNpcDef(mob.type).getCombatSprite() * k1) / 100; j2 = i2 * 3 + npcCombatModelArray1[(loginTimer / (EntityHandler .getNpcDef(mob.type).getCombatModel() - 1)) % 8]; } else if (mob.currentSprite == 9) { i2 = 5; l1 = 2; flag = true; i += (EntityHandler.getNpcDef(mob.type).getCombatSprite() * k1) / 100; j2 = i2 * 3 + npcCombatModelArray2[(loginTimer / EntityHandler .getNpcDef(mob.type).getCombatModel()) % 8]; } for (int k2 = 0; k2 < 12; k2++) { int l2 = npcAnimationArray[l1][k2]; int k3 = EntityHandler.getNpcDef(mob.type).getSprite(l2); if (k3 >= 0) { int i4 = 0; int j4 = 0; int k4 = j2; if (flag && i2 >= 1 && i2 <= 3 && EntityHandler.getAnimationDef(k3).hasF()) k4 += 15; if (i2 != 5 || EntityHandler.getAnimationDef(k3).hasA()) { int l4 = k4 + EntityHandler.getAnimationDef(k3).getNumber(); i4 = (i4 * k) / ((GameImage) (gameGraphics)).sprites[l4] .getSomething1(); j4 = (j4 * l) / ((GameImage) (gameGraphics)).sprites[l4] .getSomething2(); int i5 = (k * ((GameImage) (gameGraphics)).sprites[l4] .getSomething1()) / ((GameImage) (gameGraphics)).sprites[EntityHandler .getAnimationDef(k3).getNumber()] .getSomething1(); i4 -= (i5 - k) / 2; int colour = EntityHandler.getAnimationDef(k3) .getCharColour(); int skinColour = 0; if (colour == 1) { colour = EntityHandler.getNpcDef(mob.type) .getHairColour(); skinColour = EntityHandler.getNpcDef(mob.type) .getSkinColour(); } else if (colour == 2) { colour = EntityHandler.getNpcDef(mob.type) .getTopColour(); skinColour = EntityHandler.getNpcDef(mob.type) .getSkinColour(); } else if (colour == 3) { colour = EntityHandler.getNpcDef(mob.type) .getBottomColour(); skinColour = EntityHandler.getNpcDef(mob.type) .getSkinColour(); } gameGraphics.spriteClip4(i + i4, j + j4, i5, l, l4, colour, skinColour, j1, flag); } } } if (mob.lastMessageTimeout > 0) { mobMessagesWidth[mobMessageCount] = gameGraphics.textWidth( mob.lastMessage, 1) / 2; if (mobMessagesWidth[mobMessageCount] > 150) mobMessagesWidth[mobMessageCount] = 150; mobMessagesHeight[mobMessageCount] = (gameGraphics.textWidth( mob.lastMessage, 1) / 300) * gameGraphics.messageFontHeight(1); mobMessagesX[mobMessageCount] = i + k / 2; mobMessagesY[mobMessageCount] = j; mobMessages[mobMessageCount++] = mob.lastMessage; } if (mob.currentSprite == 8 || mob.currentSprite == 9 || mob.combatTimer != 0) { if (mob.combatTimer > 0) { int i3 = i; if (mob.currentSprite == 8) i3 -= (20 * k1) / 100; else if (mob.currentSprite == 9) i3 += (20 * k1) / 100; int l3 = (mob.hitPointsCurrent * 30) / mob.hitPointsBase; anIntArray786[anInt718] = i3 + k / 2; anIntArray787[anInt718] = j; anIntArray788[anInt718++] = l3; } if (mob.combatTimer > 150) { int j3 = i; if (mob.currentSprite == 8) j3 -= (10 * k1) / 100; else if (mob.currentSprite == 9) j3 += (10 * k1) / 100; gameGraphics.drawPicture((j3 + k / 2) - 12, (j + l / 2) - 12, SPRITE_MEDIA_START + 12); gameGraphics.drawText(String.valueOf(mob.anInt164), (j3 + k / 2) - 1, j + l / 2 + 5, 3, 0xffffff); } } } private float pkCombat(float at, float de, float st, float ra, float ma) { // Work out their combat level float hp = playerStatBase[3]; float pr = playerStatBase[5]; if (ra * 1.5 > st + at) { return (float) pkCombat2(at, de, st, ra, ma); } float cmb = (st / 4) + (de / 4) + (hp / 4) + (at / 4) + (pr / 8) + (ma / 8); // formula for a combat based // character return cmb; } private double pkCombat2(float at, float de, float st, float ra, float ma) { // Work out their combat level float hp = playerStatBase[3]; float pr = playerStatBase[5]; double cmb = (de / 4) + (hp / 4) + (pr / 8) + (ma / 8) + (ra / 2.66); // forumla // for // a // ranged // based // character cmb = Math.round(cmb * 100.0) / 100.0; return cmb; } private final void drawPointsScreen() { drawPointsScreen.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); final Menu dPS = drawPointsScreen; int i = 140 + 116; int j = 34 + 135; byte byte0 = 54; if (pkreset) { pkstrtext = dPS.drawText(i - byte0, j + 8, String.valueOf(pkstr), 1, true); pkatktext = dPS.drawText(i + byte0, j + 8, String.valueOf(pkatk), 1, true); j += 50; pkdeftext = dPS.drawText(i - byte0, j + 8, String.valueOf(pkdef), 1, true); pkrangetext = dPS.drawText(i + byte0, j + 8, String.valueOf(pkrange), 1, true); j += 50; pkmagictext = dPS.drawText(i - byte0, j + 8, String.valueOf(pkmagic), 1, true); j += 50; // Work out their combat level float at = playerStatBase[0]; float de = playerStatBase[1]; float st = playerStatBase[2]; float hp = playerStatBase[3]; float ra = playerStatBase[4]; float pr = playerStatBase[5]; float ma = playerStatBase[6]; if (ra * 1.5 > st + at) { double cmb = (de / 4) + (hp / 4) + (pr / 8) + (ma / 8) + (ra / 2.66); // forumla for a ranged based // character pkcombattext = dPS.drawText(90, 50, "Combat level: " + (Math.round(cmb * 100.0) / 100.0), 1, true); } else { float cmb = (st / 4) + (de / 4) + (hp / 4) + (at / 4) + (pr / 8) + (ma / 8); // formula for a combat based // character pkcombattext = dPS.drawText(90, 50, "Combat level: " + cmb, 1, true); } j += 10; pkpointstext = dPS.drawText(90, 70, "Points: " + String.valueOf(pkpoints), 1, true); pkreset = false; } if (dPS.hasActivated(strDownButton)) { if (pkstr == 1) { return; } pkstr--; dPS.updateText(pkstrtext, String.valueOf(pkstr)); pkpoints += pkexperienceArray[pkstr] - pkexperienceArray[pkstr - 1]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(strUpButton)) { if (pkstr == 99) { return; } pkstr++; dPS.updateText(pkstrtext, String.valueOf(pkstr)); pkpoints -= pkexperienceArray[pkstr - 1] - pkexperienceArray[pkstr - 2]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(atkDownButton)) { if (pkatk == 1) { return; } pkatk--; dPS.updateText(pkatktext, String.valueOf(pkatk)); pkpoints += pkexperienceArray[pkatk] - pkexperienceArray[pkatk - 1]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(atkUpButton)) { if (pkatk == 99) { return; } pkatk++; dPS.updateText(pkatktext, String.valueOf(pkatk)); pkpoints -= pkexperienceArray[pkatk - 1] - pkexperienceArray[pkatk - 2]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(defDownButton)) { if (pkdef == 1) { return; } pkdef--; dPS.updateText(pkdeftext, String.valueOf(pkdef)); pkpoints += pkexperienceArray[pkdef] - pkexperienceArray[pkdef - 1]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(defUpButton)) { if (pkdef == 99) { return; } pkdef++; dPS.updateText(pkdeftext, String.valueOf(pkdef)); pkpoints -= pkexperienceArray[pkdef - 1] - pkexperienceArray[pkdef - 2]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(rangeDownButton)) { if (pkrange == 1) { return; } pkrange--; dPS.updateText(pkrangetext, String.valueOf(pkrange)); pkpoints += pkexperienceArray[pkrange] - pkexperienceArray[pkrange - 1]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(rangeUpButton)) { if (pkrange == 99) { return; } pkrange++; dPS.updateText(pkrangetext, String.valueOf(pkrange)); pkpoints -= pkexperienceArray[pkrange - 1] - pkexperienceArray[pkrange - 2]; adjustPoints(pkatk, pkdef, pkstr, pkrange); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(magDownButton)) { if (pkmagic == 1) { return; } pkmagic--; dPS.updateText(pkmagictext, String.valueOf(pkmagic)); pkpoints += pkexperienceArray[pkmagic] - pkexperienceArray[pkmagic - 1]; adjustPoints(pkatk, pkdef, pkstr, pkmagic); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(magUpButton)) { if (pkmagic == 99) { return; } pkmagic++; dPS.updateText(pkmagictext, String.valueOf(pkmagic)); pkpoints -= pkexperienceArray[pkmagic - 1] - pkexperienceArray[pkmagic - 2]; adjustPoints(pkatk, pkdef, pkstr, pkmagic); dPS.updateText(pkpointstext, "Points: " + String.valueOf(pkpoints)); dPS.updateText( pkcombattext, "Combat level: " + String.valueOf(pkCombat(pkatk, pkdef, pkstr, pkrange, pkmagic))); } if (dPS.hasActivated(dPSAcceptButton)) { super.streamClass.createPacket(500); super.streamClass.addByte(pkatk); super.streamClass.addByte(pkdef); super.streamClass.addByte(pkstr); super.streamClass.addByte(pkrange); super.streamClass.formatPacket(); gameGraphics.method211(); showDrawPointsScreen = false; } } private final void drawCharacterLookScreen() { characterDesignMenu.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); if (characterDesignMenu.hasActivated(characterDesignHeadButton1)) do characterHeadType = ((characterHeadType - 1) + EntityHandler .animationCount()) % EntityHandler.animationCount(); while ((EntityHandler.getAnimationDef(characterHeadType) .getGenderModel() & 3) != 1 || (EntityHandler.getAnimationDef(characterHeadType) .getGenderModel() & 4 * characterHeadGender) == 0); if (characterDesignMenu.hasActivated(characterDesignHeadButton2)) do characterHeadType = (characterHeadType + 1) % EntityHandler.animationCount(); while ((EntityHandler.getAnimationDef(characterHeadType) .getGenderModel() & 3) != 1 || (EntityHandler.getAnimationDef(characterHeadType) .getGenderModel() & 4 * characterHeadGender) == 0); if (characterDesignMenu.hasActivated(characterDesignHairColourButton1)) characterHairColour = ((characterHairColour - 1) + characterHairColours.length) % characterHairColours.length; if (characterDesignMenu.hasActivated(characterDesignHairColourButton2)) characterHairColour = (characterHairColour + 1) % characterHairColours.length; if (characterDesignMenu.hasActivated(characterDesignGenderButton1) || characterDesignMenu .hasActivated(characterDesignGenderButton2)) { for (characterHeadGender = 3 - characterHeadGender; (EntityHandler .getAnimationDef(characterHeadType).getGenderModel() & 3) != 1 || (EntityHandler.getAnimationDef(characterHeadType) .getGenderModel() & 4 * characterHeadGender) == 0; characterHeadType = (characterHeadType + 1) % EntityHandler.animationCount()) ; for (; (EntityHandler.getAnimationDef(characterBodyGender) .getGenderModel() & 3) != 2 || (EntityHandler.getAnimationDef(characterBodyGender) .getGenderModel() & 4 * characterHeadGender) == 0; characterBodyGender = (characterBodyGender + 1) % EntityHandler.animationCount()) ; } if (characterDesignMenu.hasActivated(characterDesignTopColourButton1)) characterTopColour = ((characterTopColour - 1) + characterTopBottomColours.length) % characterTopBottomColours.length; if (characterDesignMenu.hasActivated(characterDesignTopColourButton2)) characterTopColour = (characterTopColour + 1) % characterTopBottomColours.length; if (characterDesignMenu.hasActivated(characterDesignSkinColourButton1)) characterSkinColour = ((characterSkinColour - 1) + characterSkinColours.length) % characterSkinColours.length; if (characterDesignMenu.hasActivated(characterDesignSkinColourButton2)) characterSkinColour = (characterSkinColour + 1) % characterSkinColours.length; if (characterDesignMenu .hasActivated(characterDesignBottomColourButton1)) characterBottomColour = ((characterBottomColour - 1) + characterTopBottomColours.length) % characterTopBottomColours.length; if (characterDesignMenu .hasActivated(characterDesignBottomColourButton2)) characterBottomColour = (characterBottomColour + 1) % characterTopBottomColours.length; if (characterDesignMenu.hasActivated(characterDesignAcceptButton)) { super.streamClass.createPacket(218); super.streamClass.addByte(characterHeadGender); super.streamClass.addByte(characterHeadType); super.streamClass.addByte(characterBodyGender); super.streamClass.addByte(character2Colour); super.streamClass.addByte(characterHairColour); super.streamClass.addByte(characterTopColour); super.streamClass.addByte(characterBottomColour); super.streamClass.addByte(characterSkinColour); super.streamClass.formatPacket(); gameGraphics.method211(); showCharacterLookScreen = false; } } private final int inventoryCount(int reqID) { int amount = 0; for (int index = 0; index < inventoryCount; index++) { if (getInventoryItems()[index] == reqID) { if (!EntityHandler.getItemDef(reqID).isStackable()) { amount++; } else { amount += inventoryItemsCount[index]; } } } return amount; } private final void updateLoginScreen() { if (super.socketTimeout > 0) super.socketTimeout--; if (loginScreenNumber == 0) { menuWelcome.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); if (menuWelcome.hasActivated(loginButtonNewUser)) loginScreenNumber = 1; if (menuWelcome.hasActivated(loginButtonExistingUser)) { loginScreenNumber = 2; menuLogin.updateText(loginStatusText, "Please enter your username and password"); menuLogin.updateText(loginUsernameTextBox, currentUser); menuLogin.updateText(loginPasswordTextBox, currentPass); menuLogin.setFocus(loginUsernameTextBox); return; } } else if (loginScreenNumber == 1) { menuNewUser.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); if (menuNewUser.hasActivated(newUserOkButton)) { loginScreenNumber = 0; return; } } else if (loginScreenNumber == 2) { menuLogin.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); if (menuLogin.hasActivated(loginCancelButton)) loginScreenNumber = 0; if (menuLogin.hasActivated(loginUsernameTextBox)) menuLogin.setFocus(loginPasswordTextBox); if (menuLogin.hasActivated(loginPasswordTextBox) || menuLogin.hasActivated(loginOkButton)) { currentUser = menuLogin.getText(loginUsernameTextBox); currentPass = menuLogin.getText(loginPasswordTextBox); login(currentUser, currentPass, false); } } } private final void drawLoginScreen() { hasReceivedWelcomeBoxDetails = false; gameGraphics.f1Toggle = false; gameGraphics.method211(); if (loginScreenNumber == 0 || loginScreenNumber == 1 || loginScreenNumber == 2 || loginScreenNumber == 3) { gameGraphics.drawPicture(3 + xAddition, 0 + yAddition, SPRITE_LOGO_START); } // then register on forum if (loginScreenNumber == 0) menuWelcome.drawMenu(); if (loginScreenNumber == 1) menuNewUser.drawMenu(); if (loginScreenNumber == 2) menuLogin.drawMenu(); gameGraphics.spriteClip4(0, windowHeight, windowWidth, 10, SPRITE_MEDIA_START + 22, 0, 0, 0, false); gameGraphics.drawImage(aGraphics936, 0, 0); } // abuse private final void drawAbuseWindow1() { abuseSelectedType = 0; int i = 135; for (int j = 0; j < 8; j++) { if (super.mouseX > 66 + xAddition && super.mouseX < 446 + xAddition && super.mouseY >= i - 12 + yAddition && super.mouseY < i + 3 + yAddition) abuseSelectedType = j + 1; i += 14; } if (mouseButtonClick != 0 && abuseSelectedType != 0) { mouseButtonClick = 0; showAbuseWindow = 2; super.inputText = ""; super.enteredText = ""; return; } i += 15; if (mouseButtonClick != 0) { mouseButtonClick = 0; if (super.mouseX < 56 + xAddition || super.mouseY < 35 + yAddition || super.mouseX > 456 + xAddition || super.mouseY > 325 - 50 + yAddition) { showAbuseWindow = 0; return; } if (super.mouseX > 66 + xAddition && super.mouseX < 446 + xAddition && super.mouseY >= i - 15 + yAddition && super.mouseY < i + 5 + yAddition) { showAbuseWindow = 0; return; } } gameGraphics.drawBox(56 + xAddition, 35 + yAddition, 400, 240, 0); gameGraphics.drawBoxEdge(56 + xAddition, 35 + yAddition, 400, 240, 0xffffff); i = 50 + yAddition; gameGraphics .drawText( "This form is for reporting players who are breaking our rules", 256 + xAddition, i, 1, 0xffffff); i += 15; gameGraphics .drawText( "Using it sends a snapshot of the last 60 secs of activity to us", 256 + xAddition, i, 1, 0xffffff); i += 15; gameGraphics.drawText("If you misuse this form, you will be banned.", 256 + xAddition, i, 1, 0xff8000); i += 15; i += 10; gameGraphics .drawText( "First indicate which of our 7 rules is being broken. For a detailed", 256 + xAddition, i, 1, 0xffff00); i += 15; gameGraphics .drawText( "explanation of each rule please read the manual on our website.", 256 + xAddition, i, 1, 0xffff00); i += 15; int k; if (abuseSelectedType == 1) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } gameGraphics.drawText("1: Extremly abusive behaviour", 256 + xAddition, i, 1, k); i += 14; if (abuseSelectedType == 2) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } // gameGraphics.drawText("2: Item scamming", 256, i, 1, k); // i += 14; /* * if (abuseSelectedType == 3) { gameGraphics.drawBoxEdge(66, i - 12, * 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } * gameGraphics.drawText("3: Password scamming", 256, i, 1, k); */ // i += 14; /* * if (abuseSelectedType == 4) { gameGraphics.drawBoxEdge(66, i - 12, * 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } */ gameGraphics.drawText("2: Bug abuse", 256 + xAddition, i, 1, k); i += 14; if (abuseSelectedType == 3) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } gameGraphics.drawText("3: Staff impersonation", 256 + xAddition, i, 1, k); i += 14; if (abuseSelectedType == 4) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } gameGraphics.drawText("4: Account trading/selling", 256 + xAddition, i, 1, k); i += 14; if (abuseSelectedType == 5) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } gameGraphics.drawText("5: Macroing", 256 + xAddition, i, 1, k); i += 14; if (abuseSelectedType == 6) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } // gameGraphics.drawText("8: Mutiple logging in", 256, i, 1, k); // i += 14; /* * if (abuseSelectedType == 9) { gameGraphics.drawBoxEdge(66, i - 12, * 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } */ gameGraphics.drawText("6: Encouraging others to break rules", 256 + xAddition, i, 1, k); i += 14; if (abuseSelectedType == 7) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } // gameGraphics.drawText("10: Misuse of customer support", // 256+xAddition, i, 1, k); // i += 14; /* * if (abuseSelectedType == 11) { gameGraphics.drawBoxEdge(66, i - 12, * 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } */ gameGraphics.drawText("7: Advertising / website", 256 + xAddition, i, 1, k); i += 14; if (abuseSelectedType == 8) { gameGraphics.drawBoxEdge(66 + xAddition, i - 12, 380, 15, 0xffffff); k = 0xff8000; } else { k = 0xffffff; } gameGraphics.drawText("8: Real world item trading", 256 + xAddition, i, 1, k); i += 14; i += 15; k = 0xffffff; if (super.mouseX > 196 + xAddition && super.mouseX < 316 + xAddition && super.mouseY > i - 15 && super.mouseY < i + 5) k = 0xffff00; gameGraphics.drawText("Click here to cancel", 256 + xAddition, i, 1, k); } private final void autoRotateCamera() { if ((cameraAutoAngle & 1) == 1 && enginePlayerVisible(cameraAutoAngle)) return; if ((cameraAutoAngle & 1) == 0 && enginePlayerVisible(cameraAutoAngle)) { if (enginePlayerVisible(cameraAutoAngle + 1 & 7)) { cameraAutoAngle = cameraAutoAngle + 1 & 7; return; } if (enginePlayerVisible(cameraAutoAngle + 7 & 7)) cameraAutoAngle = cameraAutoAngle + 7 & 7; return; } int ai[] = { 1, -1, 2, -2, 3, -3, 4 }; for (int i = 0; i < 7; i++) { if (!enginePlayerVisible(cameraAutoAngle + ai[i] + 8 & 7)) continue; cameraAutoAngle = cameraAutoAngle + ai[i] + 8 & 7; break; } if ((cameraAutoAngle & 1) == 0 && enginePlayerVisible(cameraAutoAngle)) { if (enginePlayerVisible(cameraAutoAngle + 1 & 7)) { cameraAutoAngle = cameraAutoAngle + 1 & 7; return; } if (enginePlayerVisible(cameraAutoAngle + 7 & 7)) cameraAutoAngle = cameraAutoAngle + 7 & 7; } } public final Graphics getGraphics() { if (GameWindow.gameFrame != null) { return GameWindow.gameFrame.getGraphics(); } return super.getGraphics(); } final void method52(int i, int j, int k, int l, int i1, int j1, int k1) { Mob mob = playerArray[i1]; if (mob.colourBottomType == 255) return; int l1 = mob.currentSprite + (cameraRotation + 16) / 32 & 7; boolean flag = false; int i2 = l1; if (i2 == 5) { i2 = 3; flag = true; } else if (i2 == 6) { i2 = 2; flag = true; } else if (i2 == 7) { i2 = 1; flag = true; } int j2 = i2 * 3 + walkModel[(mob.stepCount / 6) % 4]; if (mob.currentSprite == 8) { i2 = 5; l1 = 2; flag = false; i -= (5 * k1) / 100; j2 = i2 * 3 + npcCombatModelArray1[(loginTimer / 5) % 8]; } else if (mob.currentSprite == 9) { i2 = 5; l1 = 2; flag = true; i += (5 * k1) / 100; j2 = i2 * 3 + npcCombatModelArray2[(loginTimer / 6) % 8]; } for (int k2 = 0; k2 < 12; k2++) { int l2 = npcAnimationArray[l1][k2]; int l3 = mob.animationCount[l2] - 1; if (l3 >= 0) { int k4 = 0; int i5 = 0; int j5 = j2; if (flag && i2 >= 1 && i2 <= 3) if (EntityHandler.getAnimationDef(l3).hasF()) j5 += 15; else if (l2 == 4 && i2 == 1) { k4 = -22; i5 = -3; j5 = i2 * 3 + walkModel[(2 + mob.stepCount / 6) % 4]; } else if (l2 == 4 && i2 == 2) { k4 = 0; i5 = -8; j5 = i2 * 3 + walkModel[(2 + mob.stepCount / 6) % 4]; } else if (l2 == 4 && i2 == 3) { k4 = 26; i5 = -5; j5 = i2 * 3 + walkModel[(2 + mob.stepCount / 6) % 4]; } else if (l2 == 3 && i2 == 1) { k4 = 22; i5 = 3; j5 = i2 * 3 + walkModel[(2 + mob.stepCount / 6) % 4]; } else if (l2 == 3 && i2 == 2) { k4 = 0; i5 = 8; j5 = i2 * 3 + walkModel[(2 + mob.stepCount / 6) % 4]; } else if (l2 == 3 && i2 == 3) { k4 = -26; i5 = 5; j5 = i2 * 3 + walkModel[(2 + mob.stepCount / 6) % 4]; } if (i2 != 5 || EntityHandler.getAnimationDef(l3).hasA()) { int k5 = j5 + EntityHandler.getAnimationDef(l3).getNumber(); k4 = (k4 * k) / ((GameImage) (gameGraphics)).sprites[k5] .getSomething1(); i5 = (i5 * l) / ((GameImage) (gameGraphics)).sprites[k5] .getSomething2(); int l5 = (k * ((GameImage) (gameGraphics)).sprites[k5] .getSomething1()) / ((GameImage) (gameGraphics)).sprites[EntityHandler .getAnimationDef(l3).getNumber()] .getSomething1(); k4 -= (l5 - k) / 2; int colour = EntityHandler.getAnimationDef(l3) .getCharColour(); int skinColour = characterSkinColours[mob.colourSkinType]; if (colour == 1) colour = characterHairColours[mob.colourHairType]; else if (colour == 2) colour = characterTopBottomColours[mob.colourTopType]; else if (colour == 3) colour = characterTopBottomColours[mob.colourBottomType]; gameGraphics.spriteClip4(i + k4, j + i5, l5, l, k5, colour, skinColour, j1, flag); } } } if (mob.lastMessageTimeout > 0) { mobMessagesWidth[mobMessageCount] = gameGraphics.textWidth( mob.lastMessage, 1) / 2; if (mobMessagesWidth[mobMessageCount] > 150) mobMessagesWidth[mobMessageCount] = 150; mobMessagesHeight[mobMessageCount] = (gameGraphics.textWidth( mob.lastMessage, 1) / 300) * gameGraphics.messageFontHeight(1); mobMessagesX[mobMessageCount] = i + k / 2; mobMessagesY[mobMessageCount] = j; mobMessages[mobMessageCount++] = mob.lastMessage; } if (mob.anInt163 > 0) { anIntArray858[anInt699] = i + k / 2; anIntArray859[anInt699] = j; anIntArray705[anInt699] = k1; anIntArray706[anInt699++] = mob.anInt162; } if (mob.currentSprite == 8 || mob.currentSprite == 9 || mob.combatTimer != 0) { if (mob.combatTimer > 0) { int i3 = i; if (mob.currentSprite == 8) i3 -= (20 * k1) / 100; else if (mob.currentSprite == 9) i3 += (20 * k1) / 100; int i4 = (mob.hitPointsCurrent * 30) / mob.hitPointsBase; anIntArray786[anInt718] = i3 + k / 2; anIntArray787[anInt718] = j; anIntArray788[anInt718++] = i4; } if (mob.combatTimer > 150) { int j3 = i; if (mob.currentSprite == 8) j3 -= (10 * k1) / 100; else if (mob.currentSprite == 9) j3 += (10 * k1) / 100; gameGraphics.drawPicture((j3 + k / 2) - 12, (j + l / 2) - 12, SPRITE_MEDIA_START + 11); gameGraphics.drawText(String.valueOf(mob.anInt164), (j3 + k / 2) - 1, j + l / 2 + 5, 3, 0xffffff); } } if (mob.anInt179 == 1 && mob.anInt163 == 0) { int k3 = j1 + i + k / 2; if (mob.currentSprite == 8) k3 -= (20 * k1) / 100; else if (mob.currentSprite == 9) k3 += (20 * k1) / 100; int j4 = (16 * k1) / 100; int l4 = (16 * k1) / 100; gameGraphics.spriteClip1(k3 - j4 / 2, j - l4 / 2 - (10 * k1) / 100, j4, l4, SPRITE_MEDIA_START + 13); } } private final void loadConfigFilter() { drawDownloadProgress("Checking local data files", 1, false); EntityHandler.load(); } private final void loadModels() { drawDownloadProgress("Loading 3d models", 75, false); String[] modelNames = { "torcha2", "torcha3", "torcha4", "skulltorcha2", "skulltorcha3", "skulltorcha4", "firea2", "firea3", "fireplacea2", "fireplacea3", "firespell2", "firespell3", "lightning2", "lightning3", "clawspell2", "clawspell3", "clawspell4", "clawspell5", "spellcharge2", "spellcharge3" }; for (String name : modelNames) { EntityHandler.storeModel(name); } byte[] models = load("models36.jag"); if (models == null) { lastLoadedNull = true; return; } for (int j = 0; j < EntityHandler.getModelCount(); j++) { int k = DataOperations.method358(EntityHandler.getModelName(j) + ".ob3", models); if (k == 0) { gameDataModels[j] = new Model(1, 1); } else { gameDataModels[j] = new Model(models, k, true); } gameDataModels[j].isGiantCrystal = EntityHandler.getModelName(j) .equals("giantcrystal"); } } protected final void handleMouseDown(int button, int x, int y) { mouseClickXArray[mouseClickArrayOffset] = x; mouseClickYArray[mouseClickArrayOffset] = y; mouseClickArrayOffset = mouseClickArrayOffset + 1 & 0x1fff; for (int l = 10; l < 4000; l++) { int i1 = mouseClickArrayOffset - l & 0x1fff; if (mouseClickXArray[i1] == x && mouseClickYArray[i1] == y) { boolean flag = false; for (int j1 = 1; j1 < l; j1++) { int k1 = mouseClickArrayOffset - j1 & 0x1fff; int l1 = i1 - j1 & 0x1fff; if (mouseClickXArray[l1] != x || mouseClickYArray[l1] != y) flag = true; if (mouseClickXArray[k1] != mouseClickXArray[l1] || mouseClickYArray[k1] != mouseClickYArray[l1]) break; if (j1 == l - 1 && flag && lastWalkTimeout == 0 && logoutTimeout == 0) { logout(); return; } } } } } protected final void method4() { if (smithingscreen == null) { smithingscreen = SmithingScreen.createScreen(mc); OneonOne.createScreen(mc).isVisible = false; } if (questionmenu == null) { questionmenu = QuestionMenuScreen.createScreen(mc); OneonOne.createScreen(mc).isVisible = false; } if (lastLoadedNull) { Graphics g = getGraphics(); g.setColor(Color.black); g.fillRect(0, 0, gameWidth, gameHeight); g.setFont(new Font("Helvetica", 1, 16)); g.setColor(Color.yellow); int i = 35; g.drawString( "Sorry, an error has occured whilst loading the client", 30, i); i += 50; g.setColor(Color.white); g.drawString("To fix this try the following (in order):", 30, i); i += 50; g.setColor(Color.white); g.setFont(new Font("Helvetica", 1, 12)); g.drawString( "1: Try closing ALL open web-browser windows, and reloading", 30, i); i += 30; g.drawString( "2: Try clearing your web-browsers cache from tools->internet options", 30, i); i += 30; g.drawString("3: Try using a different game-world", 30, i); i += 30; g.drawString("4: Try rebooting your computer", 30, i); i += 30; g.drawString("5: Post on the forums under support", 30, i); changeThreadSleepModifier(1); return; } if (memoryError) { Graphics g2 = getGraphics(); g2.setColor(Color.black); g2.fillRect(0, 0, gameWidth, gameHeight); g2.setFont(new Font("Helvetica", 1, 20)); g2.setColor(Color.white); g2.drawString("Error - out of memory!", 50, 50); g2.drawString("Close ALL unnecessary programs", 50, 100); g2.drawString("and windows before loading the game", 50, 150); g2.drawString( "The client needs about 100mb of spare RAM, 300+mb to Record video", 50, 200); changeThreadSleepModifier(1); return; } try { if (loggedIn == 1) { gameGraphics.drawStringShadows = true; try { drawGame(); } catch (Exception e) { e.printStackTrace(); } } else { gameGraphics.drawStringShadows = false; drawLoginScreen(); } } catch (OutOfMemoryError e) { e.printStackTrace(); garbageCollect(); memoryError = true; } } // drawGame private final void walkToObject(int x, int y, int id, int type) { int i1; int j1; if (id == 0 || id == 4) { i1 = EntityHandler.getObjectDef(type).getWidth(); j1 = EntityHandler.getObjectDef(type).getHeight(); } else { j1 = EntityHandler.getObjectDef(type).getWidth(); i1 = EntityHandler.getObjectDef(type).getHeight(); } if (EntityHandler.getObjectDef(type).getType() == 2 || EntityHandler.getObjectDef(type).getType() == 3) { if (id == 0) { x--; i1++; } if (id == 2) j1++; if (id == 4) i1++; if (id == 6) { y--; j1++; } sendWalkCommand(getSectionX(), getSectionY(), x, y, (x + i1) - 1, (y + j1) - 1, false, true); return; } else { sendWalkCommand(getSectionX(), getSectionY(), x, y, (x + i1) - 1, (y + j1) - 1, true, true); return; } } private final void drawBankBox() { int c = 408; int c1 = 334; if (mouseOverBankPageText > 0 && bankItemCount <= 48) mouseOverBankPageText = 0; if (mouseOverBankPageText > 1 && bankItemCount <= 96) mouseOverBankPageText = 1; if (mouseOverBankPageText > 2 && bankItemCount <= 144) mouseOverBankPageText = 2; if (selectedBankItem >= bankItemCount || selectedBankItem < 0) selectedBankItem = -1; if (selectedBankItem != -1 && bankItems[selectedBankItem] != selectedBankItemType) { selectedBankItem = -1; selectedBankItemType = -2; } if (mouseButtonClick != 0) { mouseButtonClick = 0; int i = super.mouseX - (256 - c / 2) - xAddition; int k = super.mouseY - (170 - c1 / 2) - yAddition; if (i >= 0 && k >= 12 && i < 408 && k < 280) { int i1 = mouseOverBankPageText * 48; for (int l1 = 0; l1 < 6; l1++) { for (int j2 = 0; j2 < 8; j2++) { int l6 = 7 + j2 * 49; int j7 = 28 + l1 * 34; if (i > l6 && i < l6 + 49 && k > j7 && k < j7 + 34 && i1 < bankItemCount && bankItems[i1] != -1) { selectedBankItemType = bankItems[i1]; selectedBankItem = i1; } i1++; } } i = xAddition + 256 - c / 2; k = yAddition + 170 - c1 / 2; int k2; if (selectedBankItem < 0) k2 = -1; else k2 = bankItems[selectedBankItem]; if (k2 != -1) { int j1 = bankItemsCount[selectedBankItem]; // if (!EntityHandler.getItemDef(k2).isStackable() && j1 > // 1) // j1 = 1; if (j1 >= 1 && super.mouseX >= i + 220 && super.mouseY >= k + 238 && super.mouseX < i + 250 && super.mouseY <= k + 249) { super.streamClass.createPacket(183); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(1); super.streamClass.formatPacket(); } if (j1 >= 10 && super.mouseX >= i + 250 && super.mouseY >= k + 238 && super.mouseX < i + 280 && super.mouseY <= k + 249) { super.streamClass.createPacket(183); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(10); super.streamClass.formatPacket(); } if (j1 >= 100 && super.mouseX >= i + 280 && super.mouseY >= k + 238 && super.mouseX < i + 305 && super.mouseY <= k + 249) { super.streamClass.createPacket(183); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(100); super.streamClass.formatPacket(); } if (j1 >= 1000 && super.mouseX >= i + 305 && super.mouseY >= k + 238 && super.mouseX < i + 335 && super.mouseY <= k + 249) { super.streamClass.createPacket(183); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(1000); super.streamClass.formatPacket(); } if (j1 >= 10000 && super.mouseX >= i + 335 && super.mouseY >= k + 238 && super.mouseX < i + 368 && super.mouseY <= k + 249) { super.streamClass.createPacket(183); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(10000); super.streamClass.formatPacket(); } if (super.mouseX >= i + 370 && super.mouseY >= k + 238 && super.mouseX < i + 400 && super.mouseY <= k + 249) { super.streamClass.createPacket(183); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(j1); super.streamClass.formatPacket(); } if (inventoryCount(k2) >= 1 && super.mouseX >= i + 220 && super.mouseY >= k + 263 && super.mouseX < i + 250 && super.mouseY <= k + 274) { super.streamClass.createPacket(198); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(1); super.streamClass.formatPacket(); } if (inventoryCount(k2) >= 10 && super.mouseX >= i + 250 && super.mouseY >= k + 263 && super.mouseX < i + 280 && super.mouseY <= k + 274) { super.streamClass.createPacket(198); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(10); super.streamClass.formatPacket(); } if (inventoryCount(k2) >= 100 && super.mouseX >= i + 280 && super.mouseY >= k + 263 && super.mouseX < i + 305 && super.mouseY <= k + 274) { super.streamClass.createPacket(198); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(100); super.streamClass.formatPacket(); } if (inventoryCount(k2) >= 1000 && super.mouseX >= i + 305 && super.mouseY >= k + 263 && super.mouseX < i + 335 && super.mouseY <= k + 274) { super.streamClass.createPacket(198); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(1000); super.streamClass.formatPacket(); } if (inventoryCount(k2) >= 10000 && super.mouseX >= i + 335 && super.mouseY >= k + 263 && super.mouseX < i + 368 && super.mouseY <= k + 274) { super.streamClass.createPacket(198); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(10000); super.streamClass.formatPacket(); } if (super.mouseX >= i + 370 && super.mouseY >= k + 263 && super.mouseX < i + 400 && super.mouseY <= k + 274) { super.streamClass.createPacket(198); super.streamClass.add2ByteInt(k2); super.streamClass.add4ByteInt(inventoryCount(k2)); super.streamClass.formatPacket(); } } } else if (bankItemCount > 48 && i >= 50 && i <= 115 && k <= 12) mouseOverBankPageText = 0; else if (bankItemCount > 48 && i >= 115 && i <= 180 && k <= 12) mouseOverBankPageText = 1; else if (bankItemCount > 96 && i >= 180 && i <= 245 && k <= 12) mouseOverBankPageText = 2; else if (bankItemCount > 144 && i >= 245 && i <= 310 && k <= 12) { mouseOverBankPageText = 3; } else { super.streamClass.createPacket(48); super.streamClass.formatPacket(); showBank = false; return; } } int j = xAddition + 256 - c / 2; int l = yAddition + 170 - c1 / 2; gameGraphics.drawBox(j, l, 408, 12, 192); int k1 = 0x989898; gameGraphics.drawBoxAlpha(j, l + 12, 408, 17, k1, 160); gameGraphics.drawBoxAlpha(j, l + 29, 8, 204, k1, 160); gameGraphics.drawBoxAlpha(j + 399, l + 29, 9, 204, k1, 160); gameGraphics.drawBoxAlpha(j, l + 233, 408, 47, k1, 160); gameGraphics.drawString("Bank", j + 1, l + 10, 1, 0xffffff); int i2 = 50; if (bankItemCount > 48) { int l2 = 0xffffff; if (mouseOverBankPageText == 0) l2 = 0xff0000; else if (super.mouseX > j + i2 && super.mouseY >= l && super.mouseX < j + i2 + 65 && super.mouseY < l + 12) l2 = 0xffff00; gameGraphics.drawString("<page 1>", j + i2, l + 10, 1, l2); i2 += 65; l2 = 0xffffff; if (mouseOverBankPageText == 1) l2 = 0xff0000; else if (super.mouseX > j + i2 && super.mouseY >= l && super.mouseX < j + i2 + 65 && super.mouseY < l + 12) l2 = 0xffff00; gameGraphics.drawString("<page 2>", j + i2, l + 10, 1, l2); i2 += 65; } if (bankItemCount > 96) { int i3 = 0xffffff; if (mouseOverBankPageText == 2) i3 = 0xff0000; else if (super.mouseX > j + i2 && super.mouseY >= l && super.mouseX < j + i2 + 65 && super.mouseY < l + 12) i3 = 0xffff00; gameGraphics.drawString("<page 3>", j + i2, l + 10, 1, i3); i2 += 65; } if (bankItemCount > 144) { int j3 = 0xffffff; if (mouseOverBankPageText == 3) j3 = 0xff0000; else if (super.mouseX > j + i2 && super.mouseY >= l && super.mouseX < j + i2 + 65 && super.mouseY < l + 12) j3 = 0xffff00; gameGraphics.drawString("<page 4>", j + i2, l + 10, 1, j3); i2 += 65; } int k3 = 0xffffff; if (super.mouseX > j + 320 && super.mouseY >= l && super.mouseX < j + 408 && super.mouseY < l + 12) k3 = 0xff0000; gameGraphics.drawBoxTextRight("Close window", j + 406, l + 10, 1, k3); gameGraphics.drawString("Number in bank in green", j + 7, l + 24, 1, 65280); gameGraphics.drawString("Number held in blue", j + 289, l + 24, 1, 65535); int i7 = 0xd0d0d0; int k7 = mouseOverBankPageText * 48; for (int i8 = 0; i8 < 6; i8++) { for (int j8 = 0; j8 < 8; j8++) { int l8 = j + 7 + j8 * 49; int i9 = l + 28 + i8 * 34; if (selectedBankItem == k7) gameGraphics.drawBoxAlpha(l8, i9, 49, 34, 0xff0000, 160); else gameGraphics.drawBoxAlpha(l8, i9, 49, 34, i7, 160); gameGraphics.drawBoxEdge(l8, i9, 50, 35, 0); if (k7 < bankItemCount && bankItems[k7] != -1) { gameGraphics.spriteClip4(l8, i9, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(bankItems[k7]) .getSprite(), EntityHandler.getItemDef(bankItems[k7]) .getPictureMask(), 0, 0, false); gameGraphics.drawString(String.valueOf(bankItemsCount[k7]), l8 + 1, i9 + 10, 1, 65280); gameGraphics.drawBoxTextRight( String.valueOf(inventoryCount(bankItems[k7])), l8 + 47, i9 + 29, 1, 65535); } k7++; } } gameGraphics.drawLineX(j + 5, l + 256, 398, 0); if (selectedBankItem == -1) { gameGraphics.drawText("Select an object to withdraw or deposit", j + 204, l + 248, 3, 0xffff00); return; } int k8; if (selectedBankItem < 0) k8 = -1; else k8 = bankItems[selectedBankItem]; if (k8 != -1) { int l7 = bankItemsCount[selectedBankItem]; // if (!EntityHandler.getItemDef(k8).isStackable() && l7 > 1) // l7 = 1; if (l7 > 0) { gameGraphics.drawString( "Withdraw " + EntityHandler.getItemDef(k8).getName(), j + 2, l + 248, 1, 0xffffff); int l3 = 0xffffff; if (super.mouseX >= j + 220 && super.mouseY >= l + 238 && super.mouseX < j + 250 && super.mouseY <= l + 249) l3 = 0xff0000; gameGraphics.drawString("One", j + 222, l + 248, 1, l3); if (l7 >= 10) { int i4 = 0xffffff; if (super.mouseX >= j + 250 && super.mouseY >= l + 238 && super.mouseX < j + 280 && super.mouseY <= l + 249) i4 = 0xff0000; gameGraphics.drawString("10", j + 252, l + 248, 1, i4); } if (l7 >= 100) { int j4 = 0xffffff; if (super.mouseX >= j + 280 && super.mouseY >= l + 238 && super.mouseX < j + 305 && super.mouseY <= l + 249) j4 = 0xff0000; gameGraphics.drawString("100", j + 282, l + 248, 1, j4); } if (l7 >= 1000) { int k4 = 0xffffff; if (super.mouseX >= j + 305 && super.mouseY >= l + 238 && super.mouseX < j + 335 && super.mouseY <= l + 249) k4 = 0xff0000; gameGraphics.drawString("1k", j + 307, l + 248, 1, k4); } if (l7 >= 10000) { int l4 = 0xffffff; if (super.mouseX >= j + 335 && super.mouseY >= l + 238 && super.mouseX < j + 368 && super.mouseY <= l + 249) l4 = 0xff0000; gameGraphics.drawString("10k", j + 337, l + 248, 1, l4); } int i5 = 0xffffff; if (super.mouseX >= j + 370 && super.mouseY >= l + 238 && super.mouseX < j + 400 && super.mouseY <= l + 249) i5 = 0xff0000; gameGraphics.drawString("All", j + 370, l + 248, 1, i5); } if (inventoryCount(k8) > 0) { gameGraphics.drawString( "Deposit " + EntityHandler.getItemDef(k8).getName(), j + 2, l + 273, 1, 0xffffff); int j5 = 0xffffff; if (super.mouseX >= j + 220 && super.mouseY >= l + 263 && super.mouseX < j + 250 && super.mouseY <= l + 274) j5 = 0xff0000; gameGraphics.drawString("One", j + 222, l + 273, 1, j5); if (inventoryCount(k8) >= 10) { int k5 = 0xffffff; if (super.mouseX >= j + 250 && super.mouseY >= l + 263 && super.mouseX < j + 280 && super.mouseY <= l + 274) k5 = 0xff0000; gameGraphics.drawString("10", j + 252, l + 273, 1, k5); } if (inventoryCount(k8) >= 100) { int l5 = 0xffffff; if (super.mouseX >= j + 280 && super.mouseY >= l + 263 && super.mouseX < j + 305 && super.mouseY <= l + 274) l5 = 0xff0000; gameGraphics.drawString("100", j + 282, l + 273, 1, l5); } if (inventoryCount(k8) >= 1000) { int i6 = 0xffffff; if (super.mouseX >= j + 305 && super.mouseY >= l + 263 && super.mouseX < j + 335 && super.mouseY <= l + 274) i6 = 0xff0000; gameGraphics.drawString("1k", j + 307, l + 273, 1, i6); } if (inventoryCount(k8) >= 10000) { int j6 = 0xffffff; if (super.mouseX >= j + 335 && super.mouseY >= l + 263 && super.mouseX < j + 368 && super.mouseY <= l + 274) j6 = 0xff0000; gameGraphics.drawString("10k", j + 337, l + 273, 1, j6); } int k6 = 0xffffff; if (super.mouseX >= j + 370 && super.mouseY >= l + 263 && super.mouseX < j + 400 && super.mouseY <= l + 274) k6 = 0xff0000; gameGraphics.drawString("All", j + 370, l + 273, 1, k6); } } } private final void drawLoggingOutBox() { gameGraphics.drawBox(126 + xAddition, 137 + yAddition, 260, 60, 0); gameGraphics.drawBoxEdge(126 + xAddition, 137 + yAddition, 260, 60, 0xffffff); gameGraphics.drawText("Logging out...", 256 + xAddition, 173 + yAddition, 5, 0xffffff); } private final void drawInventoryMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 248; gameGraphics.drawPicture(i, 3, SPRITE_MEDIA_START + 1); for (int j = 0; j < anInt882; j++) { int k = i + (j % 5) * 49; int i1 = 36 + (j / 5) * 34; if (j < inventoryCount && wearing[j] == 1) gameGraphics.drawBoxAlpha(k, i1, 49, 34, 0xff0000, 128); else gameGraphics.drawBoxAlpha(k, i1, 49, 34, GameImage.convertRGBToLong(181, 181, 181), 128); if (j < inventoryCount) { gameGraphics.spriteClip4(k, i1, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(getInventoryItems()[j]) .getSprite(), EntityHandler.getItemDef(getInventoryItems()[j]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(getInventoryItems()[j]) .isStackable()) gameGraphics.drawString( String.valueOf(inventoryItemsCount[j]), k + 1, i1 + 10, 1, 0xffff00); } } for (int l = 1; l <= 4; l++) gameGraphics.drawLineY(i + l * 49, 36, (anInt882 / 5) * 34, 0); for (int j1 = 1; j1 <= anInt882 / 5 - 1; j1++) gameGraphics.drawLineX(i, 36 + j1 * 34, 245, 0); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 248); int k1 = super.mouseY - 36; if (i >= 0 && k1 >= 0 && i < 248 && k1 < (anInt882 / 5) * 34) { int currentInventorySlot = i / 49 + (k1 / 34) * 5; if (currentInventorySlot < inventoryCount) { int i2 = getInventoryItems()[currentInventorySlot]; ItemDef itemDef = EntityHandler.getItemDef(i2); if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell).getSpellType() == 3) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef(selectedSpell) .getName() + " on"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 600; menuActionType[menuLength] = currentInventorySlot; menuActionVariable[menuLength] = selectedSpell; menuLength++; return; } } else {// :: if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 610; menuActionType[menuLength] = currentInventorySlot; menuActionVariable[menuLength] = selectedItem; menuLength++; return; } if (wearing[currentInventorySlot] == 1) { menuText1[menuLength] = "Remove"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 620; menuActionType[menuLength] = currentInventorySlot; menuLength++; } else if (EntityHandler.getItemDef(i2).isWieldable()) { menuText1[menuLength] = "Wear"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 630; menuActionType[menuLength] = currentInventorySlot; menuLength++; } if (!itemDef.getCommand().equals("")) { menuText1[menuLength] = itemDef.getCommand(); menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 640; menuActionType[menuLength] = currentInventorySlot; menuLength++; } menuText1[menuLength] = "Use"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 650; menuActionType[menuLength] = currentInventorySlot; menuLength++; menuText1[menuLength] = "Drop"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 660; menuActionType[menuLength] = currentInventorySlot; menuLength++; menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@lre@" + itemDef.getName() + (ourPlayer.admin >= 1 ? " @or1@(" + i2 + ")" : ""); menuID[menuLength] = 3600; menuActionType[menuLength] = i2; menuLength++; } } } } private final void drawChatMessageTabs() { int x = xAddition; if (windowWidth > 512) { gameGraphics.spriteClip4(512, windowHeight, windowWidth - 512, 10, SPRITE_MEDIA_START + 22, 0, 0, 0, false); gameGraphics.spriteClip4(0, windowHeight, windowWidth - 512, 10, SPRITE_MEDIA_START + 22, 0, 0, 0, false); } gameGraphics.drawPicture(0 + x, windowHeight - 4, SPRITE_MEDIA_START + 23); int i = GameImage.convertRGBToLong(200, 200, 255); if (messagesTab == 0) i = GameImage.convertRGBToLong(255, 200, 50); if (anInt952 % 30 > 15) i = GameImage.convertRGBToLong(255, 50, 50); gameGraphics.drawText("All messages", 54 + x, windowHeight + 6, 0, i); i = GameImage.convertRGBToLong(200, 200, 255); if (messagesTab == 1) i = GameImage.convertRGBToLong(255, 200, 50); if (anInt953 % 30 > 15) i = GameImage.convertRGBToLong(255, 50, 50); gameGraphics.drawText("Chat history", 155 + x, windowHeight + 6, 0, i); i = GameImage.convertRGBToLong(200, 200, 255); if (messagesTab == 2) i = GameImage.convertRGBToLong(255, 200, 50); if (anInt954 % 30 > 15) i = GameImage.convertRGBToLong(255, 50, 50); gameGraphics.drawText("Quest history", 255 + x, windowHeight + 6, 0, i); i = GameImage.convertRGBToLong(200, 200, 255); if (messagesTab == 3) i = GameImage.convertRGBToLong(255, 200, 50); if (anInt955 % 30 > 15) i = GameImage.convertRGBToLong(255, 50, 50); gameGraphics.drawText("Private history", 355 + x, windowHeight + 6, 0, i); gameGraphics.drawText("Report abuse", 457 + x, windowHeight + 6, 0, 0xffffff); } private final void showDPS() { gameGraphics.f1Toggle = false; gameGraphics.method211(); drawPointsScreen.drawMenu(); int i = 140; int j = 50; i += 116; j -= 25; gameGraphics.spriteClip3(i - 32 - 55, j, 64, 102, EntityHandler .getAnimationDef(character2Colour).getNumber(), characterTopBottomColours[characterBottomColour]); gameGraphics.spriteClip4(i - 32 - 55, j, 64, 102, EntityHandler .getAnimationDef(characterBodyGender).getNumber(), characterTopBottomColours[characterTopColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4(i - 32 - 55, j, 64, 102, EntityHandler .getAnimationDef(characterHeadType).getNumber(), characterHairColours[characterHairColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip3(i - 32, j, 64, 102, EntityHandler .getAnimationDef(character2Colour).getNumber() + 6, characterTopBottomColours[characterBottomColour]); gameGraphics.spriteClip4(i - 32, j, 64, 102, EntityHandler .getAnimationDef(characterBodyGender).getNumber() + 6, characterTopBottomColours[characterTopColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4(i - 32, j, 64, 102, EntityHandler .getAnimationDef(characterHeadType).getNumber() + 6, characterHairColours[characterHairColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip3((i - 32) + 55, j, 64, 102, EntityHandler .getAnimationDef(character2Colour).getNumber() + 12, characterTopBottomColours[characterBottomColour]); gameGraphics.spriteClip4((i - 32) + 55, j, 64, 102, EntityHandler .getAnimationDef(characterBodyGender).getNumber() + 12, characterTopBottomColours[characterTopColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4((i - 32) + 55, j, 64, 102, EntityHandler .getAnimationDef(characterHeadType).getNumber() + 12, characterHairColours[characterHairColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4(0, windowHeight, windowWidth, 10, SPRITE_MEDIA_START + 22, 0, 0, 0, false); gameGraphics.drawImage(aGraphics936, 0, 0); } private final void method62() { gameGraphics.f1Toggle = false; gameGraphics.method211(); characterDesignMenu.drawMenu(); int i = 140; int j = 50; i += 116; j -= 25; gameGraphics.spriteClip3(i - 32 - 55, j, 64, 102, EntityHandler .getAnimationDef(character2Colour).getNumber(), characterTopBottomColours[characterBottomColour]); gameGraphics.spriteClip4(i - 32 - 55, j, 64, 102, EntityHandler .getAnimationDef(characterBodyGender).getNumber(), characterTopBottomColours[characterTopColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4(i - 32 - 55, j, 64, 102, EntityHandler .getAnimationDef(characterHeadType).getNumber(), characterHairColours[characterHairColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip3(i - 32, j, 64, 102, EntityHandler .getAnimationDef(character2Colour).getNumber() + 6, characterTopBottomColours[characterBottomColour]); gameGraphics.spriteClip4(i - 32, j, 64, 102, EntityHandler .getAnimationDef(characterBodyGender).getNumber() + 6, characterTopBottomColours[characterTopColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4(i - 32, j, 64, 102, EntityHandler .getAnimationDef(characterHeadType).getNumber() + 6, characterHairColours[characterHairColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip3((i - 32) + 55, j, 64, 102, EntityHandler .getAnimationDef(character2Colour).getNumber() + 12, characterTopBottomColours[characterBottomColour]); gameGraphics.spriteClip4((i - 32) + 55, j, 64, 102, EntityHandler .getAnimationDef(characterBodyGender).getNumber() + 12, characterTopBottomColours[characterTopColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4((i - 32) + 55, j, 64, 102, EntityHandler .getAnimationDef(characterHeadType).getNumber() + 12, characterHairColours[characterHairColour], characterSkinColours[characterSkinColour], 0, false); gameGraphics.spriteClip4(0, windowHeight, windowWidth, 10, SPRITE_MEDIA_START + 22, 0, 0, 0, false); gameGraphics.drawImage(aGraphics936, 0, 0); } private final Mob makePlayer(int mobArrayIndex, int x, int y, int sprite) { if (mobArray[mobArrayIndex] == null) { mobArray[mobArrayIndex] = new Mob(); mobArray[mobArrayIndex].serverIndex = mobArrayIndex; mobArray[mobArrayIndex].mobIntUnknown = 0; } Mob mob = mobArray[mobArrayIndex]; boolean flag = false; for (int i1 = 0; i1 < lastPlayerCount; i1++) { if (lastPlayerArray[i1].serverIndex != mobArrayIndex) continue; flag = true; break; } if (flag) { mob.nextSprite = sprite; int j1 = mob.waypointCurrent; if (x != mob.waypointsX[j1] || y != mob.waypointsY[j1]) { mob.waypointCurrent = j1 = (j1 + 1) % 10; mob.waypointsX[j1] = x; mob.waypointsY[j1] = y; } } else { mob.serverIndex = mobArrayIndex; mob.waypointEndSprite = 0; mob.waypointCurrent = 0; mob.waypointsX[0] = mob.currentX = x; mob.waypointsY[0] = mob.currentY = y; mob.nextSprite = mob.currentSprite = sprite; mob.stepCount = 0; } playerArray[playerCount++] = mob; return mob; } private final void drawWelcomeBox() { int i = 65; if (!lastLoggedInAddress.equals("0.0.0.0")) i += 30; if (subscriptionLeftDays > 0) i += 15; int j = 167 - i / 2 + yAddition; gameGraphics .drawBox(56 + xAddition, 167 - i / 2 + yAddition, 400, i, 0); gameGraphics.drawBoxEdge(56 + xAddition, 167 - i / 2 + yAddition, 400, i, 0xffffff); j += 20; gameGraphics.drawText("Welcome to RuneScape Classic " + currentUser, 256 + xAddition, j, 4, 0xffff00); j += 30; String s; if (lastLoggedInDays == 0) s = "earlier today"; else if (lastLoggedInDays == 1) s = "yesterday"; else s = lastLoggedInDays + " days ago"; if (!lastLoggedInAddress.equals("0.0.0.0")) { gameGraphics.drawText("You last logged in " + s, 256 + xAddition, j, 1, 0xffffff); j += 15; gameGraphics.drawText("from: " + lastLoggedInAddress, 256 + xAddition, j, 1, 0xffffff); j += 15; } if (subscriptionLeftDays > 0) { gameGraphics.drawText("Subscription Left: " + subscriptionLeftDays + " days", 256 + xAddition, j, 1, 0xffffff); j += 15; } int l = 0xffffff; if (super.mouseY > j - 12 && super.mouseY <= j && super.mouseX > 106 + xAddition && super.mouseX < 406 + xAddition) l = 0xff0000; gameGraphics.drawText("Click here to close window", 256 + xAddition, j, 1, l); if (mouseButtonClick == 1) { if (l == 0xff0000) showWelcomeBox = false; if ((super.mouseX < 86 + xAddition || super.mouseX > 426 + xAddition) && (super.mouseY < 167 - i / 2 || super.mouseY > 167 + i / 2)) showWelcomeBox = false; } mouseButtonClick = 0; } private final void logout() { if (loggedIn == 0) { return; } if (lastWalkTimeout > 450) { displayMessage("@cya@You can't logout during combat!", 3, 0); return; } if (lastWalkTimeout > 0) { displayMessage("@cya@You can't logout for 10 seconds after combat", 3, 0); return; } super.streamClass.createPacket(129); super.streamClass.formatPacket(); logoutTimeout = 1000; } private final void drawPlayerInfoMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 3); char c = '\304'; char c1 = '\u0113'; int l; int s; int k = s = l = GameImage.convertRGBToLong(160, 160, 160); if (anInt826 == 0) k = GameImage.convertRGBToLong(220, 220, 220); else if (anInt826 == 1) l = GameImage.convertRGBToLong(220, 220, 220); else if (anInt826 == 2) s = GameImage.convertRGBToLong(220, 220, 220); gameGraphics.drawBoxAlpha(i, j, c / 3, 24, k, 128); gameGraphics.drawBoxAlpha(i + c / 3, j, c / 3, 24, l, 128); gameGraphics.drawBoxAlpha(i + c / 3 + c / 3, j, c / 3, 24, s, 128); gameGraphics.drawBoxAlpha(i, j + 24, c, c1 - 12, GameImage.convertRGBToLong(220, 220, 220), 128); gameGraphics.drawLineX(i, j + 24, c, 0); gameGraphics.drawLineY(i + c / 3, j, 24, 0); gameGraphics.drawLineY(i + c / 3 + c / 3, j, 24, 0); gameGraphics.drawText(" Stats", i + c / 8 + 2, j + 16, 4, 0); gameGraphics.drawText(" Quests", i + c / 8 + c / 3 + 4, j + 16, 4, 0); gameGraphics.drawText(" Info", i + c / 8 + c / 3 + c / 3 + 2, j + 16, 4, 0); if (anInt826 == 0) { int i1 = 72; int k1 = -1; gameGraphics.drawString("Skills", i + 5, i1, 3, 0xffff00); i1 += 13; // gameGraphics.drawString("Fatigue: @yel@" + fatigue + "%", // (i + c / 2) - 5, i1 - 13, 1, 0xffffff); for (int l1 = 0; l1 < 9; l1++) { int i2 = 0xffffff; if (super.mouseX > i + 3 && super.mouseY >= i1 - 11 && super.mouseY < i1 + 2 && super.mouseX < i + 90) { i2 = 0xff0000; k1 = l1; } gameGraphics.drawString(skillArray[l1] + ":@yel@" + playerStatCurrent[l1] + "/" + playerStatBase[l1], i + 5, i1, 1, i2); if (l1 == 8) { gameGraphics.drawString("Fatigue: @yel@" + fatigue + "%", i + 5, i1 + 13, 1, 0xffffff); } i2 = 0xffffff; if (super.mouseX >= i + 90 && super.mouseY >= i1 - 11 - 13 && super.mouseY < i1 + 2 - 13 && super.mouseX < i + 196) { i2 = 0xff0000; k1 = l1 + 9; } gameGraphics.drawString(skillArray[l1 + 9] + ":@yel@" + playerStatCurrent[l1 + 9] + "/" + playerStatBase[l1 + 9], (i + c / 2) - 5, i1 - 13, 1, i2); i1 += 13; // Total xp: if (l1 == 8) { gameGraphics.drawString("Quest Points:@yel@" + questPoints, (i + c / 2) - 5, i1 - 13, 1, 0xffffff); i1 += 13; } } i1 += 8; gameGraphics.drawString("Equipment Status", i + 5, i1, 3, 0xffff00); i1 += 12; for (int j2 = 0; j2 < 3; j2++) { gameGraphics.drawString(equipmentStatusName[j2] + ":@yel@" + equipmentStatus[j2], i + 5, i1, 1, 0xffffff); if (j2 < 2) { gameGraphics.drawString(equipmentStatusName[j2 + 3] + ":@yel@" + equipmentStatus[j2 + 3], i + c / 2 + 25, i1, 1, 0xffffff); } i1 += 13; } i1 += 6; gameGraphics.drawLineX(i, i1 - 15, c, 0); if (k1 != -1) { gameGraphics.drawString(skillArrayLong[k1] + " skill", i + 5, i1, 1, 0xffff00); i1 += 12; int k2 = experienceArray[0]; for (int i3 = 0; i3 < 98; i3++) if (playerStatExperience[k1] >= experienceArray[i3]) k2 = experienceArray[i3 + 1]; gameGraphics.drawString( "Total xp: " + playerStatExperience[k1], i + 5, i1, 1, 0xffffff); i1 += 12; gameGraphics.drawString("Next level at: " + k2, i + 5, i1, 1, 0xffffff); i1 += 12; gameGraphics.drawString("Required xp: " + (k2 - playerStatExperience[k1]), i + 5, i1, 1, 0xffffff); } else { gameGraphics.drawString("Overall levels", i + 5, i1, 1, 0xffff00); i1 += 12; int skillTotal = 0; long expTotal = 0; for (int j3 = 0; j3 < 18; j3++) { skillTotal += playerStatBase[j3]; expTotal += playerStatExperience[j3]; } gameGraphics.drawString("Skill total: " + skillTotal, i + 5, i1, 1, 0xffffff); // i1 += 12; // gameGraphics.drawString("Total xp: " + expTotal, i + 5, i1, // 1, // 0xffffff); // Max hit i1 += 12; float at = playerStatBase[0]; float de = playerStatBase[1]; float st = playerStatBase[2]; float hp = playerStatBase[3]; float ra = playerStatBase[4]; float pr = playerStatBase[5]; float ma = playerStatBase[6]; if (ra * 1.5 > st + at) { double cmb = (de / 4) + (hp / 4) + (pr / 8) + (ma / 8) + (ra / 2.66); // forumla for a ranged based // character gameGraphics.drawString( "Combat level: " + (Math.round(cmb * 100.0) / 100.0), i + 5, i1, 1, 0xffffff); } else { float cmb = (st / 4) + (de / 4) + (hp / 4) + (at / 4) + (pr / 8) + (ma / 8); // formula for a combat based // character gameGraphics.drawString("Combat level: " + cmb, i + 5, i1, 1, 0xffffff); } i1 += 13; /* * double prayerBonus = 1.0; * * if (prayerOn[1]) prayerBonus = 1.05; else if (prayerOn[4]) * prayerBonus = 1.1; else if (prayerOn[10]) prayerBonus = 1.15; * * int modeBonus = 0; * * if (combatStyle == 0) modeBonus = 1; else if (combatStyle == * 1) modeBonus = 3; * * double str = (playerStatCurrent[2] * prayerBonus) + * modeBonus; int maxHit = (int) ((str ((((double) * equipmentStatus[2] * 0.00175D) + 0.1D)) + 1.05D) * 0.95D); * if(maxHit > 31) maxHit = 31; * gameGraphics.drawString("Max hit: " + maxHit, i + 5, i1, 1, * 0xffffff); */ } } if (anInt826 == 1) { int i1 = 72; gameGraphics.drawString("Quest-list (green=completed)", i + 5, i1, 1, 0xffffff); questMenu.resetListTextCount(questMenuHandle); for (int questIdx = 0; questIdx < newQuestNames.length; questIdx++) questMenu .drawMenuListText(questMenuHandle, questIdx, (questStage[questIdx] == 0 ? "@red@" : questStage[questIdx] == 1 ? "@yel@" : "@gre@") + newQuestNames[questIdx]); questMenu.drawMenu(); } else if (anInt826 == 2) { int i1 = 72; // Player Info gameGraphics.drawString("Player Info", i + 5, i1, 3, 0xffff00); i1 += 13; gameGraphics.drawString("Username:@yel@ " + ourPlayer.name, i + 5, i1, 1, 0xffffff); i1 += 13; gameGraphics.drawString("Coords:@yel@ (" + (sectionX + areaX) + ", " + (sectionY + areaY) + ")", i + 5, i1, 1, 0xffffff); i1 += 13; gameGraphics.drawString("Server Index:@yel@ " + ourPlayer.serverIndex, i + 5, i1, 1, 0xffffff); i1 += 13; gameGraphics.drawString( "Exp Gained:@yel@ " + (expGained > 1000 ? (expGained / 1000) + "k" : expGained), i + 5, i1, 1, 0xffffff); if (!lastLoggedInAddress.equals("0.0.0.0")) { i1 += 13; gameGraphics.drawString("Last IP:@yel@ " + lastLoggedInAddress, i + 5, i1, 1, 0xffffff); } i1 += 13; // Client Info double prayerBonus = 1.0; if (prayerOn[1]) prayerBonus = 1.05; else if (prayerOn[4]) prayerBonus = 1.1; else if (prayerOn[10]) prayerBonus = 1.15; int modeBonus = 0; if (combatStyle == 0) modeBonus = 1; else if (combatStyle == 1) modeBonus = 3; double str = (playerStatCurrent[2] * prayerBonus) + modeBonus; int maxHit = (int) ((str * ((((double) equipmentStatus[2] * 0.00175D) + 0.1D)) + 1.05D) * 0.95D); if (maxHit > 31) maxHit = 31; gameGraphics.drawString("Max hit:@yel@ " + maxHit, i + 5, i1, 1, 0xffffff); i1 += 13; long expTotal = 0; for (int j3 = 0; j3 < 18; j3++) { expTotal += playerStatExperience[j3]; } gameGraphics.drawString("Total XP:@yel@ " + expTotal, i + 5, i1, 1, 0xffffff); i1 += 21; gameGraphics.drawString("Client Info", i + 5, i1, 3, 0xffff00); i1 += 13; gameGraphics.drawString("Hostname:@yel@ " + localhost, i + 5, i1, 1, 0xffffff); i1 += 13; gameGraphics.drawString("Uptime:@yel@ " + timeSince(startTime), i + 5, i1, 1, 0xffffff); i1 += 13; gameGraphics.drawString("FPS:@yel@ " + fps, i + 5, i1, 1, 0xffffff); i1 += 21; // Server Info gameGraphics.drawString("Server Info", i + 5, i1, 3, 0xffff00); i1 += 13; gameGraphics.drawString("Hostname:@yel@ " + Config.SERVER_IP, i + 5, i1, 1, 0xffffff); i1 += 13; gameGraphics.drawString("Uptime:@yel@ " + timeSince(serverStartTime), i + 5, i1, 1, 0xffffff); i1 += 13; gameGraphics.drawString("Location:@yel@ " + serverLocation, i + 5, i1, 1, 0xffffff); i1 += 13; } if (!flag) { return; } i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < c && j < c1) { if (anInt826 == 1) questMenu .updateActions( i + (((GameImage) (gameGraphics)).menuDefaultWidth - 199), j + 36, super.lastMouseDownButton, super.mouseDownButton); if (j <= 24 && mouseButtonClick == 1) { if (i < 65) { anInt826 = 0; } else if (i >= 65 && i < 130) { anInt826 = 1; } else if (i >= 130) { anInt826 = 2; } } } } private final void drawWildernessWarningBox() { int i = 97 + yAddition; gameGraphics.drawBox(86 + xAddition, 77 + yAddition, 340, 180, 0); gameGraphics.drawBoxEdge(86 + xAddition, 77 + yAddition, 340, 180, 0xffffff); gameGraphics.drawText("Warning! Proceed with caution", 256 + xAddition, i, 4, 0xff0000); i += 26; gameGraphics.drawText( "If you go much further north you will enter the", 256 + xAddition, i, 1, 0xffffff); i += 13; gameGraphics.drawText("wilderness. This a very dangerous area where", 256 + xAddition, i, 1, 0xffffff); i += 13; gameGraphics.drawText("other players can attack you!", 256 + xAddition, i, 1, 0xffffff); i += 22; gameGraphics.drawText("The further north you go the more dangerous it", 256 + xAddition, i, 1, 0xffffff); i += 13; gameGraphics.drawText("becomes, but the more treasure you will find.", 256 + xAddition, i, 1, 0xffffff); i += 22; gameGraphics.drawText( "In the wilderness an indicator at the bottom-right", 256 + xAddition, i, 1, 0xffffff); i += 13; gameGraphics.drawText( "of the screen will show the current level of danger", 256 + xAddition, i, 1, 0xffffff); i += 22; int j = 0xffffff; if (super.mouseY > i - 12 && super.mouseY <= i && super.mouseX > 181 + xAddition && super.mouseX < 331 + xAddition) j = 0xff0000; gameGraphics.drawText("Click here to close window", 256 + xAddition, i, 1, j); if (mouseButtonClick != 0) { if (super.mouseY > i - 12 && super.mouseY <= i && super.mouseX > 181 + xAddition && super.mouseX < 331 + xAddition) wildernessType = 2; if (super.mouseX < 86 + xAddition || super.mouseX > 426 + xAddition || super.mouseY < 77 + yAddition || super.mouseY > 257 + yAddition) wildernessType = 2; mouseButtonClick = 0; } } final void method68(int i, int j, int k, int l, int i1, int j1, int k1) { int l1 = EntityHandler.getItemDef(i1).getSprite() + SPRITE_ITEM_START; int i2 = EntityHandler.getItemDef(i1).getPictureMask(); gameGraphics.spriteClip4(i, j, k, l, l1, i2, 0, 0, false); } protected final void handleServerMessage(String s) { if (s.startsWith("@bor@")) { displayMessage(s, 4, 0); return; } if (s.startsWith("@que@")) { displayMessage("@whi@" + s, 5, 0); return; } if (s.startsWith("@pri@")) { displayMessage(s, 6, 0); return; } displayMessage(s, 3, 0); } private final void checkMouseOverMenus() { // if(mouseButtonClick == 1) // { // System.out.print("X coord - " + super.mouseX); // System.out.println(" | Y coord - " + super.mouseY); // System.out.println("---------------------------"); // } if (mouseOverMenu == 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 && super.mouseY < 35) mouseOverMenu = 1; if (mouseOverMenu == 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 33 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 33 && super.mouseY < 35) { mouseOverMenu = 2; anInt985 = (int) (Math.random() * 13D) - 6; anInt986 = (int) (Math.random() * 23D) - 11; } if (mouseOverMenu == 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 66 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 66 && super.mouseY < 35) mouseOverMenu = 3; if (mouseOverMenu == 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 99 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 99 && super.mouseY < 35) mouseOverMenu = 4; if (mouseOverMenu == 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 132 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 132 && super.mouseY < 35) mouseOverMenu = 5; if (mouseOverMenu == 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 165 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 165 && super.mouseY < 35) mouseOverMenu = 6; if (mouseOverMenu == 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 198 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 198 && super.mouseY < 35) mouseOverMenu = 7; if (mouseOverMenu != 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 && super.mouseY < 26) mouseOverMenu = 1; if (mouseOverMenu != 0 && mouseOverMenu != 2 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 33 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 33 && super.mouseY < 26) { mouseOverMenu = 2; anInt985 = (int) (Math.random() * 13D) - 6; anInt986 = (int) (Math.random() * 23D) - 11; } if (mouseOverMenu != 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 66 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 66 && super.mouseY < 26) mouseOverMenu = 3; if (mouseOverMenu != 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 99 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 99 && super.mouseY < 26) mouseOverMenu = 4; if (mouseOverMenu != 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 132 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 132 && super.mouseY < 26) mouseOverMenu = 5; if (mouseOverMenu != 0 && super.mouseX >= ((GameImage) (gameGraphics)).menuDefaultWidth - 35 - 165 && super.mouseY >= 3 && super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 165 && super.mouseY < 26) mouseOverMenu = 6; if (mouseOverMenu == 1 && (super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 248 || super.mouseY > 36 + (anInt882 / 5) * 34)) mouseOverMenu = 0; if (mouseOverMenu == 3 && (super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 199 || super.mouseY > 316)) mouseOverMenu = 0; if ((mouseOverMenu == 2 || mouseOverMenu == 4 || mouseOverMenu == 5) && (super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 199 || super.mouseY > 240)) mouseOverMenu = 0; if (mouseOverMenu == 6 && (super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 199 || super.mouseY > 311)) mouseOverMenu = 0; if (mouseOverMenu == 7 && (super.mouseX < ((GameImage) (gameGraphics)).menuDefaultWidth - 232 || super.mouseY > 214)) mouseOverMenu = 0; } private final void menuClick(int index) { int actionX = menuActionX[index]; int actionY = menuActionY[index]; int actionType = menuActionType[index]; int actionVariable = menuActionVariable[index]; int actionVariable2 = menuActionVariable2[index]; int currentMenuID = menuID[index]; if (currentMenuID == 200) { walkToGroundItem(getSectionX(), getSectionY(), actionX, actionY, true); super.streamClass.createPacket(104); super.streamClass.add2ByteInt(actionVariable); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 210) { walkToGroundItem(getSectionX(), getSectionY(), actionX, actionY, true); super.streamClass.createPacket(34); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.add2ByteInt(actionType); super.streamClass.add2ByteInt(actionVariable); super.streamClass.formatPacket(); selectedItem = -1; } if (currentMenuID == 220) { walkToGroundItem(getSectionX(), getSectionY(), actionX, actionY, true); super.streamClass.createPacket(245); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.add2ByteInt(actionType); super.streamClass.add2ByteInt(actionVariable); super.streamClass.formatPacket(); } if (currentMenuID == 3200) displayMessage(EntityHandler.getItemDef(actionType) .getDescription(), 3, 0); if (currentMenuID == 300) { walkToAction(actionX, actionY, actionType); super.streamClass.createPacket(67); super.streamClass.add2ByteInt(actionVariable); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.addByte(actionType); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 310) { walkToAction(actionX, actionY, actionType); super.streamClass.createPacket(36); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.addByte(actionType); super.streamClass.add2ByteInt(actionVariable); super.streamClass.formatPacket(); selectedItem = -1; } if (currentMenuID == 320) { walkToAction(actionX, actionY, actionType); super.streamClass.createPacket(126); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.addByte(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 2300) { walkToAction(actionX, actionY, actionType); super.streamClass.createPacket(235); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.addByte(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 3300) displayMessage(EntityHandler.getDoorDef(actionType) .getDescription(), 3, 0); if (currentMenuID == 400) { walkToObject(actionX, actionY, actionType, actionVariable); super.streamClass.createPacket(17); super.streamClass.add2ByteInt(actionVariable2); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 410) { walkToObject(actionX, actionY, actionType, actionVariable); super.streamClass.createPacket(94); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.add2ByteInt(actionVariable2); super.streamClass.formatPacket(); selectedItem = -1; } if (currentMenuID == 420) { walkToObject(actionX, actionY, actionType, actionVariable); super.streamClass.createPacket(51); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.addTwo4ByteInts(System.currentTimeMillis()); super.streamClass.formatPacket(); } try { throw new Exception(); } catch (Exception e) { String caller = e.getStackTrace()[1].getClassName(); if (!caller.equalsIgnoreCase(this.getClass().getName()) && flagged == 0) { flagged = 1; streamClass.createPacket(165); streamClass.addByte(1); streamClass.formatPacket(); } } if (currentMenuID == 2400) { walkToObject(actionX, actionY, actionType, actionVariable); super.streamClass.createPacket(40); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.addTwo4ByteInts(System.currentTimeMillis()); super.streamClass.formatPacket(); } if (currentMenuID == 3400) displayMessage(EntityHandler.getObjectDef(actionType) .getDescription(), 3, 0); if (currentMenuID == 600) { super.streamClass.createPacket(49); super.streamClass.add2ByteInt(actionVariable); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 610) { super.streamClass.createPacket(27); super.streamClass.add2ByteInt(actionType); super.streamClass.add2ByteInt(actionVariable); super.streamClass.formatPacket(); selectedItem = -1; } if (currentMenuID == 620) { super.streamClass.createPacket(92); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 630) { super.streamClass.createPacket(181); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 640) { super.streamClass.createPacket(89); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 650) { selectedItem = actionType; mouseOverMenu = 0; selectedItemName = EntityHandler.getItemDef( getInventoryItems()[selectedItem]).getName(); } if (currentMenuID == 660) { super.streamClass.createPacket(147); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); selectedItem = -1; mouseOverMenu = 0; displayMessage( "Dropping " + EntityHandler.getItemDef( getInventoryItems()[actionType]).getName(), 4, 0); } if (currentMenuID == 3600) displayMessage(EntityHandler.getItemDef(actionType) .getDescription(), 3, 0); if (currentMenuID == 700) { int l1 = (actionX - 64) / magicLoc; int l3 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), l1, l3, true); super.streamClass.createPacket(71); super.streamClass.add2ByteInt(actionVariable); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 710) { int i2 = (actionX - 64) / magicLoc; int i4 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), i2, i4, true); super.streamClass.createPacket(142); super.streamClass.add2ByteInt(actionType); super.streamClass.add2ByteInt(actionVariable); super.streamClass.formatPacket(); selectedItem = -1; } if (currentMenuID == 720) { int j2 = (actionX - 64) / magicLoc; int j4 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), j2, j4, true); super.streamClass.createPacket(177); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 725) { int k2 = (actionX - 64) / magicLoc; int k4 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), k2, k4, true); super.streamClass.createPacket(74); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 715 || currentMenuID == 2715) { int l2 = (actionX - 64) / magicLoc; int l4 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), l2, l4, true); super.streamClass.createPacket(73);// createPacket(177 super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 3700) displayMessage( EntityHandler.getNpcDef(actionType).getDescription(), 3, 0); if (currentMenuID == 800) { int i3 = (actionX - 64) / magicLoc; int i5 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), i3, i5, true); super.streamClass.createPacket(55); super.streamClass.add2ByteInt(actionVariable); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 810) { int j3 = (actionX - 64) / magicLoc; int j5 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), j3, j5, true); super.streamClass.createPacket(16); super.streamClass.add2ByteInt(actionType); super.streamClass.add2ByteInt(actionVariable); super.streamClass.formatPacket(); selectedItem = -1; } if (currentMenuID == 805 || currentMenuID == 2805) { int k3 = (actionX - 64) / magicLoc; int k5 = (actionY - 64) / magicLoc; method112(getSectionX(), getSectionY(), k3, k5, true); super.streamClass.createPacket(57); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 2806) { super.streamClass.createPacket(222); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 2810) { super.streamClass.createPacket(166); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 2820) { super.streamClass.createPacket(68); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); } if (currentMenuID == 900) { method112(getSectionX(), getSectionY(), actionX, actionY, true); super.streamClass.createPacket(232); super.streamClass.add2ByteInt(actionType); super.streamClass.add2ByteInt(actionX + getAreaX()); super.streamClass.add2ByteInt(actionY + getAreaY()); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 920) { method112(getSectionX(), getSectionY(), actionX, actionY, false); if (actionPictureType == -24) actionPictureType = 24; } if (currentMenuID == 1000) { super.streamClass.createPacket(206); super.streamClass.add2ByteInt(actionType); super.streamClass.formatPacket(); selectedSpell = -1; } if (currentMenuID == 4000) { selectedItem = -1; selectedSpell = -1; } } final void method71(int i, int j, int k, int l, int i1, int j1, int k1) { int l1 = anIntArray782[i1]; int i2 = anIntArray923[i1]; if (l1 == 0) { int j2 = 255 + i2 * 5 * 256; gameGraphics.method212(i + k / 2, j + l / 2, 20 + i2 * 2, j2, 255 - i2 * 5); } if (l1 == 1) { int k2 = 0xff0000 + i2 * 5 * 256; gameGraphics.method212(i + k / 2, j + l / 2, 10 + i2, k2, 255 - i2 * 5); } } protected final void method2() { if (memoryError) return; if (lastLoadedNull) return; try { loginTimer++; if (loggedIn == 0) { super.lastActionTimeout = 0; updateLoginScreen(); } if (loggedIn == 1) { super.lastActionTimeout++; processGame(); } super.lastMouseDownButton = 0; super.keyDown2 = 0; screenRotationTimer++; if (screenRotationTimer > 500) { screenRotationTimer = 0; int i = (int) (Math.random() * 4D); if ((i & 1) == 1) screenRotationX += anInt727; if ((i & 2) == 2) screenRotationY += anInt911; } if (screenRotationX < -50) anInt727 = 2; if (screenRotationX > 50) anInt727 = -2; if (screenRotationY < -50) anInt911 = 2; if (screenRotationY > 50) anInt911 = -2; if (anInt952 > 0) anInt952--; if (anInt953 > 0) anInt953--; if (anInt954 > 0) anInt954--; if (anInt955 > 0) { anInt955--; return; } } catch (OutOfMemoryError _ex) { garbageCollect(); memoryError = true; } } private final Model makeModel(int x, int y, int k, int l, int i1) { int modelX = x; int modelY = y; int modelX1 = x; int modelX2 = y; int j2 = EntityHandler.getDoorDef(l).getModelVar2(); int k2 = EntityHandler.getDoorDef(l).getModelVar3(); int l2 = EntityHandler.getDoorDef(l).getModelVar1(); Model model = new Model(4, 1); if (k == 0) modelX1 = x + 1; if (k == 1) modelX2 = y + 1; if (k == 2) { modelX = x + 1; modelX2 = y + 1; } if (k == 3) { modelX1 = x + 1; modelX2 = y + 1; } modelX *= magicLoc; modelY *= magicLoc; modelX1 *= magicLoc; modelX2 *= magicLoc; int i3 = model.method179(modelX, -engineHandle.getAveragedElevation(modelX, modelY), modelY); int j3 = model .method179( modelX, -engineHandle.getAveragedElevation(modelX, modelY) - l2, modelY); int k3 = model.method179(modelX1, -engineHandle.getAveragedElevation(modelX1, modelX2) - l2, modelX2); int l3 = model.method179(modelX1, -engineHandle.getAveragedElevation(modelX1, modelX2), modelX2); int ai[] = { i3, j3, k3, l3 }; model.method181(4, ai, j2, k2); model.method184(false, 60, 24, -50, -10, -50); if (x >= 0 && y >= 0 && x < 96 && y < 96) gameCamera.addModel(model); model.anInt257 = i1 + 10000; return model; } private final void resetLoginVars() { loggedIn = 0; loginScreenNumber = 0; currentUser = ""; currentPass = ""; playerCount = 0; npcCount = 0; for (int i = 0; i < newQuestNames.length; i++) questStage[i] = 0; questPoints = 0; } private static final String method74(int i) { String s = String.valueOf(i); for (int j = s.length() - 3; j > 0; j -= 3) s = s.substring(0, j) + "," + s.substring(j); if (s.length() > 8) s = "@gre@" + s.substring(0, s.length() - 8) + " million @whi@(" + s + ")"; else if (s.length() > 4) s = "@cya@" + s.substring(0, s.length() - 4) + "K @whi@(" + s + ")"; return s; } public BufferedImage fixSleeping(Image sleepCaptcha) { BufferedImage image = new BufferedImage(windowWidth, windowHeight + 11, BufferedImage.TYPE_INT_RGB); Graphics2D gfx = image.createGraphics(); gfx.setColor(Color.BLUE); gfx.drawString(gameMenu.getText(chatHandle) + "*", windowWidth / 2, windowHeight / 2 - 40); gfx.setColor(Color.white); gfx.drawString((sleepMessage == null ? "Enter the words below: " : sleepMessage), windowWidth / 2 - 50, windowHeight / 2 - 60); gfx.drawImage(sleepCaptcha, windowWidth / 2 - 107, windowHeight / 2, null); gfx.drawRect(windowWidth / 2 - 108, windowHeight / 2 - 1, 258, 42); return image; } private Image sleepEquation = null; public boolean sleeping = false; public boolean loading; @SuppressWarnings("static-access") private final void drawGame() throws Exception { cur_fps++; if (System.currentTimeMillis() - lastFps < 0) { lastFps = System.currentTimeMillis(); } if (System.currentTimeMillis() - lastFps >= 1000) { fps = cur_fps; cur_fps = 0; lastFps = System.currentTimeMillis(); } // sleepTime = (int) ((long) threadSleepModifier - (l1 - // currentTimeArray[i]) / 10L); /* * long now = System.currentTimeMillis(); if (now - lastFrame > (1000 / * Config.MOVIE_FPS) && recording) { try { lastFrame = now; * frames.add(getImage()); } catch (Exception e) { e.printStackTrace(); * } } */ if (playerAliveTimeout != 0) { gameGraphics.fadePixels(); gameGraphics.drawText("Oh dear! You are dead...", windowWidth / 2, windowHeight / 2, 7, 0xff0000); drawChatMessageTabs(); drawOurSpritesOnScreen(); gameGraphics.drawImage(aGraphics936, 0, 0); return; } if (sleeping) { boolean drawEquation = true; // gameGraphics.fadePixels(); // if(Math.random() < 0.14999999999999999D) // gameGraphics.drawText("ZZZ", (int)(Math.random() * 80D), // (int)(Math.random() * (double)windowHeight), 5, // (int)(Math.random() * 16777215D)); // if(Math.random() < 0.14999999999999999D) // gameGraphics.drawText("ZZZ", windowWidth - (int)(Math.random() * // 80D), (int)(Math.random() * (double)windowHeight), 5, // (int)(Math.random() * 16777215D)); // gameGraphics.drawBox(windowWidth / 2 - 100, 160, 200, 40, 0); // gameGraphics.drawText("You are sleeping", windowWidth / 2, 50, 7, // 0xffff00); // gameGraphics.drawText("Fatigue: " + (tfatigue * 100) / 750 + "%", // windowWidth / 2, 90, 7, 0xffff00); // gameGraphics.drawText("When you want to wake up just use your", // windowWidth / 2, 140, 5, 0xffffff); // gameGraphics.drawText("keyboard to type the solution in the box below", // windowWidth / 2, 160, 5, 0xffffff); // gameGraphics.drawText(super.inputText + "*", windowWidth / 2, // 180, 5, 65535); // if(sleepMessage != null) { // gameGraphics.drawText(sleepMessage, windowWidth / 2, 260, 5, // 0xff0000); // drawEquation = false; // } // gameGraphics.drawBoxEdge(windowWidth / 2 - 128, 229, 257, 42, // 0xffffff); // drawChatMessageTabs(); // gameGraphics.drawText("If you can't read the equation", // windowWidth / 2, 290, 1, 0xffffff); // gameGraphics.drawText("@yel@click here@whi@ to get a different one", // windowWidth / 2, 305, 1, 0xffffff); // gameGraphics.drawImage(aGraphics936, 0, 0); if (drawEquation && sleepEquation != null) { gameGraphics.drawImage(aGraphics936, 0, 0, fixSleeping(sleepEquation)); // gameGraphics.drawImage(aGraphics936, windowWidth / 2 - 127, // 230, fixSleeping(sleepEquation)); } return; } if (showDrawPointsScreen) { showDPS(); return; } if (showCharacterLookScreen) { method62(); return; }// fog if (!engineHandle.playerIsAlive) { return; } for (int i = 0; i < 64; i++) { gameCamera .removeModel(engineHandle.aModelArrayArray598[lastWildYSubtract][i]); if (lastWildYSubtract == 0) { gameCamera.removeModel(engineHandle.aModelArrayArray580[1][i]); gameCamera.removeModel(engineHandle.aModelArrayArray598[1][i]); gameCamera.removeModel(engineHandle.aModelArrayArray580[2][i]); gameCamera.removeModel(engineHandle.aModelArrayArray598[2][i]); } zoomCamera = true; if (lastWildYSubtract == 0 && (engineHandle.walkableValue[ourPlayer.currentX / 128][ourPlayer.currentY / 128] & 0x80) == 0) { if (showRoof) { gameCamera .addModel(engineHandle.aModelArrayArray598[lastWildYSubtract][i]); if (lastWildYSubtract == 0) { gameCamera .addModel(engineHandle.aModelArrayArray580[1][i]); gameCamera .addModel(engineHandle.aModelArrayArray598[1][i]); gameCamera .addModel(engineHandle.aModelArrayArray580[2][i]); gameCamera .addModel(engineHandle.aModelArrayArray598[2][i]); } } zoomCamera = false; } } if (modelFireLightningSpellNumber != anInt742) { anInt742 = modelFireLightningSpellNumber; for (int j = 0; j < objectCount; j++) { if (objectType[j] == 97) method98(j, "firea" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 274) method98(j, "fireplacea" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1031) method98(j, "lightning" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1036) method98(j, "firespell" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1147) method98(j, "spellcharge" + (modelFireLightningSpellNumber + 1)); } } if (modelTorchNumber != anInt743) { anInt743 = modelTorchNumber; for (int k = 0; k < objectCount; k++) { if (objectType[k] == 51) method98(k, "torcha" + (modelTorchNumber + 1)); if (objectType[k] == 143) method98(k, "skulltorcha" + (modelTorchNumber + 1)); } } if (modelClawSpellNumber != anInt744) { anInt744 = modelClawSpellNumber; for (int l = 0; l < objectCount; l++) if (objectType[l] == 1142) method98(l, "clawspell" + (modelClawSpellNumber + 1)); } gameCamera.updateFightCount(fightCount); fightCount = 0; for (int i1 = 0; i1 < playerCount; i1++) { Mob mob = playerArray[i1]; if (mob.colourBottomType != 255) { int k1 = mob.currentX; int i2 = mob.currentY; int k2 = -engineHandle.getAveragedElevation(k1, i2); int l3 = gameCamera.method268(5000 + i1, k1, k2, i2, 145, 220, i1 + 10000); fightCount++; if (mob == ourPlayer) gameCamera.setOurPlayer(l3); if (mob.currentSprite == 8) gameCamera.setCombat(l3, -30); if (mob.currentSprite == 9) gameCamera.setCombat(l3, 30); } } for (int j1 = 0; j1 < playerCount; j1++) { Mob player = playerArray[j1]; if (player.anInt176 > 0) { Mob npc = null; if (player.attackingNpcIndex != -1) npc = npcRecordArray[player.attackingNpcIndex]; else if (player.attackingMobIndex != -1) npc = mobArray[player.attackingMobIndex]; if (npc != null) { int px = player.currentX; int py = player.currentY; int pi = -engineHandle.getAveragedElevation(px, py) - 110; int nx = npc.currentX; int ny = npc.currentY; int ni = -engineHandle.getAveragedElevation(nx, ny) - EntityHandler.getNpcDef(npc.type).getCamera2() / 2; int i10 = (px * player.anInt176 + nx * (attackingInt40 - player.anInt176)) / attackingInt40; int j10 = (pi * player.anInt176 + ni * (attackingInt40 - player.anInt176)) / attackingInt40; int k10 = (py * player.anInt176 + ny * (attackingInt40 - player.anInt176)) / attackingInt40; gameCamera.method268(SPRITE_PROJECTILE_START + player.attackingCameraInt, i10, j10, k10, 32, 32, 0); fightCount++; } } } for (int l1 = 0; l1 < npcCount; l1++) { Mob npc = npcArray[l1]; int mobx = npc.currentX; int moby = npc.currentY; int i7 = -engineHandle.getAveragedElevation(mobx, moby); int i9 = gameCamera.method268(20000 + l1, mobx, i7, moby, EntityHandler.getNpcDef(npc.type).getCamera1(), EntityHandler.getNpcDef(npc.type).getCamera2(), l1 + 30000); fightCount++; if (npc.currentSprite == 8) gameCamera.setCombat(i9, -30); if (npc.currentSprite == 9) gameCamera.setCombat(i9, 30); } if (LOOT_ENABLED) { for (int j2 = 0; j2 < groundItemCount; j2++) { int j3 = groundItemX[j2] * magicLoc + 64; int k4 = groundItemY[j2] * magicLoc + 64; gameCamera.method268(40000 + groundItemType[j2], j3, -engineHandle.getAveragedElevation(j3, k4) - groundItemObjectVar[j2], k4, 96, 64, j2 + 20000); fightCount++; } }// if (systemUpdate != 0) { for (int k3 = 0; k3 < anInt892; k3++) { int l4 = anIntArray944[k3] * magicLoc + 64; int j7 = anIntArray757[k3] * magicLoc + 64; int j9 = anIntArray782[k3]; if (j9 == 0) { gameCamera.method268(50000 + k3, l4, -engineHandle.getAveragedElevation(l4, j7), j7, 128, 256, k3 + 50000); fightCount++; } if (j9 == 1) { gameCamera.method268(50000 + k3, l4, -engineHandle.getAveragedElevation(l4, j7), j7, 128, 64, k3 + 50000); fightCount++; } } gameGraphics.f1Toggle = false; gameGraphics.method211(); gameGraphics.f1Toggle = super.keyF1Toggle; if (lastWildYSubtract == 3) { int i5 = 40 + (int) (Math.random() * 3D); int k7 = 40 + (int) (Math.random() * 7D); gameCamera.method304(i5, k7, -50, -10, -50); } anInt699 = 0; mobMessageCount = 0; anInt718 = 0; if (cameraAutoAngleDebug) { if (configAutoCameraAngle && !zoomCamera) { int lastCameraAutoAngle = cameraAutoAngle; autoRotateCamera(); if (cameraAutoAngle != lastCameraAutoAngle) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } } if (fog) { gameCamera.zoom1 = 3000 + fogVar; gameCamera.zoom2 = 3000 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2800 + fogVar; } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } cameraRotation = cameraAutoAngle * 32; int k5 = lastAutoCameraRotatePlayerX + screenRotationX; int l7 = lastAutoCameraRotatePlayerY + screenRotationY; gameCamera.setCamera(k5, -engineHandle.getAveragedElevation(k5, l7), l7, cameraVertical, cameraRotation * 4, 0, 2000); } else { if (configAutoCameraAngle && !zoomCamera) autoRotateCamera(); if (fog) { if (!super.keyF1Toggle) { gameCamera.zoom1 = 2400 + fogVar; gameCamera.zoom2 = 2400 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2300 + fogVar; } else { gameCamera.zoom1 = 2200; gameCamera.zoom2 = 2200; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2100; } } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } int l5 = lastAutoCameraRotatePlayerX + screenRotationX; int i8 = lastAutoCameraRotatePlayerY + screenRotationY; gameCamera.setCamera(l5, -engineHandle.getAveragedElevation(l5, i8), i8, cameraVertical, cameraRotation * 4, 0, cameraHeight * 2); } gameCamera.finishCamera(); /* * e.printStackTrace(); System.out.println("Camera error: " + e); * cameraHeight = 750; cameraVertical = 920; fogVar = 0; */ method119(); if (actionPictureType > 0) gameGraphics.drawPicture(actionPictureX - 8, actionPictureY - 8, SPRITE_MEDIA_START + 14 + (24 - actionPictureType) / 6); if (actionPictureType < 0) gameGraphics.drawPicture(actionPictureX - 8, actionPictureY - 8, SPRITE_MEDIA_START + 18 + (24 + actionPictureType) / 6); try { MessageQueue.getQueue().checkProcessMessages(); int height = 55; if (MessageQueue.getQueue().hasMessages()) { for (Message m : MessageQueue.getQueue().getList()) { if (m.isBIG) continue; gameGraphics.drawString(m.message, 8, height, 1, 0xffff00); height += 12; } for (Message m : MessageQueue.getQueue().getList()) { if (m.isBIG) { gameGraphics.drawString(m.message, 120, 100, 7, 0xffff00); } } } } catch (Exception e) { e.printStackTrace(); } if (systemUpdate != 0) { int i6 = systemUpdate / 50; int j8 = i6 / 60; i6 %= 60; if (i6 < 10)// redflag gameGraphics.drawText("System update in: " + j8 + ":0" + i6, 256 + xAddition, windowHeight - 7, 1, 0xffff00); else gameGraphics.drawText("System update in: " + j8 + ":" + i6, 256 + xAddition, windowHeight - 7, 1, 0xffff00); } // #pmd# if (!notInWilderness) { int j6 = 2203 - (getSectionY() + wildY + getAreaY()); if (getSectionX() + wildX + getAreaX() >= 2640) j6 = -50; if (j6 > 0) { int k8 = 1 + j6 / 6; gameGraphics.drawPicture(windowWidth - 50, windowHeight - 56, SPRITE_MEDIA_START + 13); int minx = 12; int maxx = 91; int miny = 4; int maxy = 33; // command == 1 int ourX = (getSectionX() + getAreaX()); int ourY = (getSectionY() + getAreaY()); if (ourX > minx && ourX < maxx && ourY > miny && ourY < maxy) { gameGraphics.drawText("@whi@CTF", windowWidth - 40, windowHeight - 20, 1, 0xffff00); gameGraphics.drawText("@red@Red: @whi@" + GameWindowMiddleMan.redPoints + " @blu@Blue: @whi@" + GameWindowMiddleMan.bluePoints, windowWidth - 40, windowHeight - 7, 1, 0xffff00); } else { // Coords: gameGraphics.drawText("Wilderness", windowWidth - 40, windowHeight - 20, 1, 0xffff00); gameGraphics.drawText("Level: " + k8, windowWidth - 40, windowHeight - 7, 1, 0xffff00); } if (wildernessType == 0) wildernessType = 2; } if (wildernessType == 0 && j6 > -10 && j6 <= 0) wildernessType = 1; } if (messagesTab == 0) { for (int k6 = 0; k6 < messagesArray.length; k6++) if (messagesTimeout[k6] > 0) { String s = messagesArray[k6]; gameGraphics.drawString(s, 7, windowHeight - 18 - k6 * 12, 1, 0xffff00); } } gameMenu.method171(messagesHandleType2); gameMenu.method171(messagesHandleType5); gameMenu.method171(messagesHandleType6); if (messagesTab == 1) gameMenu.method170(messagesHandleType2); else if (messagesTab == 2) gameMenu.method170(messagesHandleType5); else if (messagesTab == 3) gameMenu.method170(messagesHandleType6); Menu.anInt225 = 2; gameMenu.drawMenu(); Menu.anInt225 = 0; gameGraphics.method232( ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 197, 3, SPRITE_MEDIA_START, 128); drawGameWindowsMenus(); gameGraphics.drawStringShadows = false; drawChatMessageTabs(); drawOurSpritesOnScreen(); InterfaceHandler.tick(); gameGraphics.drawImage(aGraphics936, 0, 0); } /** * Draws our sprites on screen when needed */ private void drawOurSpritesOnScreen() { if (mouseOverMenu != 7) gameGraphics.drawBoxAlpha( ((GameImage) (gameGraphics)).menuDefaultWidth - 232, 3, 31, 32, GameImage.convertRGBToLong(181, 181, 181), 128); gameGraphics.drawPicture(windowWidth - 240, 2, SPRITE_ITEM_START + EntityHandler.getItemDef(167).getSprite()); } private final void drawRightClickMenu() { if (mouseButtonClick != 0) { for (int i = 0; i < menuLength; i++) { int k = menuX + 2; int i1 = menuY + 27 + i * 15; if (super.mouseX <= k - 2 || super.mouseY <= i1 - 12 || super.mouseY >= i1 + 4 || super.mouseX >= (k - 3) + menuWidth) continue; menuClick(menuIndexes[i]); break; } mouseButtonClick = 0; showRightClickMenu = false; return; } if (super.mouseX < menuX - 10 || super.mouseY < menuY - 10 || super.mouseX > menuX + menuWidth + 10 || super.mouseY > menuY + menuHeight + 10) { showRightClickMenu = false; return; } gameGraphics.drawBoxAlpha(menuX, menuY, menuWidth, menuHeight, 0xd0d0d0, 160); gameGraphics.drawString("Choose option", menuX + 2, menuY + 12, 1, 65535); for (int j = 0; j < menuLength; j++) { int l = menuX + 2; int j1 = menuY + 27 + j * 15; int k1 = 0xffffff; if (super.mouseX > l - 2 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && super.mouseX < (l - 3) + menuWidth) k1 = 0xffff00; gameGraphics.drawString(menuText1[menuIndexes[j]] + " " + menuText2[menuIndexes[j]], l, j1, 1, k1); } } protected final void resetIntVars() { systemUpdate = 0; loginScreenNumber = 0; loggedIn = 0; logoutTimeout = 0; for (int i = 0; i < questStage.length; i++) questStage[i] = 0; questPoints = 0; } private final void drawQuestionMenu() { if (mouseButtonClick != 0) { for (int i = 0; i < questionMenuCount; i++) { if (super.mouseX >= gameGraphics.textWidth( questionMenuAnswer[i], 1) || super.mouseY <= i * 12 || super.mouseY >= 12 + i * 12) continue; super.streamClass.createPacket(154); super.streamClass.addByte(i); super.streamClass.formatPacket(); break; } mouseButtonClick = 0; showQuestionMenu = false; return; } for (int j = 0; j < questionMenuCount; j++) { int k = 65535; if (super.mouseX < gameGraphics.textWidth(questionMenuAnswer[j], 1) && super.mouseY > j * 12 && super.mouseY < 12 + j * 12) k = 0xff0000; gameGraphics .drawString(questionMenuAnswer[j], 6, 12 + j * 12, 1, k); // KO9 breaking! // questionmenu.Questions[j] = questionMenuAnswer[j]; } // questionmenu.isVisible = true; } private final void walkToAction(int actionX, int actionY, int actionType) { if (actionType == 0) { sendWalkCommand(getSectionX(), getSectionY(), actionX, actionY - 1, actionX, actionY, false, true); return; } if (actionType == 1) { sendWalkCommand(getSectionX(), getSectionY(), actionX - 1, actionY, actionX, actionY, false, true); return; } else { sendWalkCommand(getSectionX(), getSectionY(), actionX, actionY, actionX, actionY, true, true); return; } } private final void garbageCollect() { try { if (gameGraphics != null) { gameGraphics.cleanupSprites(); gameGraphics.imagePixelArray = null; gameGraphics = null; } if (gameCamera != null) { gameCamera.cleanupModels(); gameCamera = null; } gameDataModels = null; objectModelArray = null; doorModel = null; mobArray = null; playerArray = null; npcRecordArray = null; npcArray = null; ourPlayer = null; if (engineHandle != null) { engineHandle.aModelArray596 = null; engineHandle.aModelArrayArray580 = null; engineHandle.aModelArrayArray598 = null; engineHandle.aModel = null; engineHandle = null; } System.gc(); return; } catch (Exception _ex) { return; } } protected final void loginScreenPrint(String s, String s1) { if (loginScreenNumber == 1) menuNewUser.updateText(anInt900, s + " " + s1); if (loginScreenNumber == 2) menuLogin.updateText(loginStatusText, s + " " + s1); drawLoginScreen(); resetCurrentTimeArray(); } private final void drawInventoryRightClickMenu() { int i = 2203 - (getSectionY() + wildY + getAreaY()); if (getSectionX() + wildX + getAreaX() >= 2640) i = -50; int j = -1; for (int k = 0; k < objectCount; k++) aBooleanArray827[k] = false; for (int l = 0; l < doorCount; l++) aBooleanArray970[l] = false; int i1 = gameCamera.method272(); Model models[] = gameCamera.getVisibleModels(); int ai[] = gameCamera.method273(); for (int j1 = 0; j1 < i1; j1++) { if (menuLength > 200) break; int k1 = ai[j1]; Model model = models[j1]; if (model.anIntArray258[k1] <= 65535 || model.anIntArray258[k1] >= 0x30d40 && model.anIntArray258[k1] <= 0x493e0) if (model == gameCamera.aModel_423) { int i2 = model.anIntArray258[k1] % 10000; int l2 = model.anIntArray258[k1] / 10000; if (l2 == 1) { String s = ""; int k3 = 0; if (ourPlayer.level > 0 && playerArray[i2].level > 0) k3 = ourPlayer.level - playerArray[i2].level; if (k3 < 0) s = "@or1@"; if (k3 < -3) s = "@or2@"; if (k3 < -6) s = "@or3@"; if (k3 < -9) s = "@red@"; if (k3 > 0) s = "@gr1@"; if (k3 > 3) s = "@gr2@"; if (k3 > 6) s = "@gr3@"; if (k3 > 9) s = "@gre@"; s = " " + s + "(level-" + playerArray[i2].level + ")"; if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 1 || EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 2) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 800; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 810; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { // Max hit if (i > 0 && (playerArray[i2].currentY - 64) / magicLoc + wildY + getAreaY() < 2203) { menuText1[menuLength] = "Attack"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; if (k3 >= 0 && k3 < 5) menuID[menuLength] = 805; else menuID[menuLength] = 2805; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } else { menuText1[menuLength] = "Duel with"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + "@whi@" + playerArray[i2].name + s; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuID[menuLength] = 2806; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Trade with"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 2810; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; menuText1[menuLength] = "Follow"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 2820; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } } else if (l2 == 2) { ItemDef itemDef = EntityHandler .getItemDef(groundItemType[i2]); if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 3) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 200; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 210; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { menuText1[menuLength] = "Take"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 220; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuLength++; menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@lre@" + itemDef.getName() + (ourPlayer.admin >= 1 ? " @or1@(" + groundItemType[i2] + ":" + (groundItemX[i2] + getAreaX()) + "," + (groundItemY[i2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3200; menuActionType[menuLength] = groundItemType[i2]; menuLength++; } } else if (l2 == 3) { String s1 = ""; int l3 = -1; NPCDef npcDef = EntityHandler .getNpcDef(npcArray[i2].type); if (npcDef.isAttackable()) { int j4 = (npcDef.getAtt() + npcDef.getDef() + npcDef.getStr() + npcDef.getHits()) / 4; int k4 = (playerStatBase[0] + playerStatBase[1] + playerStatBase[2] + playerStatBase[3] + 27) / 4; l3 = k4 - j4; s1 = "@yel@"; if (l3 < 0) s1 = "@or1@"; if (l3 < -3) s1 = "@or2@"; if (l3 < -6) s1 = "@or3@"; if (l3 < -9) s1 = "@red@"; if (l3 > 0) s1 = "@gr1@"; if (l3 > 3) s1 = "@gr2@"; if (l3 > 6) s1 = "@gr3@"; if (l3 > 9) s1 = "@gre@"; s1 = " " + s1 + "(level-" + j4 + ")"; } if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 2) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 700; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 710; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { if (npcDef.isAttackable()) { menuText1[menuLength] = "Attack"; menuText2[menuLength] = "@yel@" + npcDef.getName() + s1; if (l3 >= 0) menuID[menuLength] = 715; else menuID[menuLength] = 2715; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Talk-to"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 720; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; if (!npcDef.getCommand().equals("")) { menuText1[menuLength] = npcDef.getCommand(); menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 725; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@yel@" + npcDef.getName() + (ourPlayer.admin >= 1 ? " @or1@(" + npcArray[i2].type + ")" : ""); menuID[menuLength] = 3700; menuActionType[menuLength] = npcArray[i2].type; menuLength++; } }// "Skills } else if (model != null && model.anInt257 >= 10000) { int j2 = model.anInt257 - 10000; int i3 = doorType[j2]; if (!aBooleanArray970[j2]) { if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 4) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 300; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3).getName(); menuID[menuLength] = 310; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { if (!EntityHandler.getDoorDef(i3).getCommand1() .equalsIgnoreCase("WalkTo")) { menuText1[menuLength] = EntityHandler .getDoorDef(i3).getCommand1(); menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 320; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuLength++; } if (!EntityHandler.getDoorDef(i3).getCommand2() .equalsIgnoreCase("Examine")) { menuText1[menuLength] = EntityHandler .getDoorDef(i3).getCommand2(); menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 2300; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3).getName() + (ourPlayer.admin >= 1 ? " @or1@(" + i3 + ":" + (doorX[j2] + getAreaX()) + "," + (doorY[j2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3300; menuActionType[menuLength] = i3; menuLength++; } aBooleanArray970[j2] = true; } } else if (model != null && model.anInt257 >= 0) { int k2 = model.anInt257; int j3 = objectType[k2]; if (!aBooleanArray827[k2]) { if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 5) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 400; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuActionVariable2[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3).getName(); menuID[menuLength] = 410; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuActionVariable2[menuLength] = selectedItem; menuLength++; } else { if (!EntityHandler.getObjectDef(j3).getCommand1() .equalsIgnoreCase("WalkTo")) { menuText1[menuLength] = EntityHandler .getObjectDef(j3).getCommand1(); menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 420; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuLength++; } if (!EntityHandler.getObjectDef(j3).getCommand2() .equalsIgnoreCase("Examine")) { menuText1[menuLength] = EntityHandler .getObjectDef(j3).getCommand2(); menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 2400; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3).getName() + (ourPlayer.admin >= 1 ? " @or1@(" + j3 + ":" + (objectX[k2] + getAreaX()) + "," + (objectY[k2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3400; menuActionType[menuLength] = j3; menuLength++; } aBooleanArray827[k2] = true; } } else { if (k1 >= 0) k1 = model.anIntArray258[k1] - 0x30d40; if (k1 >= 0) j = k1; } } if (selectedSpell >= 0 && EntityHandler.getSpellDef(selectedSpell).getSpellType() <= 1) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef(selectedSpell).getName() + " on self"; menuText2[menuLength] = ""; menuID[menuLength] = 1000; menuActionType[menuLength] = selectedSpell; menuLength++; } if (j != -1) { int l1 = j; if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell).getSpellType() == 6) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef(selectedSpell) .getName() + " on ground"; menuText2[menuLength] = ""; menuID[menuLength] = 900; menuActionX[menuLength] = engineHandle.selectedX[l1]; menuActionY[menuLength] = engineHandle.selectedY[l1]; menuActionType[menuLength] = selectedSpell; menuLength++; return; } } else if (selectedItem < 0) { menuText1[menuLength] = "Walk here"; menuText2[menuLength] = ""; menuID[menuLength] = 920; menuActionX[menuLength] = engineHandle.selectedX[l1]; menuActionY[menuLength] = engineHandle.selectedY[l1]; menuLength++; } } } protected final void startGame() { int i = 0; for (int j = 0; j < 99; j++) { int k = j + 1; int i1 = (int) ((double) k + 300D * Math.pow(2D, (double) k / 7D)); i += i1; experienceArray[j] = (i & 0xffffffc) / 4; } super.yOffset = 0; GameWindowMiddleMan.maxPacketReadCount = 500; if (appletMode) { CacheManager.load("Loading.rscd"); setLogo(Toolkit.getDefaultToolkit().getImage( Config.CONF_DIR + File.separator + "Loading.rscd")); } loadConfigFilter(); // 15% if (lastLoadedNull) { return; } aGraphics936 = getGraphics(); changeThreadSleepModifier(50); gameGraphics = new GameImageMiddleMan(windowWidth, windowHeight + 12, 4000, this); gameGraphics._mudclient = this; GameFrame.setClient(mc); GameWindow.setClient(this); gameGraphics.setDimensions(0, 0, windowWidth, windowHeight + 12); Menu.aBoolean220 = false; /* Menu.anInt221 = anInt902; */ spellMenu = new Menu(gameGraphics, 5); int l = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; spellMenuHandle = spellMenu.method162(l, byte0 + 24, 196, 90, 1, 500, true); friendsMenu = new Menu(gameGraphics, 5); friendsMenuHandle = friendsMenu.method162(l, byte0 + 40, 196, 126, 1, 500, true); questMenu = new Menu(gameGraphics, 5); questMenuHandle = questMenu.method162(l, byte0 + 40, 196, 235, 1, 500, true); loadMedia(); // 30% if (lastLoadedNull) return; loadEntity(); // 45% if (lastLoadedNull) return; gameCamera = new Camera(gameGraphics, 15000, 15000, 1000); gameCamera.setCameraSize(windowWidth / 2, windowHeight / 2, windowWidth / 2, windowHeight / 2, windowWidth, cameraSizeInt); if (fog) { gameCamera.zoom1 = 2400 + fogVar; gameCamera.zoom2 = 2400 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2300 + fogVar; } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } gameCamera.method303(-50, -10, -50); engineHandle = new EngineHandle(gameCamera, gameGraphics); loadTextures(); // 60% if (lastLoadedNull) return; loadModels(); // 75% if (lastLoadedNull) return; loadSounds(); // 90% if (lastLoadedNull) return; CacheManager.doneLoading(); drawDownloadProgress("Starting game...", 100, false); drawGameMenu(); makeLoginMenus(); makeCharacterDesignMenu(); makeDPSMenu(); resetLoginVars(); menusLoaded = true; } private final void loadSprite(int id, String packageName, int amount) { for (int i = id; i < id + amount; i++) { if (!gameGraphics.loadSprite(i, packageName)) { lastLoadedNull = true; return; } } } private final void loadMedia() { drawDownloadProgress("Unpacking media", 30, false); loadSprite(SPRITE_MEDIA_START, "media", 1); loadSprite(SPRITE_MEDIA_START + 1, "media", 6); loadSprite(SPRITE_MEDIA_START + 9, "media", 1); loadSprite(SPRITE_MEDIA_START + 10, "media", 1); loadSprite(SPRITE_MEDIA_START + 11, "media", 3); loadSprite(SPRITE_MEDIA_START + 14, "media", 8); loadSprite(SPRITE_MEDIA_START + 22, "media", 1); loadSprite(SPRITE_MEDIA_START + 23, "media", 1); loadSprite(SPRITE_MEDIA_START + 24, "media", 1); loadSprite(SPRITE_MEDIA_START + 25, "media", 2); loadSprite(SPRITE_UTIL_START, "media", 2); loadSprite(SPRITE_UTIL_START + 2, "media", 4); loadSprite(SPRITE_UTIL_START + 6, "media", 2); loadSprite(SPRITE_PROJECTILE_START, "media", 7); loadSprite(SPRITE_LOGO_START, "media", 1); int i = EntityHandler.invPictureCount(); for (int j = 1; i > 0; j++) { int k = i; i -= 30; if (k > 30) { k = 30; } loadSprite(SPRITE_ITEM_START + (j - 1) * 30, "media.object", k); } } private final void loadEntity() { drawDownloadProgress("Unpacking entities", 45, false); int animationNumber = 0; label0: for (int animationIndex = 0; animationIndex < EntityHandler .animationCount(); animationIndex++) { String s = EntityHandler.getAnimationDef(animationIndex).getName(); for (int nextAnimationIndex = 0; nextAnimationIndex < animationIndex; nextAnimationIndex++) { if (!EntityHandler.getAnimationDef(nextAnimationIndex) .getName().equalsIgnoreCase(s)) { continue; } EntityHandler.getAnimationDef(animationIndex).number = EntityHandler .getAnimationDef(nextAnimationIndex).getNumber(); continue label0; } loadSprite(animationNumber, "entity", 15); if (EntityHandler.getAnimationDef(animationIndex).hasA()) { loadSprite(animationNumber + 15, "entity", 3); } if (EntityHandler.getAnimationDef(animationIndex).hasF()) { loadSprite(animationNumber + 18, "entity", 9); } EntityHandler.getAnimationDef(animationIndex).number = animationNumber; animationNumber += 27; } } private final void loadTextures() { drawDownloadProgress("Unpacking textures", 60, false); gameCamera.method297(EntityHandler.textureCount(), 7, 11); for (int i = 0; i < EntityHandler.textureCount(); i++) { loadSprite(SPRITE_TEXTURE_START + i, "texture", 1); Sprite sprite = ((GameImage) (gameGraphics)).sprites[SPRITE_TEXTURE_START + i]; int length = sprite.getWidth() * sprite.getHeight(); int[] pixels = sprite.getPixels(); int ai1[] = new int[32768]; for (int k = 0; k < length; k++) { ai1[((pixels[k] & 0xf80000) >> 9) + ((pixels[k] & 0xf800) >> 6) + ((pixels[k] & 0xf8) >> 3)]++; } int[] dictionary = new int[256]; dictionary[0] = 0xff00ff; int[] temp = new int[256]; for (int i1 = 0; i1 < ai1.length; i1++) { int j1 = ai1[i1]; if (j1 > temp[255]) { for (int k1 = 1; k1 < 256; k1++) { if (j1 <= temp[k1]) { continue; } for (int i2 = 255; i2 > k1; i2--) { dictionary[i2] = dictionary[i2 - 1]; temp[i2] = temp[i2 - 1]; } dictionary[k1] = ((i1 & 0x7c00) << 9) + ((i1 & 0x3e0) << 6) + ((i1 & 0x1f) << 3) + 0x40404; temp[k1] = j1; break; } } ai1[i1] = -1; } byte[] indices = new byte[length]; for (int l1 = 0; l1 < length; l1++) { int j2 = pixels[l1]; int k2 = ((j2 & 0xf80000) >> 9) + ((j2 & 0xf800) >> 6) + ((j2 & 0xf8) >> 3); int l2 = ai1[k2]; if (l2 == -1) { int i3 = 0x3b9ac9ff; int j3 = j2 >> 16 & 0xff; int k3 = j2 >> 8 & 0xff; int l3 = j2 & 0xff; for (int i4 = 0; i4 < 256; i4++) { int j4 = dictionary[i4]; int k4 = j4 >> 16 & 0xff; int l4 = j4 >> 8 & 0xff; int i5 = j4 & 0xff; int j5 = (j3 - k4) * (j3 - k4) + (k3 - l4) * (k3 - l4) + (l3 - i5) * (l3 - i5); if (j5 < i3) { i3 = j5; l2 = i4; } } ai1[k2] = l2; } indices[l1] = (byte) l2; } gameCamera.method298(i, indices, dictionary, sprite.getSomething1() / 64 - 1); } } /* * private int lastMouseButton = -1; private int lastMouseX = -1; private * int lastMouseY = -1; private double camVert = 0.0D; private double camRot * = 0.0D; private java.awt.Robot robot; protected final void * handleMouseDrag(MouseEvent mouse, int x, int y, int button) { * if(controlDown && button == 2) { int unitX = x - lastMouseX; * * if(unitX > 1) unitX = 1; else if(unitX < -1) unitX = -1; * * int unitY = lastMouseY - y; * * if(unitY > 1) unitY = 1; else if(unitY < -1) unitY = -1; * * cameraVertical += unitY; //cameraRotation += unitX; * * System.out.println("Y: " + y + ", LastY: " + lastMouseY + " dif: (" + (y * - lastMouseY) + ")"); * * lastMouseX = x; lastMouseY = y; //super.mouseX = lastMouseX; * //super.mouseY = lastMouseY; //robot.mouseMove(super.mouseX, * super.mouseY); } } */ private final void checkMouseStatus() { /* * lastMouseX = * (int)java.awt.MouseInfo.getPointerInfo().getLocation().getX(); * lastMouseY = * (int)java.awt.MouseInfo.getPointerInfo().getLocation().getY(); * lastMouseButton = mouseButtonClick; * * if(mouseButtonClick == 2 && controlDown) return; */ if (selectedSpell >= 0 || selectedItem >= 0) { menuText1[menuLength] = "Cancel"; menuText2[menuLength] = ""; menuID[menuLength] = 4000; menuLength++; } for (int i = 0; i < menuLength; i++) menuIndexes[i] = i; for (boolean flag = false; !flag;) { flag = true; for (int j = 0; j < menuLength - 1; j++) { int l = menuIndexes[j]; int j1 = menuIndexes[j + 1]; if (menuID[l] > menuID[j1]) { menuIndexes[j] = j1; menuIndexes[j + 1] = l; flag = false; } } } if (menuLength > 20) menuLength = 20; if (menuLength > 0) { int k = -1; for (int i1 = 0; i1 < menuLength; i1++) { if (menuText2[menuIndexes[i1]] == null || menuText2[menuIndexes[i1]].length() <= 0) continue; k = i1; break; } String s = null; if ((selectedItem >= 0 || selectedSpell >= 0) && menuLength == 1) s = "Choose a target"; else if ((selectedItem >= 0 || selectedSpell >= 0) && menuLength > 1) s = "@whi@" + menuText1[menuIndexes[0]] + " " + menuText2[menuIndexes[0]]; else if (k != -1) s = menuText2[menuIndexes[k]] + ": @whi@" + menuText1[menuIndexes[0]]; if (menuLength == 2 && s != null) s = s + "@whi@ / 1 more option"; if (menuLength > 2 && s != null) s = s + "@whi@ / " + (menuLength - 1) + " more options"; if (s != null) gameGraphics.drawString(s, 6, 14, 1, 0xffff00); if (!configMouseButtons && mouseButtonClick == 1 || configMouseButtons && mouseButtonClick == 1 && menuLength == 1) { menuClick(menuIndexes[0]); mouseButtonClick = 0; return; } if (!configMouseButtons && mouseButtonClick == 2 || configMouseButtons && mouseButtonClick == 1) { menuHeight = (menuLength + 1) * 15; menuWidth = gameGraphics.textWidth("Choose option", 1) + 5; for (int k1 = 0; k1 < menuLength; k1++) { int l1 = gameGraphics.textWidth(menuText1[k1] + " " + menuText2[k1], 1) + 5; if (l1 > menuWidth) menuWidth = l1; } menuX = super.mouseX - menuWidth / 2; menuY = super.mouseY - 7; showRightClickMenu = true; if (menuX < 0) menuX = 0; if (menuY < 0) menuY = 0; if (menuX + menuWidth > (windowWidth - 10)) menuX = (windowWidth - 10) - menuWidth; if (menuY + menuHeight > (windowHeight)) menuY = (windowHeight - 10) - menuHeight; mouseButtonClick = 0; } } } protected final void cantLogout() { logoutTimeout = 0; displayMessage("@cya@Sorry, you can't logout at the moment", 3, 0); } private final void drawFriendsWindow(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 5); char c = '\304'; char c1 = '\266'; int l; int k = l = GameImage.convertRGBToLong(160, 160, 160); if (anInt981 == 0) k = GameImage.convertRGBToLong(220, 220, 220); else l = GameImage.convertRGBToLong(220, 220, 220); int maxWidth = windowWidth - 23; int minWidth = windowWidth - 83; gameGraphics.drawBoxAlpha(i, j, c / 2, 24, k, 128); gameGraphics.drawBoxAlpha(i + c / 2, j, c / 2, 24, l, 128); gameGraphics.drawBoxAlpha(i, j + 24, c, c1 - 24, GameImage.convertRGBToLong(220, 220, 220), 128); gameGraphics.drawLineX(i, j + 24, c, 0); gameGraphics.drawLineY(i + c / 2, j, 24, 0); gameGraphics.drawLineX(i, (j + c1) - 16, c, 0); gameGraphics.drawText("Friends", i + c / 4, j + 16, 4, 0); gameGraphics.drawText("Ignore", i + c / 4 + c / 2, j + 16, 4, 0); friendsMenu.resetListTextCount(friendsMenuHandle); if (anInt981 == 0) { for (int i1 = 0; i1 < super.friendsCount; i1++) { String s; if (super.friendsListOnlineStatus[i1] == 99) s = "@gre@"; else if (super.friendsListOnlineStatus[i1] > 0) s = "@yel@"; else s = "@red@"; friendsMenu .drawMenuListText( friendsMenuHandle, i1, s + DataOperations .longToString(super.friendsListLongs[i1]) + "~" + (windowWidth - 73) + "~" + "@whi@Remove WWWWWWWWWW"); } } if (anInt981 == 1) { for (int j1 = 0; j1 < super.ignoreListCount; j1++) friendsMenu .drawMenuListText( friendsMenuHandle, j1, "@yel@" + DataOperations .longToString(super.ignoreListLongs[j1]) + "~" + (windowWidth - 73) + "~" + "@whi@Remove WWWWWWWWWW"); } friendsMenu.drawMenu(); if (anInt981 == 0) { int k1 = friendsMenu.selectedListIndex(friendsMenuHandle); if (k1 >= 0 && super.mouseX < maxWidth) { if (super.mouseX > minWidth) gameGraphics .drawText( "Click to remove " + DataOperations .longToString(super.friendsListLongs[k1]), i + c / 2, j + 35, 1, 0xffffff); else if (super.friendsListOnlineStatus[k1] == 99) gameGraphics .drawText( "Click to message " + DataOperations .longToString(super.friendsListLongs[k1]), i + c / 2, j + 35, 1, 0xffffff); else if (super.friendsListOnlineStatus[k1] > 0) gameGraphics.drawText( DataOperations .longToString(super.friendsListLongs[k1]) + " is on world " + super.friendsListOnlineStatus[k1], i + c / 2, j + 35, 1, 0xffffff); else gameGraphics.drawText( DataOperations .longToString(super.friendsListLongs[k1]) + " is offline", i + c / 2, j + 35, 1, 0xffffff); } else gameGraphics.drawText("Click a name to send a message", i + c / 2, j + 35, 1, 0xffffff); int k2; if (super.mouseX > i && super.mouseX < i + c && super.mouseY > (j + c1) - 16 && super.mouseY < j + c1) k2 = 0xffff00; else k2 = 0xffffff; gameGraphics.drawText("Click here to add a friend", i + c / 2, (j + c1) - 3, 1, k2); } if (anInt981 == 1) { int l1 = friendsMenu.selectedListIndex(friendsMenuHandle); if (l1 >= 0 && super.mouseX < maxWidth && super.mouseX > minWidth) { if (super.mouseX > minWidth) gameGraphics .drawText( "Click to remove " + DataOperations .longToString(super.ignoreListLongs[l1]), i + c / 2, j + 35, 1, 0xffffff); } else { gameGraphics.drawText("Blocking messages from:", i + c / 2, j + 35, 1, 0xffffff); } int l2; if (super.mouseX > i && super.mouseX < i + c && super.mouseY > (j + c1) - 16 && super.mouseY < j + c1) l2 = 0xffff00; else l2 = 0xffffff; gameGraphics.drawText("Click here to add a name", i + c / 2, (j + c1) - 3, 1, l2); } if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 182) { friendsMenu.updateActions(i + (((GameImage) (gameGraphics)).menuDefaultWidth - 199), j + 36, super.lastMouseDownButton, super.mouseDownButton); if (j <= 24 && mouseButtonClick == 1) if (i < 98 && anInt981 == 1) { anInt981 = 0; friendsMenu.method165(friendsMenuHandle, 0); } else if (i > 98 && anInt981 == 0) { anInt981 = 1; friendsMenu.method165(friendsMenuHandle, 0); } if (mouseButtonClick == 1 && anInt981 == 0) { int i2 = friendsMenu.selectedListIndex(friendsMenuHandle); if (i2 >= 0 && super.mouseX < maxWidth) if (super.mouseX > minWidth) removeFromFriends(super.friendsListLongs[i2]); else if (super.friendsListOnlineStatus[i2] != 0) { inputBoxType = 2; privateMessageTarget = super.friendsListLongs[i2]; super.inputMessage = ""; super.enteredMessage = ""; } } if (mouseButtonClick == 1 && anInt981 == 1) { int j2 = friendsMenu.selectedListIndex(friendsMenuHandle); if (j2 >= 0 && super.mouseX < maxWidth && super.mouseX > minWidth) removeFromIgnoreList(super.ignoreListLongs[j2]); } if (j > 166 && mouseButtonClick == 1 && anInt981 == 0) { inputBoxType = 1; super.inputText = ""; super.enteredText = ""; } if (j > 166 && mouseButtonClick == 1 && anInt981 == 1) { inputBoxType = 3; super.inputText = ""; super.enteredText = ""; } mouseButtonClick = 0; } } private final boolean loadSection(int i, int j) { if (playerAliveTimeout != 0) { engineHandle.playerIsAlive = false; return false; } notInWilderness = false; i += wildX; j += wildY; if (lastWildYSubtract == wildYSubtract && i > anInt789 && i < anInt791 && j > anInt790 && j < anInt792) { engineHandle.playerIsAlive = true; return false; } gameGraphics.drawText("Loading... Please wait", 256 + xAddition, 192 + yAddition, 1, 0xffffff); drawChatMessageTabs(); drawOurSpritesOnScreen(); gameGraphics.drawImage(aGraphics936, 0, 0); int k = getAreaX(); int l = getAreaY(); int i1 = (i + 24) / 48; int j1 = (j + 24) / 48; lastWildYSubtract = wildYSubtract; setAreaX(i1 * 48 - 48); setAreaY(j1 * 48 - 48); anInt789 = i1 * 48 - 32; anInt790 = j1 * 48 - 32; anInt791 = i1 * 48 + 32; anInt792 = j1 * 48 + 32; engineHandle.method401(i, j, lastWildYSubtract); setAreaX(getAreaX() - wildX); setAreaY(getAreaY() - wildY); int k1 = getAreaX() - k; int l1 = getAreaY() - l; for (int i2 = 0; i2 < objectCount; i2++) { objectX[i2] -= k1; objectY[i2] -= l1; int j2 = objectX[i2]; int l2 = objectY[i2]; int k3 = objectType[i2]; int m4 = objectID[i2]; Model model = objectModelArray[i2]; try { int l4 = objectID[i2]; int k5; int i6; if (l4 == 0 || l4 == 4) { k5 = EntityHandler.getObjectDef(k3).getWidth(); i6 = EntityHandler.getObjectDef(k3).getHeight(); } else { i6 = EntityHandler.getObjectDef(k3).getWidth(); k5 = EntityHandler.getObjectDef(k3).getHeight(); } int j6 = ((j2 + j2 + k5) * magicLoc) / 2; int k6 = ((l2 + l2 + i6) * magicLoc) / 2; if (j2 >= 0 && l2 >= 0 && j2 < 96 && l2 < 96) { gameCamera.addModel(model); model.method191(j6, -engineHandle.getAveragedElevation(j6, k6), k6); engineHandle.method412(j2, l2, k3, m4); if (k3 == 74) model.method190(0, -480, 0); } } catch (RuntimeException runtimeexception) { System.out.println("Loc Error: " + runtimeexception.getMessage()); System.out.println("i:" + i2 + " obj:" + model); runtimeexception.printStackTrace(); } } for (int k2 = 0; k2 < doorCount; k2++) { doorX[k2] -= k1; doorY[k2] -= l1; int i3 = doorX[k2]; int l3 = doorY[k2]; int j4 = doorType[k2]; int i5 = doorDirection[k2]; try { engineHandle.method408(i3, l3, i5, j4); Model model_1 = makeModel(i3, l3, i5, j4, k2); doorModel[k2] = model_1; } catch (RuntimeException runtimeexception1) { System.out.println("Bound Error: " + runtimeexception1.getMessage()); runtimeexception1.printStackTrace(); } } for (int j3 = 0; j3 < groundItemCount; j3++) { groundItemX[j3] -= k1; groundItemY[j3] -= l1; } for (int i4 = 0; i4 < playerCount; i4++) { Mob mob = playerArray[i4]; mob.currentX -= k1 * magicLoc; mob.currentY -= l1 * magicLoc; for (int j5 = 0; j5 <= mob.waypointCurrent; j5++) { mob.waypointsX[j5] -= k1 * magicLoc; mob.waypointsY[j5] -= l1 * magicLoc; } } for (int k4 = 0; k4 < npcCount; k4++) { Mob mob_1 = npcArray[k4]; mob_1.currentX -= k1 * magicLoc; mob_1.currentY -= l1 * magicLoc; for (int l5 = 0; l5 <= mob_1.waypointCurrent; l5++) { mob_1.waypointsX[l5] -= k1 * magicLoc; mob_1.waypointsY[l5] -= l1 * magicLoc; } } engineHandle.playerIsAlive = true; return true; } private final void drawMagicWindow(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 4); char c = '\304'; char c1 = '\266'; int l; int k = l = GameImage.convertRGBToLong(160, 160, 160); if (menuMagicPrayersSelected == 0) k = GameImage.convertRGBToLong(220, 220, 220); else l = GameImage.convertRGBToLong(220, 220, 220); gameGraphics.drawBoxAlpha(i, j, c / 2, 24, k, 128); gameGraphics.drawBoxAlpha(i + c / 2, j, c / 2, 24, l, 128); gameGraphics.drawBoxAlpha(i, j + 24, c, 90, GameImage.convertRGBToLong(220, 220, 220), 128); gameGraphics.drawBoxAlpha(i, j + 24 + 90, c, c1 - 90 - 24, GameImage.convertRGBToLong(160, 160, 160), 128); gameGraphics.drawLineX(i, j + 24, c, 0); gameGraphics.drawLineY(i + c / 2, j, 24, 0); gameGraphics.drawLineX(i, j + 113, c, 0); gameGraphics.drawText("Magic", i + c / 4, j + 16, 4, 0); gameGraphics.drawText("Prayers", i + c / 4 + c / 2, j + 16, 4, 0); if (menuMagicPrayersSelected == 0) { spellMenu.resetListTextCount(spellMenuHandle); int i1 = 0; for (int spellIndex = 0; spellIndex < EntityHandler.spellCount(); spellIndex++) { String s = "@yel@"; for (Entry e : EntityHandler.getSpellDef(spellIndex) .getRunesRequired()) { if (hasRequiredRunes((Integer) e.getKey(), (Integer) e.getValue())) { continue; } s = "@whi@"; break; } int spellLevel = playerStatCurrent[6]; if (EntityHandler.getSpellDef(spellIndex).getReqLevel() > spellLevel) { s = "@bla@"; } spellMenu.drawMenuListText(spellMenuHandle, i1++, s + "Level " + EntityHandler.getSpellDef(spellIndex).getReqLevel() + ": " + EntityHandler.getSpellDef(spellIndex).getName()); } spellMenu.drawMenu(); int selectedSpellIndex = spellMenu .selectedListIndex(spellMenuHandle); if (selectedSpellIndex != -1) { gameGraphics .drawString( "Level " + EntityHandler.getSpellDef( selectedSpellIndex) .getReqLevel() + ": " + EntityHandler.getSpellDef( selectedSpellIndex).getName(), i + 2, j + 124, 1, 0xffff00); gameGraphics.drawString( EntityHandler.getSpellDef(selectedSpellIndex) .getDescription(), i + 2, j + 136, 0, 0xffffff); int i4 = 0; for (Entry<Integer, Integer> e : EntityHandler.getSpellDef( selectedSpellIndex).getRunesRequired()) { int runeID = e.getKey(); gameGraphics.drawPicture(i + 2 + i4 * 44, j + 150, SPRITE_ITEM_START + EntityHandler.getItemDef(runeID) .getSprite()); int runeInvCount = inventoryCount(runeID); int runeCount = e.getValue(); String s2 = "@red@"; if (hasRequiredRunes(runeID, runeCount)) { s2 = "@gre@"; } gameGraphics.drawString( s2 + runeInvCount + "/" + runeCount, i + 2 + i4 * 44, j + 150, 1, 0xffffff); i4++; } } else { gameGraphics.drawString("Point at a spell for a description", i + 2, j + 124, 1, 0); } } if (menuMagicPrayersSelected == 1) { spellMenu.resetListTextCount(spellMenuHandle); int j1 = 0; for (int j2 = 0; j2 < EntityHandler.prayerCount(); j2++) { String s1 = "@whi@"; if (EntityHandler.getPrayerDef(j2).getReqLevel() > playerStatBase[5]) s1 = "@bla@"; if (prayerOn[j2]) s1 = "@gre@"; spellMenu.drawMenuListText(spellMenuHandle, j1++, s1 + "Level " + EntityHandler.getPrayerDef(j2).getReqLevel() + ": " + EntityHandler.getPrayerDef(j2).getName()); } spellMenu.drawMenu(); int j3 = spellMenu.selectedListIndex(spellMenuHandle); if (j3 != -1) { gameGraphics.drawText("Level " + EntityHandler.getPrayerDef(j3).getReqLevel() + ": " + EntityHandler.getPrayerDef(j3).getName(), i + c / 2, j + 130, 1, 0xffff00); if (j3 == 13) { if (playerStatBase[5] > 39) { int percent = (int) ((playerStatBase[5] - 40) * 0.6); percent += 60; if (percent > 100) percent = 100; gameGraphics.drawText(percent + "% protection from ranged attack", i + c / 2, j + 145, 0, 0xffffff); } else gameGraphics.drawText( "60% protection from ranged attack", i + c / 2, j + 145, 0, 0xffffff); } else gameGraphics.drawText(EntityHandler.getPrayerDef(j3) .getDescription(), i + c / 2, j + 145, 0, 0xffffff); gameGraphics.drawText("Drain rate: " + EntityHandler.getPrayerDef(j3).getDrainRate(), i + c / 2, j + 160, 1, 0); } else { gameGraphics.drawString("Point at a prayer for a description", i + 2, j + 124, 1, 0); } } if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 182) { spellMenu.updateActions(i + (((GameImage) (gameGraphics)).menuDefaultWidth - 199), j + 36, super.lastMouseDownButton, super.mouseDownButton); if (j <= 24 && mouseButtonClick == 1) if (i < 98 && menuMagicPrayersSelected == 1) { menuMagicPrayersSelected = 0; prayerMenuIndex = spellMenu.getMenuIndex(spellMenuHandle); spellMenu.method165(spellMenuHandle, magicMenuIndex); } else if (i > 98 && menuMagicPrayersSelected == 0) { menuMagicPrayersSelected = 1; magicMenuIndex = spellMenu.getMenuIndex(spellMenuHandle); spellMenu.method165(spellMenuHandle, prayerMenuIndex); } if (mouseButtonClick == 1 && menuMagicPrayersSelected == 0) { int k1 = spellMenu.selectedListIndex(spellMenuHandle); if (k1 != -1) { int k2 = playerStatCurrent[6]; if (EntityHandler.getSpellDef(k1).getReqLevel() > k2) { displayMessage( "Your magic ability is not high enough for this spell", 3, 0); } else { int k3 = 0; for (Entry<Integer, Integer> e : EntityHandler .getSpellDef(k1).getRunesRequired()) { if (!hasRequiredRunes(e.getKey(), e.getValue())) { displayMessage( "You don't have all the reagents you need for this spell", 3, 0); k3 = -1; break; } k3++; } if (k3 == EntityHandler.getSpellDef(k1).getRuneCount()) { selectedSpell = k1; selectedItem = -1; } } } } if (mouseButtonClick == 1 && menuMagicPrayersSelected == 1) { int l1 = spellMenu.selectedListIndex(spellMenuHandle); if (l1 != -1) { int l2 = playerStatBase[5]; if (EntityHandler.getPrayerDef(l1).getReqLevel() > l2) displayMessage( "Your prayer ability is not high enough for this prayer", 3, 0); else if (playerStatCurrent[5] == 0) displayMessage( "You have run out of prayer points. Return to a church to recharge", 3, 0); else if (prayerOn[l1]) { super.streamClass.createPacket(248); super.streamClass.addByte(l1); super.streamClass.formatPacket(); prayerOn[l1] = false; playSound("prayeroff"); } else { super.streamClass.createPacket(56); super.streamClass.addByte(l1); super.streamClass.formatPacket(); prayerOn[l1] = true; playSound("prayeron"); } } } mouseButtonClick = 0; } } protected final void handleWheelRotate(int units) { if (super.controlDown) { if (units > -1) { if (cameraVertical >= 1000) return; } else { if (cameraVertical <= 850) return; } cameraVertical += units * 2; } } protected final void handleMenuKeyDown(int key, char keyChar) { if (!menusLoaded) return; switch (key) { case 123: // F12 takeScreenshot(true); break; case 33: { if (cameraHeight < 300) { cameraHeight += 25; } else { cameraHeight -= 25; } break; } case 34: { // Page Down { if (cameraHeight > 1500) { cameraHeight -= 25; } else { cameraHeight += 25; } break; } case 36: { cameraHeight = 750; break; } } if (loggedIn == 0) { if (loginScreenNumber == 0) menuWelcome.keyDown(key, keyChar); if (loginScreenNumber == 1) menuNewUser.keyDown(key, keyChar); if (loginScreenNumber == 2) menuLogin.keyDown(key, keyChar); } if (loggedIn == 1) { if (showCharacterLookScreen) { characterDesignMenu.keyDown(key, keyChar); return; } if (showDrawPointsScreen) { drawPointsScreen.keyDown(key, keyChar); return; } if (inputBoxType == 0 && showAbuseWindow == 0) gameMenu.keyDown(key, keyChar); } } private final void drawShopBox() { if (mouseButtonClick != 0) { mouseButtonClick = 0; int i = super.mouseX - 52 - xAddition; int j = super.mouseY - 44 - yAddition; if (i >= 0 && j >= 12 && i < 408 && j < 246) { int k = 0; for (int i1 = 0; i1 < 5; i1++) { for (int i2 = 0; i2 < 8; i2++) { int l2 = 7 + i2 * 49; int l3 = 28 + i1 * 34; if (i > l2 && i < l2 + 49 && j > l3 && j < l3 + 34 && shopItems[k] != -1) { selectedShopItemIndex = k; selectedShopItemType = shopItems[k]; } k++; } } if (selectedShopItemIndex >= 0) { int j2 = shopItems[selectedShopItemIndex]; if (j2 != -1) { if (shopItemCount[selectedShopItemIndex] > 0 && i > 298 && j >= 204 && i < 408 && j <= 215) { int i4 = shopItemsBuyPrice[selectedShopItemIndex];// (shopItemBuyPriceModifier // * // EntityHandler.getItemDef(j2).getBasePrice()) // / // 100; super.streamClass.createPacket(128); super.streamClass .add2ByteInt(shopItems[selectedShopItemIndex]); super.streamClass.add4ByteInt(i4); super.streamClass.formatPacket(); } if (inventoryCount(j2) > 0 && i > 2 && j >= 229 && i < 112 && j <= 240) { int j4 = shopItemsSellPrice[selectedShopItemIndex];// (shopItemSellPriceModifier // * // EntityHandler.getItemDef(j2).getBasePrice()) // / // 100; super.streamClass.createPacket(255); super.streamClass .add2ByteInt(shopItems[selectedShopItemIndex]); super.streamClass.add4ByteInt(j4); super.streamClass.formatPacket(); } } } } else { super.streamClass.createPacket(253); super.streamClass.formatPacket(); showShop = false; return; } } int byte0 = 52 + xAddition; int byte1 = 44 + yAddition; gameGraphics.drawBox(byte0, byte1, 408, 12, 192); int l = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 408, 17, l, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 29, 8, 170, l, 160); gameGraphics.drawBoxAlpha(byte0 + 399, byte1 + 29, 9, 170, l, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 199, 408, 47, l, 160); gameGraphics.drawString("Buying and selling items", byte0 + 1, byte1 + 10, 1, 0xffffff); int j1 = 0xffffff; if (super.mouseX > byte0 + 320 && super.mouseY >= byte1 && super.mouseX < byte0 + 408 && super.mouseY < byte1 + 12) j1 = 0xff0000; gameGraphics.drawBoxTextRight("Close window", byte0 + 406, byte1 + 10, 1, j1); gameGraphics.drawString("Shops stock in green", byte0 + 2, byte1 + 24, 1, 65280); gameGraphics.drawString("Number you own in blue", byte0 + 135, byte1 + 24, 1, 65535); gameGraphics.drawString("Your money: " + inventoryCount(10) + "gp", byte0 + 280, byte1 + 24, 1, 0xffff00); int k2 = 0xd0d0d0; int k3 = 0; for (int k4 = 0; k4 < 5; k4++) { for (int l4 = 0; l4 < 8; l4++) { int j5 = byte0 + 7 + l4 * 49; int i6 = byte1 + 28 + k4 * 34; if (selectedShopItemIndex == k3) gameGraphics.drawBoxAlpha(j5, i6, 49, 34, 0xff0000, 160); else gameGraphics.drawBoxAlpha(j5, i6, 49, 34, k2, 160); gameGraphics.drawBoxEdge(j5, i6, 50, 35, 0); if (shopItems[k3] != -1) { gameGraphics.spriteClip4(j5, i6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(shopItems[k3]) .getSprite(), EntityHandler.getItemDef(shopItems[k3]) .getPictureMask(), 0, 0, false); gameGraphics.drawString(String.valueOf(shopItemCount[k3]), j5 + 1, i6 + 10, 1, 65280); gameGraphics.drawBoxTextRight( String.valueOf(inventoryCount(shopItems[k3])), j5 + 47, i6 + 10, 1, 65535); } k3++; } } gameGraphics.drawLineX(byte0 + 5, byte1 + 222, 398, 0); if (selectedShopItemIndex == -1) { gameGraphics.drawText("Select an object to buy or sell", byte0 + 204, byte1 + 214, 3, 0xffff00); return; } int i5 = shopItems[selectedShopItemIndex]; if (i5 != -1) { if (shopItemCount[selectedShopItemIndex] > 0) { int j6 = shopItemsBuyPrice[selectedShopItemIndex];// (shopItemBuyPriceModifier // * // EntityHandler.getItemDef( // i5).getBasePrice()) / 100; gameGraphics.drawString("Buy a new " + EntityHandler.getItemDef(i5).getName() + " for " + j6 + "gp", byte0 + 2, byte1 + 214, 1, 0xffff00); int k1 = 0xffffff; if (super.mouseX > byte0 + 298 && super.mouseY >= byte1 + 204 && super.mouseX < byte0 + 408 && super.mouseY <= byte1 + 215) k1 = 0xff0000; gameGraphics.drawBoxTextRight("Click here to buy", byte0 + 405, byte1 + 214, 3, k1); } else { gameGraphics.drawText( "This item is not currently available to buy", byte0 + 204, byte1 + 214, 3, 0xffff00); } if (inventoryCount(i5) > 0) { int k6 = shopItemsSellPrice[selectedShopItemIndex];// (shopItemSellPriceModifier // * // EntityHandler.getItemDef( // i5).getBasePrice()) / 100; gameGraphics.drawBoxTextRight("Sell your " + EntityHandler.getItemDef(i5).getName() + " for " + k6 + "gp", byte0 + 405, byte1 + 239, 1, 0xffff00); int l1 = 0xffffff; if (super.mouseX > byte0 + 2 && super.mouseY >= byte1 + 229 && super.mouseX < byte0 + 112 && super.mouseY <= byte1 + 240) l1 = 0xff0000; gameGraphics.drawString("Click here to sell", byte0 + 2, byte1 + 239, 3, l1); return; } gameGraphics.drawText("You do not have any of this item to sell", byte0 + 204, byte1 + 239, 3, 0xffff00); } } private final void drawGameMenu() { gameMenu = new Menu(gameGraphics, 10); messagesHandleType2 = gameMenu.method159(5, windowHeight - 85, windowWidth - 10, 56, 1, 20, true); chatHandle = gameMenu.method160(7, windowHeight - 10, windowWidth - 14, 14, 1, 80, false, true); messagesHandleType5 = gameMenu.method159(5, windowHeight - 65, windowWidth - 10, 56, 1, 20, true); messagesHandleType6 = gameMenu.method159(5, windowHeight - 65, windowWidth - 10, 56, 1, 20, true); gameMenu.setFocus(chatHandle); } protected final byte[] load(String filename) { CacheManager.load(filename); return super.load(Config.CONF_DIR + File.separator + filename); } /** * Draws our options menu (client size etc) * * @param flag */ private final void drawOurOptionsMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 232; int j = 36; int c = 360; gameGraphics.drawBoxAlpha(i, 36, c, 176, GameImage.convertRGBToLong(181, 181, 181), 160); /** * Draws the gray box behind the icon */ gameGraphics.drawBox(i, 3, 31, 32, GameImage.convertRGBToLong(0, 0, 131)); int temp = 10; gameGraphics.drawBox(i, 26, 274, temp, GameImage.convertRGBToLong(0, 0, 131)); gameGraphics.drawBox(i, 26 + temp, 274, 1, GameImage.convertRGBToLong(0, 0, 0)); gameGraphics.drawString("screen size", i + 147, 26 + temp, 4, 0xffffff); int k = i + 3; int i1 = j + 15; i1 += 15; if (Resolutions.fs) gameGraphics.drawString( " Fullscreen @gre@On", k, i1, 1, 0xffffff); else gameGraphics.drawString( " Fullscreen @red@Off", k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" Screen size @gre@" + reso.getResolution(), k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" Refresh rate @gre@" + reso.getRefreshRate(), k, i1, 1, 0xffffff); i1 += 30; gameGraphics.drawString(" Window size will change after you", k, i1, 1, 0xffffff); i1 += 15; gameGraphics .drawString(" restart the client.", k, i1, 1, 0xffffff); i1 += 30; gameGraphics.drawString(" Going to fullsreen and back does", k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" not require a client restart.", k, i1, 1, 0xffffff); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 265) { int l1 = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; char c1 = '\304'; int l = l1 + 3; int j1 = byte0 + 30; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { if (gameFrame == null) { mudclient .drawPopup("You cannot switch to fullscreen from the webclient, sorry!"); return; } if (Resolutions.fs) { gameFrame.makeRegularScreen(); } else { gameFrame.makeFullScreen(); } } j1 += 15; // amera error if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { reso.findNextResolution(); Config.storeConfig( "width", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getWidth()); Config.storeConfig( "height", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getHeight()); Config.storeConfig( "refreshRate", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getRefreshRate()); Config.storeConfig( "bitDepth", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getBitDepth()); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; boolean flag1 = false; j1 += 35; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; j1 += 20; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) mouseButtonClick = 0; } } private final void drawOptionsMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 6); char c = '\304'; gameGraphics.drawBoxAlpha(i, 36, c, 65, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 101, c, 65, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 166, c, 95, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 261, c, 52, GameImage.convertRGBToLong(181, 181, 181), 160); int k = i + 3; int i1 = j + 15; gameGraphics.drawString("Game options - click to toggle", k, i1, 1, 0); i1 += 15; if (configAutoCameraAngle) gameGraphics.drawString("Camera angle mode - @gre@Auto", k, i1, 1, 0xffffff); else gameGraphics.drawString("Camera angle mode - @red@Manual", k, i1, 1, 0xffffff); i1 += 15; if (configMouseButtons) gameGraphics.drawString("Mouse buttons - @red@One", k, i1, 1, 0xffffff); else gameGraphics.drawString("Mouse buttons - @gre@Two", k, i1, 1, 0xffffff); i1 += 15; if (configSoundEffects) gameGraphics.drawString("Sound effects - @red@off", k, i1, 1, 0xffffff); else gameGraphics.drawString("Sound effects - @gre@on", k, i1, 1, 0xffffff); i1 += 15; gameGraphics .drawString("Client assists - click to toggle", k, i1, 1, 0); i1 += 15; if (showRoof) gameGraphics .drawString("Hide Roofs - @red@off", k, i1, 1, 0xffffff); else gameGraphics.drawString("Hide Roofs - @gre@on", k, i1, 1, 0xffffff); i1 += 15; if (autoScreenshot) gameGraphics.drawString("Auto Screenshots - @gre@on", k, i1, 1, 0xffffff); else gameGraphics.drawString("Auto Screenshots - @red@off", k, i1, 1, 0xffffff); i1 += 15; if (combatWindow) gameGraphics.drawString("Fightmode Selector - @gre@on", k, i1, 1, 0xffffff); else gameGraphics.drawString("Fightmode Selector - @red@off", k, i1, 1, 0xffffff); i1 += 15; if (fog) gameGraphics.drawString("Fog of War - @gre@on", k, i1, 1, 0xffffff); else gameGraphics .drawString("Fog of War - @red@off", k, i1, 1, 0xffffff); i1 += 15; i1 += 5; gameGraphics.drawString("Privacy settings. Will be applied to", i + 3, i1, 1, 0); i1 += 15; gameGraphics.drawString("all people not on your friends list", i + 3, i1, 1, 0); i1 += 15; if (super.blockChatMessages == 0) gameGraphics.drawString("Block chat messages: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block chat messages: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockPrivateMessages == 0) gameGraphics.drawString("Block private messages: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block private messages: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockTradeRequests == 0) gameGraphics.drawString("Block trade requests: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block trade requests: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockDuelRequests == 0) gameGraphics.drawString("Block duel requests: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block duel requests: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; i1 += 5; gameGraphics.drawString("Always logout when you finish", k, i1, 1, 0); i1 += 15; int k1 = 0xffffff; if (super.mouseX > k && super.mouseX < k + c && super.mouseY > i1 - 12 && super.mouseY < i1 + 4) k1 = 0xffff00; gameGraphics.drawString("Click here to logout", i + 3, i1, 1, k1); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 265) { int l1 = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; char c1 = '\304'; int l = l1 + 3; int j1 = byte0 + 30; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configAutoCameraAngle = !configAutoCameraAngle; super.streamClass.createPacket(157); super.streamClass.addByte(0); super.streamClass.addByte(configAutoCameraAngle ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; // amera error if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configMouseButtons = !configMouseButtons; super.streamClass.createPacket(157); super.streamClass.addByte(2); super.streamClass.addByte(configMouseButtons ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configSoundEffects = !configSoundEffects; super.streamClass.createPacket(157); super.streamClass.addByte(3); super.streamClass.addByte(configSoundEffects ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { showRoof = !showRoof; super.streamClass.createPacket(157); super.streamClass.addByte(4); super.streamClass.addByte(showRoof ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { autoScreenshot = !autoScreenshot; super.streamClass.createPacket(157); super.streamClass.addByte(5); super.streamClass.addByte(autoScreenshot ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { combatWindow = !combatWindow; super.streamClass.createPacket(157); super.streamClass.addByte(6); super.streamClass.addByte(combatWindow ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { fog = !fog; } j1 += 15; boolean flag1 = false; j1 += 35; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockChatMessages = 1 - super.blockChatMessages; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockPrivateMessages = 1 - super.blockPrivateMessages; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockTradeRequests = 1 - super.blockTradeRequests; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockDuelRequests = 1 - super.blockDuelRequests; flag1 = true; } j1 += 15; if (flag1) sendUpdatedPrivacyInfo(super.blockChatMessages, super.blockPrivateMessages, super.blockTradeRequests, super.blockDuelRequests); j1 += 20; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) logout(); mouseButtonClick = 0; } } private final void processGame() { try { if (super.keyDownDown) { currentChat++; if (currentChat >= messages.size()) { currentChat = messages.size() - 1; super.keyDownDown = false; return; } gameMenu.updateText(chatHandle, messages.get(currentChat)); super.keyDownDown = false; } if (super.keyUpDown) { currentChat--; if (currentChat < 0) { currentChat = 0; super.keyUpDown = false; return; } gameMenu.updateText(chatHandle, messages.get(currentChat)); super.keyUpDown = false; } } catch (Exception e) { e.printStackTrace(); } if (systemUpdate > 1) { systemUpdate--; } sendPingPacketReadPacketData(); if (logoutTimeout > 0) { logoutTimeout--; } if (ourPlayer.currentSprite == 8 || ourPlayer.currentSprite == 9) { lastWalkTimeout = 500; } if (lastWalkTimeout > 0) { lastWalkTimeout--; } if (showCharacterLookScreen) { drawCharacterLookScreen(); return; } if (showDrawPointsScreen) { drawPointsScreen(); return; } for (int i = 0; i < playerCount; i++) { Mob mob = playerArray[i]; int k = (mob.waypointCurrent + 1) % 10; if (mob.waypointEndSprite != k) { int i1 = -1; int l2 = mob.waypointEndSprite; int j4; if (l2 < k) j4 = k - l2; else j4 = (10 + k) - l2; int j5 = 4; if (j4 > 2) j5 = (j4 - 1) * 4; if (mob.waypointsX[l2] - mob.currentX > magicLoc * 3 || mob.waypointsY[l2] - mob.currentY > magicLoc * 3 || mob.waypointsX[l2] - mob.currentX < -magicLoc * 3 || mob.waypointsY[l2] - mob.currentY < -magicLoc * 3 || j4 > 8) { mob.currentX = mob.waypointsX[l2]; mob.currentY = mob.waypointsY[l2]; } else { if (mob.currentX < mob.waypointsX[l2]) { mob.currentX += j5; mob.stepCount++; i1 = 2; } else if (mob.currentX > mob.waypointsX[l2]) { mob.currentX -= j5; mob.stepCount++; i1 = 6; } if (mob.currentX - mob.waypointsX[l2] < j5 && mob.currentX - mob.waypointsX[l2] > -j5) mob.currentX = mob.waypointsX[l2]; if (mob.currentY < mob.waypointsY[l2]) { mob.currentY += j5; mob.stepCount++; if (i1 == -1) i1 = 4; else if (i1 == 2) i1 = 3; else i1 = 5; } else if (mob.currentY > mob.waypointsY[l2]) { mob.currentY -= j5; mob.stepCount++; if (i1 == -1) i1 = 0; else if (i1 == 2) i1 = 1; else i1 = 7; } if (mob.currentY - mob.waypointsY[l2] < j5 && mob.currentY - mob.waypointsY[l2] > -j5) mob.currentY = mob.waypointsY[l2]; } if (i1 != -1) mob.currentSprite = i1; if (mob.currentX == mob.waypointsX[l2] && mob.currentY == mob.waypointsY[l2]) mob.waypointEndSprite = (l2 + 1) % 10; } else { mob.currentSprite = mob.nextSprite; } if (mob.lastMessageTimeout > 0) mob.lastMessageTimeout--; if (mob.anInt163 > 0) mob.anInt163--; if (mob.combatTimer > 0) mob.combatTimer--; if (playerAliveTimeout > 0) { playerAliveTimeout--; if (playerAliveTimeout == 0) displayMessage( "You have been granted another life. Be more careful this time!", 3, 0); if (playerAliveTimeout == 0) displayMessage( "You retain your skills. Your objects land where you died", 3, 0); } } for (int j = 0; j < npcCount; j++) { Mob mob_1 = npcArray[j]; if (mob_1 == null) { System.out.println("MOB == NULL, npcCount: " + npcCount + ", j: " + j); System.exit(1); } int j1 = (mob_1.waypointCurrent + 1) % 10; if (mob_1.waypointEndSprite != j1) { int i3 = -1; int k4 = mob_1.waypointEndSprite; int k5; if (k4 < j1) k5 = j1 - k4; else k5 = (10 + j1) - k4; int l5 = 4; if (k5 > 2) l5 = (k5 - 1) * 4; if (mob_1.waypointsX[k4] - mob_1.currentX > magicLoc * 3 || mob_1.waypointsY[k4] - mob_1.currentY > magicLoc * 3 || mob_1.waypointsX[k4] - mob_1.currentX < -magicLoc * 3 || mob_1.waypointsY[k4] - mob_1.currentY < -magicLoc * 3 || k5 > 8) { mob_1.currentX = mob_1.waypointsX[k4]; mob_1.currentY = mob_1.waypointsY[k4]; } else { if (mob_1.currentX < mob_1.waypointsX[k4]) { mob_1.currentX += l5; mob_1.stepCount++; i3 = 2; } else if (mob_1.currentX > mob_1.waypointsX[k4]) { mob_1.currentX -= l5; mob_1.stepCount++; i3 = 6; } if (mob_1.currentX - mob_1.waypointsX[k4] < l5 && mob_1.currentX - mob_1.waypointsX[k4] > -l5) mob_1.currentX = mob_1.waypointsX[k4]; if (mob_1.currentY < mob_1.waypointsY[k4]) { mob_1.currentY += l5; mob_1.stepCount++; if (i3 == -1) i3 = 4; else if (i3 == 2) i3 = 3; else i3 = 5; } else if (mob_1.currentY > mob_1.waypointsY[k4]) { mob_1.currentY -= l5; mob_1.stepCount++; if (i3 == -1) i3 = 0; else if (i3 == 2) i3 = 1; else i3 = 7; } if (mob_1.currentY - mob_1.waypointsY[k4] < l5 && mob_1.currentY - mob_1.waypointsY[k4] > -l5) mob_1.currentY = mob_1.waypointsY[k4]; } if (i3 != -1) mob_1.currentSprite = i3; if (mob_1.currentX == mob_1.waypointsX[k4] && mob_1.currentY == mob_1.waypointsY[k4]) mob_1.waypointEndSprite = (k4 + 1) % 10; } else { mob_1.currentSprite = mob_1.nextSprite; if (mob_1.type == 43) mob_1.stepCount++; } if (mob_1.lastMessageTimeout > 0) mob_1.lastMessageTimeout--; if (mob_1.anInt163 > 0) mob_1.anInt163--; if (mob_1.combatTimer > 0) mob_1.combatTimer--; } if (mouseOverMenu != 2) { if (GameImage.anInt346 > 0) anInt658++; if (GameImage.anInt347 > 0) anInt658 = 0; GameImage.anInt346 = 0; GameImage.anInt347 = 0; } for (int l = 0; l < playerCount; l++) { Mob mob_2 = playerArray[l]; if (mob_2.anInt176 > 0) mob_2.anInt176--; } if (cameraAutoAngleDebug) { if (lastAutoCameraRotatePlayerX - ourPlayer.currentX < -500 || lastAutoCameraRotatePlayerX - ourPlayer.currentX > 500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY < -500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY > 500) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } } else { if (lastAutoCameraRotatePlayerX - ourPlayer.currentX < -500 || lastAutoCameraRotatePlayerX - ourPlayer.currentX > 500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY < -500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY > 500) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } if (lastAutoCameraRotatePlayerX != ourPlayer.currentX) lastAutoCameraRotatePlayerX += (ourPlayer.currentX - lastAutoCameraRotatePlayerX) / (16 + (cameraHeight - 500) / 15); if (lastAutoCameraRotatePlayerY != ourPlayer.currentY) lastAutoCameraRotatePlayerY += (ourPlayer.currentY - lastAutoCameraRotatePlayerY) / (16 + (cameraHeight - 500) / 15); if (configAutoCameraAngle) { int k1 = cameraAutoAngle * 32; int j3 = k1 - cameraRotation; byte byte0 = 1; if (j3 != 0) { cameraRotationBaseAddition++; if (j3 > 128) { byte0 = -1; j3 = 256 - j3; } else if (j3 > 0) byte0 = 1; else if (j3 < -128) { byte0 = 1; j3 = 256 + j3; } else if (j3 < 0) { byte0 = -1; j3 = -j3; } cameraRotation += ((cameraRotationBaseAddition * j3 + 255) / 256) * byte0; cameraRotation &= 0xff; } else { cameraRotationBaseAddition = 0; } } } if (anInt658 > 20) { aBoolean767 = false; anInt658 = 0; } if (sleeping) { ignoreNext = true; if (super.enteredText.length() > 0) { super.streamClass.createPacket(200); super.streamClass.addString(super.enteredText); if (!aBoolean767) { super.streamClass.addByte(0); aBoolean767 = true; } super.streamClass.formatPacket(); super.inputText = ""; super.enteredText = ""; gameMenu.updateText(chatHandle, ""); sleepMessage = "Please wait..."; } // PLZ CAN I HAS NEW SLEEP EKWAZION? if (super.lastMouseDownButton != 0 && super.mouseX >= ((windowWidth / 2) - 100) && super.mouseX < ((windowWidth / 2) + 100) && super.mouseY > 280 && super.mouseY < 310) { super.streamClass.createPacket(200); super.streamClass.addString("-null-"); if (!aBoolean767) { super.streamClass.addByte(0); aBoolean767 = true; } super.streamClass.formatPacket(); super.inputText = ""; super.enteredText = ""; sleepMessage = " Please wait..."; } super.lastMouseDownButton = 0; return; } if (super.mouseY > windowHeight - 4) { if (super.mouseX > 15 + xAddition && super.mouseX < 96 + xAddition && super.lastMouseDownButton == 1) messagesTab = 0; if (super.mouseX > 110 + xAddition && super.mouseX < 194 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 1; gameMenu.anIntArray187[messagesHandleType2] = 0xf423f; } if (super.mouseX > 215 + xAddition && super.mouseX < 295 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 2; gameMenu.anIntArray187[messagesHandleType5] = 0xf423f; } if (super.mouseX > 315 + xAddition && super.mouseX < 395 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 3; gameMenu.anIntArray187[messagesHandleType6] = 0xf423f; } if (super.mouseX > 417 + xAddition && super.mouseX < 497 + xAddition && super.lastMouseDownButton == 1) { showAbuseWindow = 1; abuseSelectedType = 0; super.inputText = ""; super.enteredText = ""; } super.lastMouseDownButton = 0; super.mouseDownButton = 0; } gameMenu.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); if (messagesTab > 0 && super.mouseX >= 494 && super.mouseY >= windowHeight - 66) super.lastMouseDownButton = 0; if (gameMenu.hasActivated(chatHandle)) { String s = gameMenu.getText(chatHandle); gameMenu.updateText(chatHandle, ""); if (ignoreNext) { ignoreNext = false; return; } if (s.startsWith("::")) { s = s.substring(2); if (!handleCommand(s) && !sleeping && !ignoreNext) { sendChatString(s); if (messages.size() == 0 || !messages.get(messages.size() - 1) .equalsIgnoreCase("::" + s)) { messages.add("::" + s); currentChat = messages.size(); } else if (messages.get(messages.size() - 1) .equalsIgnoreCase("::" + s)) { currentChat = messages.size(); } } } else if (!sleeping && !ignoreNext) { byte[] chatMessage = DataConversions.stringToByteArray(s); sendChatMessage(chatMessage, chatMessage.length); s = DataConversions.byteToString(chatMessage, 0, chatMessage.length).trim(); if (s.toLowerCase().trim().startsWith(";;")) return; if (messages.size() == 0 || !messages.get(messages.size() - 1).equalsIgnoreCase( s)) { messages.add(s); currentChat = messages.size(); } else if (messages.get(messages.size() - 1) .equalsIgnoreCase(s)) { currentChat = messages.size(); } ourPlayer.lastMessageTimeout = 150; ourPlayer.lastMessage = s; displayMessage(ourPlayer.name + ": " + s, 2, ourPlayer.admin); } } if (messagesTab == 0) { for (int l1 = 0; l1 < messagesTimeout.length; l1++) if (messagesTimeout[l1] > 0) messagesTimeout[l1]--; } if (playerAliveTimeout != 0) super.lastMouseDownButton = 0; if (showTradeWindow || showDuelWindow) { if (super.mouseDownButton != 0) mouseDownTime++; else mouseDownTime = 0; if (mouseDownTime > 500) itemIncrement += 100000; else if (mouseDownTime > 350) itemIncrement += 10000; else if (mouseDownTime > 250) itemIncrement += 1000; else if (mouseDownTime > 150) itemIncrement += 100; else if (mouseDownTime > 100) itemIncrement += 10; else if (mouseDownTime > 50) itemIncrement++; else if (mouseDownTime > 20 && (mouseDownTime & 5) == 0) itemIncrement++; } else { mouseDownTime = 0; itemIncrement = 0; } if (super.lastMouseDownButton == 1) mouseButtonClick = 1; else if (super.lastMouseDownButton == 2) mouseButtonClick = 2; gameCamera.updateMouseCoords(super.mouseX, super.mouseY); super.lastMouseDownButton = 0; if (configAutoCameraAngle) { if (cameraRotationBaseAddition == 0 || cameraAutoAngleDebug) { if (super.keyLeftDown) { cameraAutoAngle = cameraAutoAngle + 1 & 7; super.keyLeftDown = false; if (!zoomCamera) { if ((cameraAutoAngle & 1) == 0) cameraAutoAngle = cameraAutoAngle + 1 & 7; for (int i2 = 0; i2 < 8; i2++) { if (enginePlayerVisible(cameraAutoAngle)) break; cameraAutoAngle = cameraAutoAngle + 1 & 7; } } } if (super.keyRightDown) { cameraAutoAngle = cameraAutoAngle + 7 & 7; super.keyRightDown = false; if (!zoomCamera) { if ((cameraAutoAngle & 1) == 0) cameraAutoAngle = cameraAutoAngle + 7 & 7; for (int j2 = 0; j2 < 8; j2++) { if (enginePlayerVisible(cameraAutoAngle)) break; cameraAutoAngle = cameraAutoAngle + 7 & 7; } } } } } else try { if (super.keyLeftDown) cameraRotation = cameraRotation + 2 & 0xff; else if (super.keyRightDown) cameraRotation = cameraRotation - 2 & 0xff; if (super.home) { cameraHeight = 750; cameraVertical = 920; fogVar = 0; } else if (super.pageUp) { if (cameraHeight > 400) cameraHeight -= 6; } else if (super.pageDown) { if (cameraHeight < 3000) cameraHeight += 6; } if (controlDown && fog) { if (minus) fogVar += 20; else if (plus) fogVar -= 20; } } catch (Exception e) { e.printStackTrace(); System.out.println("Camera error: " + e); cameraHeight = 750; cameraVertical = 920; fogVar = 0; } if (actionPictureType > 0) actionPictureType--; else if (actionPictureType < 0) actionPictureType++; gameCamera.method301(17); modelUpdatingTimer++; if (modelUpdatingTimer > 5) { modelUpdatingTimer = 0; modelFireLightningSpellNumber = (modelFireLightningSpellNumber + 1) % 3; modelTorchNumber = (modelTorchNumber + 1) % 4; modelClawSpellNumber = (modelClawSpellNumber + 1) % 5; } for (int k2 = 0; k2 < objectCount; k2++) { int l3 = objectX[k2]; int l4 = objectY[k2]; if (l3 >= 0 && l4 >= 0 && l3 < 96 && l4 < 96 && objectType[k2] == 74) objectModelArray[k2].method188(1, 0, 0); } for (int i4 = 0; i4 < anInt892; i4++) { anIntArray923[i4]++; if (anIntArray923[i4] > 50) { anInt892--; for (int i5 = i4; i5 < anInt892; i5++) { anIntArray944[i5] = anIntArray944[i5 + 1]; anIntArray757[i5] = anIntArray757[i5 + 1]; anIntArray923[i5] = anIntArray923[i5 + 1]; anIntArray782[i5] = anIntArray782[i5 + 1]; } } } }// command == 11 public static HashMap<String, File> ctfsounds = new HashMap<String, File>(); private final void loadSounds() { try { drawDownloadProgress("Unpacking Sound effects", 90, false); sounds = load("sounds1.mem"); audioReader = new AudioReader(); return; } catch (Throwable throwable) { System.out.println("Unable to init sounds:" + throwable); } } private final void drawCombatStyleWindow() { byte byte0 = 7; byte byte1 = 15; char c = '\257'; if (mouseButtonClick != 0) { for (int i = 0; i < 5; i++) { if (i <= 0 || super.mouseX <= byte0 || super.mouseX >= byte0 + c || super.mouseY <= byte1 + i * 20 || super.mouseY >= byte1 + i * 20 + 20) continue; combatStyle = i - 1; mouseButtonClick = 0; super.streamClass.createPacket(42); super.streamClass.addByte(combatStyle); super.streamClass.formatPacket(); break; } } for (int j = 0; j < 5; j++) { if (j == combatStyle + 1) gameGraphics.drawBoxAlpha(byte0, byte1 + j * 20, c, 20, GameImage.convertRGBToLong(255, 0, 0), 128); else gameGraphics.drawBoxAlpha(byte0, byte1 + j * 20, c, 20, GameImage.convertRGBToLong(190, 190, 190), 128); gameGraphics.drawLineX(byte0, byte1 + j * 20, c, 0); gameGraphics.drawLineX(byte0, byte1 + j * 20 + 20, c, 0); } gameGraphics.drawText("Select combat style", byte0 + c / 2, byte1 + 16, 3, 0xffffff); gameGraphics.drawText("Controlled (+1 of each)", byte0 + c / 2, byte1 + 36, 3, 0); gameGraphics.drawText("Aggressive (+3 strength)", byte0 + c / 2, byte1 + 56, 3, 0); gameGraphics.drawText("Accurate (+3 attack)", byte0 + c / 2, byte1 + 76, 3, 0); gameGraphics.drawText("Defensive (+3 defense)", byte0 + c / 2, byte1 + 96, 3, 0); } private final void drawDuelConfirmWindow() { int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 16, 192); int i = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 16, 468, 246, i, 160); gameGraphics.drawText("Please confirm your duel with @yel@" + DataOperations.longToString(duelOpponentNameLong), byte0 + 234, byte1 + 12, 1, 0xffffff); gameGraphics.drawText("Your stake:", byte0 + 117, byte1 + 30, 1, 0xffff00); for (int j = 0; j < duelConfirmMyItemCount; j++) { String s = EntityHandler.getItemDef(duelConfirmMyItems[j]) .getName(); if (EntityHandler.getItemDef(duelConfirmMyItems[j]).isStackable()) s = s + " x " + method74(duelConfirmMyItemsCount[j]); gameGraphics.drawText(s, byte0 + 117, byte1 + 42 + j * 12, 1, 0xffffff); } if (duelConfirmMyItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 117, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("Your opponent's stake:", byte0 + 351, byte1 + 30, 1, 0xffff00); for (int k = 0; k < duelConfirmOpponentItemCount; k++) { String s1 = EntityHandler.getItemDef(duelConfirmOpponentItems[k]) .getName(); if (EntityHandler.getItemDef(duelConfirmOpponentItems[k]) .isStackable()) s1 = s1 + " x " + method74(duelConfirmOpponentItemsCount[k]); gameGraphics.drawText(s1, byte0 + 351, byte1 + 42 + k * 12, 1, 0xffffff); } if (duelConfirmOpponentItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 351, byte1 + 42, 1, 0xffffff); if (duelCantRetreat == 0) gameGraphics.drawText("You can retreat from this duel", byte0 + 234, byte1 + 180, 1, 65280); else gameGraphics.drawText("No retreat is possible!", byte0 + 234, byte1 + 180, 1, 0xff0000); if (duelUseMagic == 0) gameGraphics.drawText("Magic may be used", byte0 + 234, byte1 + 192, 1, 65280); else gameGraphics.drawText("Magic cannot be used", byte0 + 234, byte1 + 192, 1, 0xff0000); if (duelUsePrayer == 0) gameGraphics.drawText("Prayer may be used", byte0 + 234, byte1 + 204, 1, 65280); else gameGraphics.drawText("Prayer cannot be used", byte0 + 234, byte1 + 204, 1, 0xff0000); if (duelUseWeapons == 0) gameGraphics.drawText("Weapons may be used", byte0 + 234, byte1 + 216, 1, 65280); else gameGraphics.drawText("Weapons cannot be used", byte0 + 234, byte1 + 216, 1, 0xff0000); gameGraphics.drawText( "If you are sure click 'Accept' to begin the duel", byte0 + 234, byte1 + 230, 1, 0xffffff); if (!duelWeAccept) { gameGraphics.drawPicture((byte0 + 118) - 35, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture((byte0 + 352) - 35, byte1 + 238, SPRITE_MEDIA_START + 26); } else { gameGraphics.drawText("Waiting for other player...", byte0 + 234, byte1 + 250, 1, 0xffff00); } if (mouseButtonClick == 1) { if (super.mouseX < byte0 || super.mouseY < byte1 || super.mouseX > byte0 + 468 || super.mouseY > byte1 + 262) { showDuelConfirmWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 118) - 35 && super.mouseX <= byte0 + 118 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { duelWeAccept = true; super.streamClass.createPacket(87); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 352) - 35 && super.mouseX <= byte0 + 353 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { showDuelConfirmWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } mouseButtonClick = 0; } } private final void updateBankItems() { bankItemCount = newBankItemCount; for (int i = 0; i < newBankItemCount; i++) { bankItems[i] = newBankItems[i]; bankItemsCount[i] = newBankItemsCount[i]; } for (int j = 0; j < inventoryCount; j++) { if (bankItemCount >= bankItemsMax) break; int k = getInventoryItems()[j]; boolean flag = false; for (int l = 0; l < bankItemCount; l++) { if (bankItems[l] != k) continue; flag = true; break; } if (!flag) { bankItems[bankItemCount] = k; bankItemsCount[bankItemCount] = 0; bankItemCount++; } } } private final void makeDPSMenu() { drawPointsScreen = new Menu(gameGraphics, 100); final Menu dPS = drawPointsScreen; dPS.drawText(256, 10, "Please select your points", 4, true); int i = 140; int j = 34; i += 116; j -= 10; byte byte0 = 54; j += 145; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Str", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); strDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); strUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); dPS.method157(i + byte0, j, 53, 41); dPS.drawText(i + byte0, j - 8, "Atk", 1, true); dPS.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); atkDownButton = dPS.makeButton((i + byte0) - 40, j, 20, 20); dPS.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); atkUpButton = dPS.makeButton(i + byte0 + 40, j, 20, 20); j += 50; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Def", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); defDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); defUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); dPS.method157(i + byte0, j, 53, 41); dPS.drawText(i + byte0, j - 8, "Range", 1, true); dPS.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); rangeDownButton = dPS.makeButton((i + byte0) - 40, j, 20, 20); dPS.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); rangeUpButton = dPS.makeButton(i + byte0 + 40, j, 20, 20); j += 50; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Magic", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); magDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); magUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); j += 82; j -= 35; dPS.drawBox(i, j, 200, 30); dPS.drawText(i, j, "Accept", 4, false); dPSAcceptButton = dPS.makeButton(i, j, 200, 30); } private final void makeCharacterDesignMenu() { characterDesignMenu = new Menu(gameGraphics, 100); characterDesignMenu.drawText(256, 10, "Please design Your Character", 4, true); int i = 140; int j = 34; i += 116; j -= 10; characterDesignMenu.drawText(i - 55, j + 110, "Front", 3, true); characterDesignMenu.drawText(i, j + 110, "Side", 3, true); characterDesignMenu.drawText(i + 55, j + 110, "Back", 3, true); byte byte0 = 54; j += 145; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j - 8, "Head", 1, true); characterDesignMenu.drawText(i - byte0, j + 8, "Type", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignHeadButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignHeadButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Hair", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignHairColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignHairColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 50; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j, "Gender", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignGenderButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignGenderButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Top", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignTopColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignTopColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 50; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j - 8, "Skin", 1, true); characterDesignMenu.drawText(i - byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignSkinColourButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignSkinColourButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Bottom", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignBottomColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignBottomColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 82; j -= 35; characterDesignMenu.drawBox(i, j, 200, 30); characterDesignMenu.drawText(i, j, "Accept", 4, false); characterDesignAcceptButton = characterDesignMenu.makeButton(i, j, 200, 30); } private final void drawAbuseWindow2() { if (super.enteredText.length() > 0) { String s = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; if (s.length() > 0) { long l = DataOperations.stringLength12ToLong(s); super.streamClass.createPacket(7); super.streamClass.addTwo4ByteInts(l); super.streamClass.addByte(abuseSelectedType); super.streamClass.formatPacket(); } showAbuseWindow = 0; return; } gameGraphics.drawBox(56 + xAddition, 130 + yAddition, 400, 100, 0); gameGraphics.drawBoxEdge(56 + xAddition, 130 + yAddition, 400, 100, 0xffffff); int i = 160 + yAddition; gameGraphics.drawText( "Now type the name of the offending player, and press enter", 256 + xAddition, i, 1, 0xffff00); i += 18; gameGraphics.drawText("Name: " + super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); i = 222 + yAddition; int j = 0xffffff; if (super.mouseX > 196 + xAddition && super.mouseX < 316 + xAddition && super.mouseY > i - 13 && super.mouseY < i + 2) { j = 0xffff00; if (mouseButtonClick == 1) { mouseButtonClick = 0; showAbuseWindow = 0; } } gameGraphics.drawText("Click here to cancel", 256 + xAddition, i, 1, j); if (mouseButtonClick == 1 && (super.mouseX < 56 + xAddition || super.mouseX > 456 + xAddition || super.mouseY < 130 + yAddition || super.mouseY > 230 + yAddition)) { mouseButtonClick = 0; showAbuseWindow = 0; } } public final void displayMessage(String message, int type, int status) { if (type == 2 || type == 4 || type == 6) { for (; message.length() > 5 && message.charAt(0) == '@' && message.charAt(4) == '@'; message = message.substring(5)) ; } if (message.startsWith("%", 0)) { message = message.substring(1); status = 4; } if (message.startsWith("&", 0)) { message = message.substring(1); status = 33; } // if (command == 131) { message = message.replaceAll("\\#pmd\\#", ""); message = message.replaceAll("\\#mod\\#", ""); message = message.replaceAll("\\#adm\\#", ""); if (type == 2) message = "@yel@" + message; if (type == 3 || type == 4) message = "@whi@" + message; if (type == 6) message = "@cya@" + message; if (status == 1) message = "#pmd#" + message; if (status == 2) message = "#mod#" + message; if (status == 3) message = "#adm#" + message; if (status == 4) { message = "#pmd#" + message; MessageQueue.getQueue(); MessageQueue.addMessage(new Message(message)); gameMenu.addString(messagesHandleType6, message, false); return; } // MessageQueue if (status == 33) { MessageQueue.getQueue(); MessageQueue.addMessage(new Message(message, true)); gameMenu.addString(messagesHandleType6, message, false); return; } if (messagesTab != 0) { if (type == 4 || type == 3) anInt952 = 200; if (type == 2 && messagesTab != 1) anInt953 = 200; if (type == 5 && messagesTab != 2) anInt954 = 200; if (type == 6 && messagesTab != 3) anInt955 = 200; if (type == 3 && messagesTab != 0) messagesTab = 0; if (type == 6 && messagesTab != 3 && messagesTab != 0) messagesTab = 0; } for (int k = messagesArray.length - 1; k > 0; k--) { messagesArray[k] = messagesArray[k - 1]; messagesTimeout[k] = messagesTimeout[k - 1]; } messagesArray[0] = message; /** * Change this to add longer chat msg time */ messagesTimeout[0] = 300; if (type == 2) if (gameMenu.anIntArray187[messagesHandleType2] == gameMenu.menuListTextCount[messagesHandleType2] - 4) gameMenu.addString(messagesHandleType2, message, true); else gameMenu.addString(messagesHandleType2, message, false); if (type == 5) if (gameMenu.anIntArray187[messagesHandleType5] == gameMenu.menuListTextCount[messagesHandleType5] - 4) gameMenu.addString(messagesHandleType5, message, true); else gameMenu.addString(messagesHandleType5, message, false); if (type == 6) { if (gameMenu.anIntArray187[messagesHandleType6] == gameMenu.menuListTextCount[messagesHandleType6] - 4) { gameMenu.addString(messagesHandleType6, message, true); return; } gameMenu.addString(messagesHandleType6, message, false); } } protected final void logoutAndStop() { sendLogoutPacket(); garbageCollect(); if (audioReader != null) { audioReader.stopAudio(); } } private final void method98(int i, String s) { int j = objectX[i]; int k = objectY[i]; int l = j - ourPlayer.currentX / 128; int i1 = k - ourPlayer.currentY / 128; byte byte0 = 7; if (j >= 0 && k >= 0 && j < 96 && k < 96 && l > -byte0 && l < byte0 && i1 > -byte0 && i1 < byte0) { try { gameCamera.removeModel(objectModelArray[i]); int j1 = EntityHandler.storeModel(s); Model model = gameDataModels[j1].method203(); gameCamera.addModel(model); model.method184(true, 48, 48, -50, -10, -50); model.method205(objectModelArray[i]); model.anInt257 = i; objectModelArray[i] = model; } catch (Exception e) { // e.printStackTrace(); } } } protected final void resetVars() { systemUpdate = 0; combatStyle = 0; logoutTimeout = 0; loginScreenNumber = 0; loggedIn = 1; flagged = 0; resetPrivateMessageStrings(); gameGraphics.method211(); gameGraphics.drawImage(aGraphics936, 0, 0); for (int i = 0; i < objectCount; i++) { gameCamera.removeModel(objectModelArray[i]); engineHandle.updateObject(objectX[i], objectY[i], objectType[i], objectID[i]); } for (int j = 0; j < doorCount; j++) { gameCamera.removeModel(doorModel[j]); engineHandle.updateDoor(doorX[j], doorY[j], doorDirection[j], doorType[j]); } objectCount = 0; doorCount = 0; groundItemCount = 0; playerCount = 0; for (int k = 0; k < mobArray.length; k++) mobArray[k] = null; for (int l = 0; l < playerArray.length; l++) playerArray[l] = null; npcCount = 0; for (int i1 = 0; i1 < npcRecordArray.length; i1++) npcRecordArray[i1] = null; for (int j1 = 0; j1 < npcArray.length; j1++) npcArray[j1] = null; for (int k1 = 0; k1 < prayerOn.length; k1++) prayerOn[k1] = false; mouseButtonClick = 0; super.lastMouseDownButton = 0; super.mouseDownButton = 0; showShop = false; showBank = false; super.friendsCount = 0; } private final void drawTradeWindow() { if (mouseButtonClick != 0 && itemIncrement == 0) itemIncrement = 1; if (itemIncrement > 0) { int i = super.mouseX - 22 - xAddition; int j = super.mouseY - 36 - yAddition; if (i >= 0 && j >= 0 && i < 468 && j < 262) { if (i > 216 && j > 30 && i < 462 && j < 235) { int k = (i - 217) / 49 + ((j - 31) / 34) * 5; if (k >= 0 && k < inventoryCount) { boolean flag = false; int l1 = 0; int k2 = getInventoryItems()[k]; for (int k3 = 0; k3 < tradeMyItemCount; k3++) if (tradeMyItems[k3] == k2) if (EntityHandler.getItemDef(k2).isStackable()) { for (int i4 = 0; i4 < itemIncrement; i4++) { if (tradeMyItemsCount[k3] < inventoryItemsCount[k]) tradeMyItemsCount[k3]++; flag = true; } } else { l1++; } if (inventoryCount(k2) <= l1) flag = true; if (!flag && tradeMyItemCount < 12) { tradeMyItems[tradeMyItemCount] = k2; tradeMyItemsCount[tradeMyItemCount] = 1; tradeMyItemCount++; flag = true; } if (flag) { super.streamClass.createPacket(70); super.streamClass.addByte(tradeMyItemCount); for (int j4 = 0; j4 < tradeMyItemCount; j4++) { super.streamClass.add2ByteInt(tradeMyItems[j4]); super.streamClass .add4ByteInt(tradeMyItemsCount[j4]); } super.streamClass.formatPacket(); tradeOtherAccepted = false; tradeWeAccepted = false; } } } if (i > 8 && j > 30 && i < 205 && j < 133) { int l = (i - 9) / 49 + ((j - 31) / 34) * 4; if (l >= 0 && l < tradeMyItemCount) { int j1 = tradeMyItems[l]; for (int i2 = 0; i2 < itemIncrement; i2++) { if (EntityHandler.getItemDef(j1).isStackable() && tradeMyItemsCount[l] > 1) { tradeMyItemsCount[l]--; continue; }// shopItem tradeMyItemCount--; mouseDownTime = 0; for (int l2 = l; l2 < tradeMyItemCount; l2++) { tradeMyItems[l2] = tradeMyItems[l2 + 1]; tradeMyItemsCount[l2] = tradeMyItemsCount[l2 + 1]; } break; } super.streamClass.createPacket(70); super.streamClass.addByte(tradeMyItemCount); for (int i3 = 0; i3 < tradeMyItemCount; i3++) { super.streamClass.add2ByteInt(tradeMyItems[i3]); super.streamClass .add4ByteInt(tradeMyItemsCount[i3]); } super.streamClass.formatPacket(); tradeOtherAccepted = false; tradeWeAccepted = false; } } if (i >= 217 && j >= 238 && i <= 286 && j <= 259) { tradeWeAccepted = true; super.streamClass.createPacket(211); super.streamClass.formatPacket(); } if (i >= 394 && j >= 238 && i < 463 && j < 259) { showTradeWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } } else if (mouseButtonClick != 0) { showTradeWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } mouseButtonClick = 0; itemIncrement = 0; } if (!showTradeWindow) return; int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 12, 192); int i1 = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 468, 18, i1, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 30, 8, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 205, byte1 + 30, 11, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 462, byte1 + 30, 6, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 133, 197, 22, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 258, 197, 20, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 235, 246, 43, i1, 160); int k1 = 0xd0d0d0; gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 30, 197, 103, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 155, 197, 103, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 30, 246, 205, k1, 160); for (int j2 = 0; j2 < 4; j2++) gameGraphics.drawLineX(byte0 + 8, byte1 + 30 + j2 * 34, 197, 0); for (int j3 = 0; j3 < 4; j3++) gameGraphics.drawLineX(byte0 + 8, byte1 + 155 + j3 * 34, 197, 0); for (int l3 = 0; l3 < 7; l3++) gameGraphics.drawLineX(byte0 + 216, byte1 + 30 + l3 * 34, 246, 0); for (int k4 = 0; k4 < 6; k4++) { if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 30, 103, 0); if (k4 < 5) gameGraphics .drawLineY(byte0 + 8 + k4 * 49, byte1 + 155, 103, 0); gameGraphics.drawLineY(byte0 + 216 + k4 * 49, byte1 + 30, 205, 0); } gameGraphics.drawString("Trading with: " + tradeOtherPlayerName, byte0 + 1, byte1 + 10, 1, 0xffffff); gameGraphics.drawString("Your Offer", byte0 + 9, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("Opponent's Offer", byte0 + 9, byte1 + 152, 4, 0xffffff); gameGraphics.drawString("Your Inventory", byte0 + 216, byte1 + 27, 4, 0xffffff); if (!tradeWeAccepted) gameGraphics.drawPicture(byte0 + 217, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture(byte0 + 394, byte1 + 238, SPRITE_MEDIA_START + 26); if (tradeOtherAccepted) { gameGraphics.drawText("Other player", byte0 + 341, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("has accepted", byte0 + 341, byte1 + 256, 1, 0xffffff); } if (tradeWeAccepted) { gameGraphics.drawText("Waiting for", byte0 + 217 + 35, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("other player", byte0 + 217 + 35, byte1 + 256, 1, 0xffffff); } for (int l4 = 0; l4 < inventoryCount; l4++) { int i5 = 217 + byte0 + (l4 % 5) * 49; int k5 = 31 + byte1 + (l4 / 5) * 34; gameGraphics.spriteClip4(i5, k5, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(getInventoryItems()[l4]) .getSprite(), EntityHandler.getItemDef(getInventoryItems()[l4]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(getInventoryItems()[l4]).isStackable()) gameGraphics.drawString( String.valueOf(inventoryItemsCount[l4]), i5 + 1, k5 + 10, 1, 0xffff00); } for (int j5 = 0; j5 < tradeMyItemCount; j5++) { int l5 = 9 + byte0 + (j5 % 4) * 49; int j6 = 31 + byte1 + (j5 / 4) * 34; gameGraphics .spriteClip4(l5, j6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(tradeMyItems[j5]) .getSprite(), EntityHandler.getItemDef(tradeMyItems[j5]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(tradeMyItems[j5]).isStackable()) gameGraphics.drawString(String.valueOf(tradeMyItemsCount[j5]), l5 + 1, j6 + 10, 1, 0xffff00); if (super.mouseX > l5 && super.mouseX < l5 + 48 && super.mouseY > j6 && super.mouseY < j6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(tradeMyItems[j5]).getName() + ": @whi@" + EntityHandler.getItemDef(tradeMyItems[j5]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } for (int i6 = 0; i6 < tradeOtherItemCount; i6++) { int k6 = 9 + byte0 + (i6 % 4) * 49; int l6 = 156 + byte1 + (i6 / 4) * 34; gameGraphics.spriteClip4( k6, l6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(tradeOtherItems[i6]) .getSprite(), EntityHandler.getItemDef(tradeOtherItems[i6]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(tradeOtherItems[i6]).isStackable()) gameGraphics.drawString( String.valueOf(tradeOtherItemsCount[i6]), k6 + 1, l6 + 10, 1, 0xffff00); if (super.mouseX > k6 && super.mouseX < k6 + 48 && super.mouseY > l6 && super.mouseY < l6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(tradeOtherItems[i6]).getName() + ": @whi@" + EntityHandler.getItemDef(tradeOtherItems[i6]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } } private final boolean enginePlayerVisible(int i) { int j = ourPlayer.currentX / 128; int k = ourPlayer.currentY / 128; for (int l = 2; l >= 1; l--) { if (i == 1 && ((engineHandle.walkableValue[j][k - l] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k - l] & 0x80) == 128)) return false; if (i == 3 && ((engineHandle.walkableValue[j][k + l] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k + l] & 0x80) == 128)) return false; if (i == 5 && ((engineHandle.walkableValue[j][k + l] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k + l] & 0x80) == 128)) return false; if (i == 7 && ((engineHandle.walkableValue[j][k - l] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k - l] & 0x80) == 128)) return false; if (i == 0 && (engineHandle.walkableValue[j][k - l] & 0x80) == 128) return false; if (i == 2 && (engineHandle.walkableValue[j - l][k] & 0x80) == 128) return false; if (i == 4 && (engineHandle.walkableValue[j][k + l] & 0x80) == 128) return false; if (i == 6 && (engineHandle.walkableValue[j + l][k] & 0x80) == 128) return false; } return true; } private Mob getLastPlayer(int serverIndex) { for (int i1 = 0; i1 < lastPlayerCount; i1++) { if (lastPlayerArray[i1].serverIndex == serverIndex) { return lastPlayerArray[i1]; } } return null; } private Mob getLastNpc(int serverIndex) { for (int i1 = 0; i1 < lastNpcCount; i1++) { if (lastNpcArray[i1].serverIndex == serverIndex) { return lastNpcArray[i1]; } } return null; } protected final void handleIncomingPacket(int command, int length, byte data[]) { try { if (command == 254) { int bar = DataOperations.getUnsigned4Bytes(data, 1); // System.out.println(bar); if (bar == -1) { smithingscreen.isVisible = false; } else { SmithingScreen.changeItems(smithingscreen, bar); smithingscreen.isVisible = true; } } if (command == 231) { // PS = DataOperations.getUnsigned4Bytes(data, 1); return; } if (command == 233) { questPoints = DataOperations.getUnsignedByte(data[1]); int k = DataOperations.getUnsignedByte(data[2]); int r = 3; newQuestNames = new String[k]; questStage = new byte[k]; for (int i = 0; i < k; i++) { int uid = DataOperations.getUnsignedByte(data[r]); r++; newQuestNames[i] = questName[uid]; questStage[i] = (byte) DataOperations .getUnsignedByte(data[r]); // System.out.println(newQuestNames[i] + " " + // questStage[i]); r++; } }// command == 177 if (command == 110) { int i = 1; serverStartTime = DataOperations.getUnsigned8Bytes(data, i); i += 8; serverLocation = new String(data, i, length - i); return; } if (command == 145) { if (!hasWorldInfo) { return; } loading = true; lastPlayerCount = playerCount; for (int k = 0; k < lastPlayerCount; k++) lastPlayerArray[k] = playerArray[k]; int currentOffset = 8; setSectionX(DataOperations.getIntFromByteArray(data, currentOffset, 11)); currentOffset += 11; setSectionY(DataOperations.getIntFromByteArray(data, currentOffset, 13)); currentOffset += 13; int mobSprite = DataOperations.getIntFromByteArray(data, currentOffset, 4); currentOffset += 4; boolean sectionLoaded = loadSection(getSectionX(), getSectionY()); setSectionX(getSectionX() - getAreaX()); setSectionY(getSectionY() - getAreaY()); int mapEnterX = getSectionX() * magicLoc + 64; int mapEnterY = getSectionY() * magicLoc + 64; if (sectionLoaded) { ourPlayer.waypointCurrent = 0; ourPlayer.waypointEndSprite = 0; ourPlayer.currentX = ourPlayer.waypointsX[0] = mapEnterX; ourPlayer.currentY = ourPlayer.waypointsY[0] = mapEnterY; } playerCount = 0; ourPlayer = makePlayer(serverIndex, mapEnterX, mapEnterY, mobSprite); int newPlayerCount = DataOperations.getIntFromByteArray(data, currentOffset, 8); currentOffset += 8; for (int currentNewPlayer = 0; currentNewPlayer < newPlayerCount; currentNewPlayer++) { Mob lastMob = getLastPlayer(DataOperations .getIntFromByteArray(data, currentOffset, 16)); currentOffset += 16; int nextPlayer = DataOperations.getIntFromByteArray(data, currentOffset, 1); // 1 currentOffset++; if (nextPlayer != 0) { int waypointsLeft = DataOperations.getIntFromByteArray( data, currentOffset, 1); // 2 currentOffset++; if (waypointsLeft == 0) { int currentNextSprite = DataOperations .getIntFromByteArray(data, currentOffset, 3); // 3 currentOffset += 3; int currentWaypoint = lastMob.waypointCurrent; int newWaypointX = lastMob.waypointsX[currentWaypoint]; int newWaypointY = lastMob.waypointsY[currentWaypoint]; if (currentNextSprite == 2 || currentNextSprite == 1 || currentNextSprite == 3) newWaypointX += magicLoc; if (currentNextSprite == 6 || currentNextSprite == 5 || currentNextSprite == 7) newWaypointX -= magicLoc; if (currentNextSprite == 4 || currentNextSprite == 3 || currentNextSprite == 5) newWaypointY += magicLoc; if (currentNextSprite == 0 || currentNextSprite == 1 || currentNextSprite == 7) newWaypointY -= magicLoc; lastMob.nextSprite = currentNextSprite; lastMob.waypointCurrent = currentWaypoint = (currentWaypoint + 1) % 10; lastMob.waypointsX[currentWaypoint] = newWaypointX; lastMob.waypointsY[currentWaypoint] = newWaypointY; } else { int needsNextSprite = DataOperations .getIntFromByteArray(data, currentOffset, 4); currentOffset += 4; if ((needsNextSprite & 0xc) == 12) { continue; } lastMob.nextSprite = needsNextSprite; } } playerArray[playerCount++] = lastMob; } int mobCount = 0; while (currentOffset + 24 < length * 8) { int mobIndex = DataOperations.getIntFromByteArray(data, currentOffset, 16); currentOffset += 16; int areaMobX = DataOperations.getIntFromByteArray(data, currentOffset, 5); currentOffset += 5; if (areaMobX > 15) areaMobX -= 32; int areaMobY = DataOperations.getIntFromByteArray(data, currentOffset, 5); currentOffset += 5; if (areaMobY > 15) areaMobY -= 32; int mobArrayMobID = DataOperations.getIntFromByteArray( data, currentOffset, 4); currentOffset += 4; int addIndex = DataOperations.getIntFromByteArray(data, currentOffset, 1); currentOffset++; int mobX = (getSectionX() + areaMobX) * magicLoc + 64; int mobY = (getSectionY() + areaMobY) * magicLoc + 64; makePlayer(mobIndex, mobX, mobY, mobArrayMobID); if (addIndex == 0) mobArrayIndexes[mobCount++] = mobIndex; } if (mobCount > 0) { super.streamClass.createPacket(83); super.streamClass.add2ByteInt(mobCount); for (int currentMob = 0; currentMob < mobCount; currentMob++) { Mob dummyMob = mobArray[mobArrayIndexes[currentMob]]; super.streamClass.add2ByteInt(dummyMob.serverIndex); super.streamClass.add2ByteInt(dummyMob.mobIntUnknown); } super.streamClass.formatPacket(); mobCount = 0; } loading = false; return; } if (command == 109) { - if (needsClear) { + /*if (needsClear) { for (int i = 0; i < groundItemType.length; i++) { groundItemType[i] = -1; groundItemX[i] = -1; groundItemY[i] = -1; } needsClear = false; - } + }*/ for (int l = 1; l < length;) if (DataOperations.getUnsignedByte(data[l]) == 255) { // ??? int newCount = 0; int newSectionX = getSectionX() + data[l + 1] >> 3; int newSectionY = getSectionY() + data[l + 2] >> 3; l += 3; for (int groundItem = 0; groundItem < groundItemCount; groundItem++) { int newX = (groundItemX[groundItem] >> 3) - newSectionX; int newY = (groundItemY[groundItem] >> 3) - newSectionY; if (newX != 0 || newY != 0) { if (groundItem != newCount) { groundItemX[newCount] = groundItemX[groundItem]; groundItemY[newCount] = groundItemY[groundItem]; groundItemType[newCount] = groundItemType[groundItem]; groundItemObjectVar[newCount] = groundItemObjectVar[groundItem]; } newCount++; } } groundItemCount = newCount; } else { int i8 = DataOperations.getUnsigned2Bytes(data, l); l += 2; int k14 = getSectionX() + data[l++]; int j19 = getSectionY() + data[l++]; if ((i8 & 0x8000) == 0) { // New Item groundItemX[groundItemCount] = k14; groundItemY[groundItemCount] = j19; groundItemType[groundItemCount] = i8; groundItemObjectVar[groundItemCount] = 0; for (int k23 = 0; k23 < objectCount; k23++) { if (objectX[k23] != k14 || objectY[k23] != j19) continue; groundItemObjectVar[groundItemCount] = EntityHandler .getObjectDef(objectType[k23]) .getGroundItemVar(); break; } groundItemCount++; } else { // Known Item i8 &= 0x7fff; int l23 = 0; for (int k26 = 0; k26 < groundItemCount; k26++) { if (groundItemX[k26] != k14 || groundItemY[k26] != j19 || groundItemType[k26] != i8) { // Keep // how // it is if (k26 != l23) { groundItemX[l23] = groundItemX[k26]; groundItemY[l23] = groundItemY[k26]; groundItemType[l23] = groundItemType[k26]; groundItemObjectVar[l23] = groundItemObjectVar[k26]; } l23++; } else { // Remove i8 = -123; } } groundItemCount = l23; } } return; } if (command == 27) { for (int i1 = 1; i1 < length;) if (DataOperations.getUnsignedByte(data[i1]) == 255) { int j8 = 0; int l14 = getSectionX() + data[i1 + 1] >> 3; int k19 = getSectionY() + data[i1 + 2] >> 3; i1 += 3; for (int i24 = 0; i24 < objectCount; i24++) { int l26 = (objectX[i24] >> 3) - l14; int k29 = (objectY[i24] >> 3) - k19; if (l26 != 0 || k29 != 0) { if (i24 != j8) { objectModelArray[j8] = objectModelArray[i24]; objectModelArray[j8].anInt257 = j8; objectX[j8] = objectX[i24]; objectY[j8] = objectY[i24]; objectType[j8] = objectType[i24]; objectID[j8] = objectID[i24]; } j8++; } else { gameCamera.removeModel(objectModelArray[i24]); engineHandle.updateObject(objectX[i24], objectY[i24], objectType[i24], objectID[i24]); } } objectCount = j8; } else { int k8 = DataOperations.getUnsigned2Bytes(data, i1); i1 += 2; int i15 = getSectionX() + data[i1++]; int l19 = getSectionY() + data[i1++]; int l29 = data[i1++]; int j24 = 0; for (int i27 = 0; i27 < objectCount; i27++) if (objectX[i27] != i15 || objectY[i27] != l19 || objectID[i27] != l29) { if (i27 != j24) { objectModelArray[j24] = objectModelArray[i27]; objectModelArray[j24].anInt257 = j24; objectX[j24] = objectX[i27]; objectY[j24] = objectY[i27]; objectType[j24] = objectType[i27]; objectID[j24] = objectID[i27]; } j24++; } else { gameCamera.removeModel(objectModelArray[i27]); engineHandle.updateObject(objectX[i27], objectY[i27], objectType[i27], objectID[i27]); } objectCount = j24; if (k8 != 60000) { engineHandle.registerObjectDir(i15, l19, l29); int i34; int j37; if (l29 == 0 || l29 == 4) { i34 = EntityHandler.getObjectDef(k8).getWidth(); j37 = EntityHandler.getObjectDef(k8) .getHeight(); } else { j37 = EntityHandler.getObjectDef(k8).getWidth(); i34 = EntityHandler.getObjectDef(k8) .getHeight(); } int j40 = ((i15 + i15 + i34) * magicLoc) / 2; int i42 = ((l19 + l19 + j37) * magicLoc) / 2; int k43 = EntityHandler.getObjectDef(k8).modelID; Model model_1 = gameDataModels[k43].method203(); gameCamera.addModel(model_1); model_1.anInt257 = objectCount; model_1.method188(0, l29 * 32, 0); model_1.method190(j40, -engineHandle .getAveragedElevation(j40, i42), i42); model_1.method184(true, 48, 48, -50, -10, -50); engineHandle.method412(i15, l19, k8, l29); if (k8 == 74) model_1.method190(0, -480, 0); objectX[objectCount] = i15; objectY[objectCount] = l19; objectType[objectCount] = k8; objectID[objectCount] = l29; objectModelArray[objectCount++] = model_1; } } return; }// command == 48 if (command == 114) { int invOffset = 1; inventoryCount = data[invOffset++] & 0xff; for (int invItem = 0; invItem < inventoryCount; invItem++) { int j15 = DataOperations.getUnsigned2Bytes(data, invOffset); invOffset += 2; getInventoryItems()[invItem] = (j15 & 0x7fff); wearing[invItem] = j15 / 32768; if (EntityHandler.getItemDef(j15 & 0x7fff).isStackable()) { inventoryItemsCount[invItem] = DataOperations.readInt( data, invOffset); invOffset += 4; } else { inventoryItemsCount[invItem] = 1; } } return; } if (command == 53) { int mobCount = DataOperations.getUnsigned2Bytes(data, 1); int mobUpdateOffset = 3; for (int currentMob = 0; currentMob < mobCount; currentMob++) { int mobArrayIndex = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mobArrayIndex < 0 || mobArrayIndex > mobArray.length) { return; } Mob mob = mobArray[mobArrayIndex]; if (mob == null) { return; } byte mobUpdateType = data[mobUpdateOffset++]; if (mobUpdateType == 0) { int i30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.anInt163 = 150; mob.anInt162 = i30; } } else if (mobUpdateType == 1) { // Player talking byte byte7 = data[mobUpdateOffset++]; if (mob != null) { String s2 = DataConversions.byteToString(data, mobUpdateOffset, byte7); mob.lastMessageTimeout = 150; mob.lastMessage = s2; displayMessage(mob.name + ": " + mob.lastMessage, 2, mob.admin); } mobUpdateOffset += byte7; } else if (mobUpdateType == 2) { // Someone getting hit. int j30 = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); int hits = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); int hitsBase = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); if (mob != null) { mob.anInt164 = j30; mob.hitPointsCurrent = hits; mob.hitPointsBase = hitsBase; mob.combatTimer = 200; if (mob == ourPlayer) { playerStatCurrent[3] = hits; playerStatBase[3] = hitsBase; showWelcomeBox = false; // showServerMessageBox = false; } } } else if (mobUpdateType == 3) { // Projectile an npc.. int k30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; int k34 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.attackingCameraInt = k30; mob.attackingNpcIndex = k34; mob.attackingMobIndex = -1; mob.anInt176 = attackingInt40; } } else if (mobUpdateType == 4) { // Projectile another // player. int l30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; int l34 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.attackingCameraInt = l30; mob.attackingMobIndex = l34; mob.attackingNpcIndex = -1; mob.anInt176 = attackingInt40; } } else if (mobUpdateType == 5) { // Apperance update if (mob != null) { mob.mobIntUnknown = DataOperations .getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; mob.nameLong = DataOperations.getUnsigned8Bytes( data, mobUpdateOffset); mobUpdateOffset += 8; mob.name = DataOperations .longToString(mob.nameLong); int i31 = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset++; for (int i35 = 0; i35 < i31; i35++) { mob.animationCount[i35] = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset++; } for (int l37 = i31; l37 < 12; l37++) mob.animationCount[l37] = 0; mob.colourHairType = data[mobUpdateOffset++] & 0xff; mob.colourTopType = data[mobUpdateOffset++] & 0xff; mob.colourBottomType = data[mobUpdateOffset++] & 0xff; mob.colourSkinType = data[mobUpdateOffset++] & 0xff; mob.level = data[mobUpdateOffset++] & 0xff; mob.anInt179 = data[mobUpdateOffset++] & 0xff; mob.admin = data[mobUpdateOffset++] & 0xff; } else { mobUpdateOffset += 14; int j31 = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset += j31 + 1; } } else if (mobUpdateType == 6) { // private player talking byte byte8 = data[mobUpdateOffset]; mobUpdateOffset++; if (mob != null) { String s3 = DataConversions.byteToString(data, mobUpdateOffset, byte8); mob.lastMessageTimeout = 150; mob.lastMessage = s3; if (mob == ourPlayer) displayMessage(mob.name + ": " + mob.lastMessage, 5, mob.admin); } mobUpdateOffset += byte8; } } return; } if (command == 129) { combatStyle = DataOperations.getUnsignedByte(data[1]); return; } if (command == 95) { for (int l1 = 1; l1 < length;) if (DataOperations.getUnsignedByte(data[l1]) == 255) { int j9 = 0; int l15 = getSectionX() + data[l1 + 1] >> 3; int j20 = getSectionY() + data[l1 + 2] >> 3; l1 += 3; for (int currentDoor = 0; currentDoor < doorCount; currentDoor++) { int j27 = (doorX[currentDoor] >> 3) - l15; int k31 = (doorY[currentDoor] >> 3) - j20; if (j27 != 0 || k31 != 0) { if (currentDoor != j9) { doorModel[j9] = doorModel[currentDoor]; doorModel[j9].anInt257 = j9 + 10000; doorX[j9] = doorX[currentDoor]; doorY[j9] = doorY[currentDoor]; doorDirection[j9] = doorDirection[currentDoor]; doorType[j9] = doorType[currentDoor]; } j9++; } else { gameCamera.removeModel(doorModel[currentDoor]); engineHandle.updateDoor(doorX[currentDoor], doorY[currentDoor], doorDirection[currentDoor], doorType[currentDoor]); } } doorCount = j9; } else { int k9 = DataOperations.getUnsigned2Bytes(data, l1); l1 += 2; int i16 = getSectionX() + data[l1++]; int k20 = getSectionY() + data[l1++]; byte byte5 = data[l1++]; int k27 = 0; for (int l31 = 0; l31 < doorCount; l31++) if (doorX[l31] != i16 || doorY[l31] != k20 || doorDirection[l31] != byte5) { if (l31 != k27) { doorModel[k27] = doorModel[l31]; doorModel[k27].anInt257 = k27 + 10000; doorX[k27] = doorX[l31]; doorY[k27] = doorY[l31]; doorDirection[k27] = doorDirection[l31]; doorType[k27] = doorType[l31]; } k27++; } else { gameCamera.removeModel(doorModel[l31]); engineHandle.updateDoor(doorX[l31], doorY[l31], doorDirection[l31], doorType[l31]); } doorCount = k27; if (k9 != 60000) { // 65535) { engineHandle.method408(i16, k20, byte5, k9); Model model = makeModel(i16, k20, byte5, k9, doorCount); doorModel[doorCount] = model; doorX[doorCount] = i16; doorY[doorCount] = k20; doorType[doorCount] = k9; doorDirection[doorCount++] = byte5; } } return; } if (command == 77) { lastNpcCount = npcCount; npcCount = 0; for (int lastNpcIndex = 0; lastNpcIndex < lastNpcCount; lastNpcIndex++) lastNpcArray[lastNpcIndex] = npcArray[lastNpcIndex]; int newNpcOffset = 8; int newNpcCount = DataOperations.getIntFromByteArray(data, newNpcOffset, 8); newNpcOffset += 8; for (int newNpcIndex = 0; newNpcIndex < newNpcCount; newNpcIndex++) { Mob newNPC = getLastNpc(DataOperations.getIntFromByteArray( data, newNpcOffset, 16)); newNpcOffset += 16; int npcNeedsUpdate = DataOperations.getIntFromByteArray( data, newNpcOffset, 1); newNpcOffset++; if (npcNeedsUpdate != 0) { int i32 = DataOperations.getIntFromByteArray(data, newNpcOffset, 1); newNpcOffset++; if (i32 == 0) { int nextSprite = DataOperations .getIntFromByteArray(data, newNpcOffset, 3); newNpcOffset += 3; int waypointCurrent = newNPC.waypointCurrent; int waypointX = newNPC.waypointsX[waypointCurrent]; int waypointY = newNPC.waypointsY[waypointCurrent]; if (nextSprite == 2 || nextSprite == 1 || nextSprite == 3) waypointX += magicLoc; if (nextSprite == 6 || nextSprite == 5 || nextSprite == 7) waypointX -= magicLoc; if (nextSprite == 4 || nextSprite == 3 || nextSprite == 5) waypointY += magicLoc; if (nextSprite == 0 || nextSprite == 1 || nextSprite == 7) waypointY -= magicLoc; newNPC.nextSprite = nextSprite; newNPC.waypointCurrent = waypointCurrent = (waypointCurrent + 1) % 10; newNPC.waypointsX[waypointCurrent] = waypointX; newNPC.waypointsY[waypointCurrent] = waypointY; } else { int nextSpriteOffset = DataOperations .getIntFromByteArray(data, newNpcOffset, 4); newNpcOffset += 4; if ((nextSpriteOffset & 0xc) == 12) { continue; } newNPC.nextSprite = nextSpriteOffset; } } npcArray[npcCount++] = newNPC; } while (newNpcOffset + 34 < length * 8) { int serverIndex = DataOperations.getIntFromByteArray(data, newNpcOffset, 16); newNpcOffset += 16; int i28 = DataOperations.getIntFromByteArray(data, newNpcOffset, 5); newNpcOffset += 5; if (i28 > 15) i28 -= 32; int j32 = DataOperations.getIntFromByteArray(data, newNpcOffset, 5); newNpcOffset += 5; if (j32 > 15) j32 -= 32; int nextSprite = DataOperations.getIntFromByteArray(data, newNpcOffset, 4); newNpcOffset += 4; int x = (getSectionX() + i28) * magicLoc + 64; int y = (getSectionY() + j32) * magicLoc + 64; int type = DataOperations.getIntFromByteArray(data, newNpcOffset, 10); newNpcOffset += 10; if (type >= EntityHandler.npcCount()) type = 24; addNPC(serverIndex, x, y, nextSprite, type); } return; } if (command == 190) { int j2 = DataOperations.getUnsigned2Bytes(data, 1); int i10 = 3; for (int k16 = 0; k16 < j2; k16++) { int i21 = DataOperations.getUnsigned2Bytes(data, i10); i10 += 2; Mob mob_2 = npcRecordArray[i21]; int j28 = DataOperations.getUnsignedByte(data[i10]); i10++; if (j28 == 1) { int k32 = DataOperations.getUnsigned2Bytes(data, i10); i10 += 2; byte byte9 = data[i10]; i10++; if (mob_2 != null) { String s4 = DataConversions.byteToString(data, i10, byte9); mob_2.lastMessageTimeout = 150; mob_2.lastMessage = s4; if (k32 == ourPlayer.serverIndex) displayMessage("@yel@" + EntityHandler.getNpcDef(mob_2.type) .getName() + ": " + mob_2.lastMessage, 5, 0); } i10 += byte9; } else if (j28 == 2) { int l32 = DataOperations.getUnsignedByte(data[i10]); i10++; int i36 = DataOperations.getUnsignedByte(data[i10]); i10++; int k38 = DataOperations.getUnsignedByte(data[i10]); i10++; if (mob_2 != null) { mob_2.anInt164 = l32; mob_2.hitPointsCurrent = i36; mob_2.hitPointsBase = k38; mob_2.combatTimer = 200; } } } return; } if (command == 223) { showQuestionMenu = true; int newQuestionMenuCount = DataOperations .getUnsignedByte(data[1]); questionMenuCount = newQuestionMenuCount; int newQuestionMenuOffset = 2; for (int l16 = 0; l16 < newQuestionMenuCount; l16++) { int newQuestionMenuQuestionLength = DataOperations .getUnsignedByte(data[newQuestionMenuOffset]); newQuestionMenuOffset++; questionMenuAnswer[l16] = new String(data, newQuestionMenuOffset, newQuestionMenuQuestionLength); newQuestionMenuOffset += newQuestionMenuQuestionLength; } return; } if (command == 127) { showQuestionMenu = false; return; }// if (command == 109) { if (command == 131) { needsClear = true; notInWilderness = true; hasWorldInfo = true; serverIndex = DataOperations.getUnsigned2Bytes(data, 1); wildX = DataOperations.getUnsigned2Bytes(data, 3); wildY = DataOperations.getUnsigned2Bytes(data, 5); wildYSubtract = DataOperations.getUnsigned2Bytes(data, 7); wildYMultiplier = DataOperations.getUnsigned2Bytes(data, 9); wildY -= wildYSubtract * wildYMultiplier; return; } if (command == 180) { int l2 = 1; for (int k10 = 0; k10 < 18; k10++) { playerStatCurrent[k10] = DataOperations .getUnsignedByte(data[l2++]); } for (int i17 = 0; i17 < 18; i17++) { playerStatBase[i17] = DataOperations .getUnsignedByte(data[l2++]); } for (int k21 = 0; k21 < 18; k21++) { playerStatExperience[k21] = DataOperations .readInt(data, l2); l2 += 4; } expGained = 0; return; }// command == 114 if (command == 177) { int i3 = 1; for (int x = 0; x < 6; x++) { equipmentStatus[x] = DataOperations.getSigned2Bytes(data, i3); i3 += 2; } return; } if (command == 165) { playerAliveTimeout = 250; return; } if (command == 115) { int thingLength = (length - 1) / 4; for (int currentThing = 0; currentThing < thingLength; currentThing++) { int currentItemSectionX = getSectionX() + DataOperations.getSigned2Bytes(data, 1 + currentThing * 4) >> 3; int currentItemSectionY = getSectionY() + DataOperations.getSigned2Bytes(data, 3 + currentThing * 4) >> 3; int currentCount = 0; for (int currentItem = 0; currentItem < groundItemCount; currentItem++) { int currentItemOffsetX = (groundItemX[currentItem] >> 3) - currentItemSectionX; int currentItemOffsetY = (groundItemY[currentItem] >> 3) - currentItemSectionY; if (currentItemOffsetX != 0 || currentItemOffsetY != 0) { if (currentItem != currentCount) { groundItemX[currentCount] = groundItemX[currentItem]; groundItemY[currentCount] = groundItemY[currentItem]; groundItemType[currentCount] = groundItemType[currentItem]; groundItemObjectVar[currentCount] = groundItemObjectVar[currentItem]; } currentCount++; } } groundItemCount = currentCount; currentCount = 0; for (int j33 = 0; j33 < objectCount; j33++) { int k36 = (objectX[j33] >> 3) - currentItemSectionX; int l38 = (objectY[j33] >> 3) - currentItemSectionY; if (k36 != 0 || l38 != 0) { if (j33 != currentCount) { objectModelArray[currentCount] = objectModelArray[j33]; objectModelArray[currentCount].anInt257 = currentCount; objectX[currentCount] = objectX[j33]; objectY[currentCount] = objectY[j33]; objectType[currentCount] = objectType[j33]; objectID[currentCount] = objectID[j33]; } currentCount++; } else { gameCamera.removeModel(objectModelArray[j33]); engineHandle.updateObject(objectX[j33], objectY[j33], objectType[j33], objectID[j33]); } } objectCount = currentCount; currentCount = 0; for (int l36 = 0; l36 < doorCount; l36++) { int i39 = (doorX[l36] >> 3) - currentItemSectionX; int j41 = (doorY[l36] >> 3) - currentItemSectionY; if (i39 != 0 || j41 != 0) { if (l36 != currentCount) { doorModel[currentCount] = doorModel[l36]; doorModel[currentCount].anInt257 = currentCount + 10000; doorX[currentCount] = doorX[l36]; doorY[currentCount] = doorY[l36]; doorDirection[currentCount] = doorDirection[l36]; doorType[currentCount] = doorType[l36]; } currentCount++; } else { gameCamera.removeModel(doorModel[l36]); engineHandle.updateDoor(doorX[l36], doorY[l36], doorDirection[l36], doorType[l36]); } } doorCount = currentCount; } return; } if (command == 230) { showDrawPointsScreen = true; int pkbytes = 1; pkatk = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkdef = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkstr = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkrange = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkmagic = DataOperations.readInt(data, pkbytes); } if (command == 207) { showCharacterLookScreen = true; return; } if (command == 4) { int currentMob = DataOperations.getUnsigned2Bytes(data, 1); if (mobArray[currentMob] != null) // todo: check what that // mobArray is tradeOtherPlayerName = mobArray[currentMob].name; showTradeWindow = true; tradeOtherAccepted = false; tradeWeAccepted = false; tradeMyItemCount = 0; tradeOtherItemCount = 0; return; } if (command == 187) { showTradeWindow = false; showTradeConfirmWindow = false; return; } if (command == 250) { tradeOtherItemCount = data[1] & 0xff; int l3 = 2; for (int i11 = 0; i11 < tradeOtherItemCount; i11++) { tradeOtherItems[i11] = DataOperations.getUnsigned2Bytes( data, l3); l3 += 2; tradeOtherItemsCount[i11] = DataOperations .readInt(data, l3); l3 += 4; } tradeOtherAccepted = false; tradeWeAccepted = false; return; } if (command == 92) { tradeOtherAccepted = data[1] == 1; } if (command == 253) { showShop = true; int i4 = 1; int j11 = data[i4++] & 0xff; byte byte4 = data[i4++]; shopItemSellPriceModifier = data[i4++] & 0xff; shopItemBuyPriceModifier = data[i4++] & 0xff; for (int i22 = 0; i22 < 40; i22++) shopItems[i22] = -1; for (int j25 = 0; j25 < j11; j25++) { shopItems[j25] = DataOperations.getUnsigned2Bytes(data, i4); i4 += 2; shopItemCount[j25] = DataOperations.getUnsigned2Bytes(data, i4); i4 += 2; shopItemsBuyPrice[j25] = DataOperations.getUnsigned4Bytes( data, i4); i4 += 4; shopItemsSellPrice[j25] = DataOperations.getUnsigned4Bytes( data, i4); i4 += 4; } if (byte4 == 1) { int l28 = 39; for (int k33 = 0; k33 < inventoryCount; k33++) { if (l28 < j11) break; boolean flag2 = false; for (int j39 = 0; j39 < 40; j39++) { if (shopItems[j39] != getInventoryItems()[k33]) continue; flag2 = true; break; } if (getInventoryItems()[k33] == 10) flag2 = true; if (!flag2) { // our own item that's not in stock. shopItems[l28] = getInventoryItems()[k33] & 0x7fff; shopItemsSellPrice[l28] = EntityHandler .getItemDef(shopItems[l28]).basePrice - (int) (EntityHandler .getItemDef(shopItems[l28]).basePrice / 2.5); shopItemsSellPrice[l28] = shopItemsSellPrice[l28] - (int) (shopItemsSellPrice[l28] * 0.10); shopItemCount[l28] = 0; l28--; } } } if (selectedShopItemIndex >= 0 && selectedShopItemIndex < 40 && shopItems[selectedShopItemIndex] != selectedShopItemType) { selectedShopItemIndex = -1; selectedShopItemType = -2; } return; } if (command == 220) { showShop = false; return; } if (command == 18) { tradeWeAccepted = data[1] == 1; } if (command == 152) { configAutoCameraAngle = DataOperations.getUnsignedByte(data[1]) == 1; configMouseButtons = DataOperations.getUnsignedByte(data[2]) == 1; configSoundEffects = DataOperations.getUnsignedByte(data[3]) == 1; showRoof = DataOperations.getUnsignedByte(data[4]) == 1; autoScreenshot = DataOperations.getUnsignedByte(data[5]) == 1; combatWindow = DataOperations.getUnsignedByte(data[6]) == 1; return; } if (command == 209) { for (int currentPrayer = 0; currentPrayer < length - 1; currentPrayer++) { boolean prayerOff = data[currentPrayer + 1] == 1; if (!prayerOn[currentPrayer] && prayerOff) playSound("prayeron"); if (prayerOn[currentPrayer] && !prayerOff) playSound("prayeroff"); prayerOn[currentPrayer] = prayerOff; } return; } if (command == 93) { showBank = true; int l4 = 1; newBankItemCount = data[l4++] & 0xff; bankItemsMax = data[l4++] & 0xff; for (int k11 = 0; k11 < newBankItemCount; k11++) { newBankItems[k11] = DataOperations.getUnsigned2Bytes(data, l4); l4 += 2; newBankItemsCount[k11] = DataOperations.getUnsigned4Bytes( data, l4); l4 += 4; } updateBankItems(); return; } if (command == 171) { showBank = false; return; } if (command == 211) { int idx = data[1] & 0xFF; int oldExp = playerStatExperience[idx]; playerStatExperience[idx] = DataOperations.readInt(data, 2); if (playerStatExperience[idx] > oldExp) { expGained += (playerStatExperience[idx] - oldExp); } return; } if (command == 229) { int j5 = DataOperations.getUnsigned2Bytes(data, 1); if (mobArray[j5] != null) { duelOpponentName = mobArray[j5].name; } showDuelWindow = true; duelMyItemCount = 0; duelOpponentItemCount = 0; duelOpponentAccepted = false; duelMyAccepted = false; duelNoRetreating = false; duelNoMagic = false; duelNoPrayer = false; duelNoWeapons = false; return; } if (command == 160) { showDuelWindow = false; showDuelConfirmWindow = false; return; } if (command == 251) { showTradeConfirmWindow = true; tradeConfirmAccepted = false; showTradeWindow = false; int k5 = 1; tradeConfirmOtherNameLong = DataOperations.getUnsigned8Bytes( data, k5); k5 += 8; tradeConfirmOtherItemCount = data[k5++] & 0xff; for (int l11 = 0; l11 < tradeConfirmOtherItemCount; l11++) { tradeConfirmOtherItems[l11] = DataOperations .getUnsigned2Bytes(data, k5); k5 += 2; tradeConfirmOtherItemsCount[l11] = DataOperations.readInt( data, k5); k5 += 4; } tradeConfirmItemCount = data[k5++] & 0xff; for (int k17 = 0; k17 < tradeConfirmItemCount; k17++) { tradeConfirmItems[k17] = DataOperations.getUnsigned2Bytes( data, k5); k5 += 2; tradeConfirmItemsCount[k17] = DataOperations.readInt(data, k5); k5 += 4; } return; } if (command == 63) { duelOpponentItemCount = data[1] & 0xff; int l5 = 2; for (int i12 = 0; i12 < duelOpponentItemCount; i12++) { duelOpponentItems[i12] = DataOperations.getUnsigned2Bytes( data, l5); l5 += 2; duelOpponentItemsCount[i12] = DataOperations.readInt(data, l5); l5 += 4; } duelOpponentAccepted = false; duelMyAccepted = false; return; } if (command == 198) { duelNoRetreating = data[1] == 1; duelNoMagic = data[2] == 1; duelNoPrayer = data[3] == 1; duelNoWeapons = data[4] == 1; duelOpponentAccepted = false; duelMyAccepted = false; return; } if (command == 139) { int bankDataOffset = 1; int bankSlot = data[bankDataOffset++] & 0xff; int bankItemId = DataOperations.getUnsigned2Bytes(data, bankDataOffset); bankDataOffset += 2; int bankItemCount = DataOperations.getUnsigned4Bytes(data, bankDataOffset); bankDataOffset += 4; if (bankItemCount == 0) { newBankItemCount--; for (int currentBankSlot = bankSlot; currentBankSlot < newBankItemCount; currentBankSlot++) { newBankItems[currentBankSlot] = newBankItems[currentBankSlot + 1]; newBankItemsCount[currentBankSlot] = newBankItemsCount[currentBankSlot + 1]; } } else { newBankItems[bankSlot] = bankItemId; newBankItemsCount[bankSlot] = bankItemCount; if (bankSlot >= newBankItemCount) newBankItemCount = bankSlot + 1; } updateBankItems(); return; } if (command == 228) { int j6 = 1; int k12 = 1; int i18 = data[j6++] & 0xff; int k22 = DataOperations.getUnsigned2Bytes(data, j6); j6 += 2; if (EntityHandler.getItemDef(k22 & 0x7fff).isStackable()) { k12 = DataOperations.readInt(data, j6); j6 += 4; } getInventoryItems()[i18] = k22 & 0x7fff; wearing[i18] = k22 / 32768; inventoryItemsCount[i18] = k12; if (i18 >= inventoryCount) inventoryCount = i18 + 1; return; } if (command == 191) { int k6 = data[1] & 0xff; inventoryCount--; for (int l12 = k6; l12 < inventoryCount; l12++) { getInventoryItems()[l12] = getInventoryItems()[l12 + 1]; inventoryItemsCount[l12] = inventoryItemsCount[l12 + 1]; wearing[l12] = wearing[l12 + 1]; } return; } if (command == 208) { int pointer = 1; int idx = data[pointer++] & 0xff; int oldExp = playerStatExperience[idx]; playerStatCurrent[idx] = DataOperations .getUnsignedByte(data[pointer++]); playerStatBase[idx] = DataOperations .getUnsignedByte(data[pointer++]); playerStatExperience[idx] = DataOperations.readInt(data, pointer); pointer += 4; if (playerStatExperience[idx] > oldExp) { expGained += (playerStatExperience[idx] - oldExp); } return; } if (command == 65) { duelOpponentAccepted = data[1] == 1; } if (command == 197) { duelMyAccepted = data[1] == 1; } if (command == 147) { showDuelConfirmWindow = true; duelWeAccept = false; showDuelWindow = false; int i7 = 1; duelOpponentNameLong = DataOperations.getUnsigned8Bytes(data, i7); i7 += 8; duelConfirmOpponentItemCount = data[i7++] & 0xff; for (int j13 = 0; j13 < duelConfirmOpponentItemCount; j13++) { duelConfirmOpponentItems[j13] = DataOperations .getUnsigned2Bytes(data, i7); i7 += 2; duelConfirmOpponentItemsCount[j13] = DataOperations .readInt(data, i7); i7 += 4; } duelConfirmMyItemCount = data[i7++] & 0xff; for (int j18 = 0; j18 < duelConfirmMyItemCount; j18++) { duelConfirmMyItems[j18] = DataOperations.getUnsigned2Bytes( data, i7); i7 += 2; duelConfirmMyItemsCount[j18] = DataOperations.readInt(data, i7); i7 += 4; } duelCantRetreat = data[i7++] & 0xff; duelUseMagic = data[i7++] & 0xff; duelUsePrayer = data[i7++] & 0xff; duelUseWeapons = data[i7++] & 0xff; return; } if (command == 11) { String s = new String(data, 1, length - 1); playSound(s); return; } if (command == 23) { if (anInt892 < 50) { int j7 = data[1] & 0xff; int k13 = data[2] + getSectionX(); int k18 = data[3] + getSectionY(); anIntArray782[anInt892] = j7; anIntArray923[anInt892] = 0; anIntArray944[anInt892] = k13; anIntArray757[anInt892] = k18; anInt892++; } return; } if (command == 248) { if (!hasReceivedWelcomeBoxDetails) { lastLoggedInDays = DataOperations .getUnsigned2Bytes(data, 1); subscriptionLeftDays = DataOperations.getUnsigned2Bytes( data, 3); lastLoggedInAddress = new String(data, 5, length - 5); showWelcomeBox = true; hasReceivedWelcomeBoxDetails = true; } return; } if (command == 148) { serverMessage = new String(data, 1, length - 1); showServerMessageBox = true; serverMessageBoxTop = false; return; } if (command == 64) { serverMessage = new String(data, 1, length - 1); showServerMessageBox = true; serverMessageBoxTop = true; return; } if (command == 126) { fatigue = DataOperations.getUnsigned2Bytes(data, 1); return; } if (command == 206) { if (!sleeping) { } sleeping = true; gameMenu.updateText(chatHandle, ""); super.inputText = ""; super.enteredText = ""; sleepEquation = DataOperations.getImage(data, 1, length); // sleepMessage = null; return; } if (command == 182) { int offset = 1; questPoints = DataOperations.getUnsigned2Bytes(data, offset); offset += 2; for (int i = 0; i < questName.length; i++) questStage[i] = data[offset + i]; return; } if (command == 224) { sleeping = false; sleepMessage = null; return; } if (command == 225) { sleepMessage = "Incorrect - please try again..."; return; } if (command == 174) { DataOperations.getUnsigned2Bytes(data, 1); return; } if (command == 181) { if (autoScreenshot) { takeScreenshot(false); } return; } if (command == 172) { systemUpdate = DataOperations.getUnsigned2Bytes(data, 1) * 32; return; } // System.out.println("Bad ID: " + command + " Length: " + length); } catch (Exception e) { // e.printStackTrace(); /* * if (handlePacketErrorCount < 3) { * super.streamClass.createPacket(156); * super.streamClass.addString(runtimeexception.toString()); * super.streamClass.formatPacket(); handlePacketErrorCount++; } */ } } private String sleepMessage = ""; protected final void lostConnection() { systemUpdate = 0; if (logoutTimeout != 0) { resetIntVars(); return; } super.lostConnection(); } private final void playSound(String s) { if (audioReader == null) { return; } if (configSoundEffects) { return; } audioReader.loadData(sounds, DataOperations.method358(s + ".pcm", sounds), DataOperations.method359(s + ".pcm", sounds)); } private final boolean sendWalkCommand(int walkSectionX, int walkSectionY, int x1, int y1, int x2, int y2, boolean stepBoolean, boolean coordsEqual) { // todo: needs checking int stepCount = engineHandle.getStepCount(walkSectionX, walkSectionY, x1, y1, x2, y2, sectionXArray, sectionYArray, stepBoolean); if (stepCount == -1) if (coordsEqual) { stepCount = 1; sectionXArray[0] = x1; sectionYArray[0] = y1; } else { return false; } stepCount--; walkSectionX = sectionXArray[stepCount]; walkSectionY = sectionYArray[stepCount]; stepCount--; if (coordsEqual) super.streamClass.createPacket(246); else super.streamClass.createPacket(132); super.streamClass.add2ByteInt(walkSectionX + getAreaX()); super.streamClass.add2ByteInt(walkSectionY + getAreaY()); if (coordsEqual && stepCount == -1 && (walkSectionX + getAreaX()) % 5 == 0) stepCount = 0; for (int currentStep = stepCount; currentStep >= 0 && currentStep > stepCount - 25; currentStep--) { super.streamClass .addByte(sectionXArray[currentStep] - walkSectionX); super.streamClass .addByte(sectionYArray[currentStep] - walkSectionY); } super.streamClass.formatPacket(); actionPictureType = -24; actionPictureX = super.mouseX; // guessing the little red/yellow x that // appears when you click actionPictureY = super.mouseY; return true; } private final boolean sendWalkCommandIgnoreCoordsEqual(int walkSectionX, int walkSectionY, int x1, int y1, int x2, int y2, boolean stepBoolean, boolean coordsEqual) { int stepCount = engineHandle.getStepCount(walkSectionX, walkSectionY, x1, y1, x2, y2, sectionXArray, sectionYArray, stepBoolean); if (stepCount == -1) return false; stepCount--; walkSectionX = sectionXArray[stepCount]; walkSectionY = sectionYArray[stepCount]; stepCount--; if (coordsEqual) super.streamClass.createPacket(246); else super.streamClass.createPacket(132); super.streamClass.add2ByteInt(walkSectionX + getAreaX()); super.streamClass.add2ByteInt(walkSectionY + getAreaY()); if (coordsEqual && stepCount == -1 && (walkSectionX + getAreaX()) % 5 == 0) stepCount = 0; for (int currentStep = stepCount; currentStep >= 0 && currentStep > stepCount - 25; currentStep--) { super.streamClass .addByte(sectionXArray[currentStep] - walkSectionX); super.streamClass .addByte(sectionYArray[currentStep] - walkSectionY); } super.streamClass.formatPacket(); actionPictureType = -24; actionPictureX = super.mouseX; actionPictureY = super.mouseY; return true; } public final Image createImage(int i, int j) { if (GameWindow.gameFrame != null) { return GameWindow.gameFrame.createImage(i, j); } return super.createImage(i, j); } private final void drawTradeConfirmWindow() { int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 16, 192); int i = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 16, 468, 246, i, 160); gameGraphics.drawText("Please confirm your trade with @yel@" + DataOperations.longToString(tradeConfirmOtherNameLong), byte0 + 234, byte1 + 12, 1, 0xffffff); gameGraphics.drawText("You are about to give:", byte0 + 117, byte1 + 30, 1, 0xffff00); for (int j = 0; j < tradeConfirmItemCount; j++) { String s = EntityHandler.getItemDef(tradeConfirmItems[j]).getName(); if (EntityHandler.getItemDef(tradeConfirmItems[j]).isStackable()) s = s + " x " + method74(tradeConfirmItemsCount[j]); gameGraphics.drawText(s, byte0 + 117, byte1 + 42 + j * 12, 1, 0xffffff); } if (tradeConfirmItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 117, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("In return you will receive:", byte0 + 351, byte1 + 30, 1, 0xffff00); for (int k = 0; k < tradeConfirmOtherItemCount; k++) { String s1 = EntityHandler.getItemDef(tradeConfirmOtherItems[k]) .getName(); if (EntityHandler.getItemDef(tradeConfirmOtherItems[k]) .isStackable()) s1 = s1 + " x " + method74(tradeConfirmOtherItemsCount[k]); gameGraphics.drawText(s1, byte0 + 351, byte1 + 42 + k * 12, 1, 0xffffff); } if (tradeConfirmOtherItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 351, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("Are you sure you want to do this?", byte0 + 234, byte1 + 200, 4, 65535); gameGraphics.drawText( "There is NO WAY to reverse a trade if you change your mind.", byte0 + 234, byte1 + 215, 1, 0xffffff); gameGraphics.drawText("Remember that not all players are trustworthy", byte0 + 234, byte1 + 230, 1, 0xffffff); if (!tradeConfirmAccepted) { gameGraphics.drawPicture((byte0 + 118) - 35, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture((byte0 + 352) - 35, byte1 + 238, SPRITE_MEDIA_START + 26); } else { gameGraphics.drawText("Waiting for other player...", byte0 + 234, byte1 + 250, 1, 0xffff00); } if (mouseButtonClick == 1) { if (super.mouseX < byte0 || super.mouseY < byte1 || super.mouseX > byte0 + 468 || super.mouseY > byte1 + 262) { showTradeConfirmWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 118) - 35 && super.mouseX <= byte0 + 118 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { tradeConfirmAccepted = true; super.streamClass.createPacket(53); // createPacket(73 super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 352) - 35 && super.mouseX <= byte0 + 353 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { showTradeConfirmWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } mouseButtonClick = 0; } } private final void walkToGroundItem(int walkSectionX, int walkSectionY, int x, int y, boolean coordsEqual) { if (sendWalkCommandIgnoreCoordsEqual(walkSectionX, walkSectionY, x, y, x, y, false, coordsEqual)) { return; } else { sendWalkCommand(walkSectionX, walkSectionY, x, y, x, y, true, coordsEqual); return; } } private final Mob addNPC(int serverIndex, int x, int y, int nextSprite, int type) { if (npcRecordArray[serverIndex] == null) { npcRecordArray[serverIndex] = new Mob(); npcRecordArray[serverIndex].serverIndex = serverIndex; } Mob mob = npcRecordArray[serverIndex]; boolean npcAlreadyExists = false; for (int lastNpcIndex = 0; lastNpcIndex < lastNpcCount; lastNpcIndex++) { if (lastNpcArray[lastNpcIndex].serverIndex != serverIndex) continue; npcAlreadyExists = true; break; } if (npcAlreadyExists) { mob.type = type; mob.nextSprite = nextSprite; int waypointCurrent = mob.waypointCurrent; if (x != mob.waypointsX[waypointCurrent] || y != mob.waypointsY[waypointCurrent]) { mob.waypointCurrent = waypointCurrent = (waypointCurrent + 1) % 10; mob.waypointsX[waypointCurrent] = x; mob.waypointsY[waypointCurrent] = y; } } else { mob.serverIndex = serverIndex; mob.waypointEndSprite = 0; mob.waypointCurrent = 0; mob.waypointsX[0] = mob.currentX = x; mob.waypointsY[0] = mob.currentY = y; mob.type = type; mob.nextSprite = mob.currentSprite = nextSprite; mob.stepCount = 0; } npcArray[npcCount++] = mob; return mob; } private final void drawDuelWindow() { if (mouseButtonClick != 0 && itemIncrement == 0) itemIncrement = 1; if (itemIncrement > 0) { int i = super.mouseX - 22 - xAddition; int j = super.mouseY - 36 - yAddition; if (i >= 0 && j >= 0 && i < 468 && j < 262) { if (i > 216 && j > 30 && i < 462 && j < 235) { int k = (i - 217) / 49 + ((j - 31) / 34) * 5; if (k >= 0 && k < inventoryCount) { boolean flag1 = false; int l1 = 0; int k2 = getInventoryItems()[k]; for (int k3 = 0; k3 < duelMyItemCount; k3++) if (duelMyItems[k3] == k2) if (EntityHandler.getItemDef(k2).isStackable()) { for (int i4 = 0; i4 < itemIncrement; i4++) { if (duelMyItemsCount[k3] < inventoryItemsCount[k]) duelMyItemsCount[k3]++; flag1 = true; } } else { l1++; } if (inventoryCount(k2) <= l1) flag1 = true; if (!flag1 && duelMyItemCount < 8) { duelMyItems[duelMyItemCount] = k2; duelMyItemsCount[duelMyItemCount] = 1; duelMyItemCount++; flag1 = true; } if (flag1) { super.streamClass.createPacket(123); super.streamClass.addByte(duelMyItemCount); for (int duelItem = 0; duelItem < duelMyItemCount; duelItem++) { super.streamClass .add2ByteInt(duelMyItems[duelItem]); super.streamClass .add4ByteInt(duelMyItemsCount[duelItem]); } super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } } } if (i > 8 && j > 30 && i < 205 && j < 129) { int l = (i - 9) / 49 + ((j - 31) / 34) * 4; if (l >= 0 && l < duelMyItemCount) { int j1 = duelMyItems[l]; for (int i2 = 0; i2 < itemIncrement; i2++) { if (EntityHandler.getItemDef(j1).isStackable() && duelMyItemsCount[l] > 1) { duelMyItemsCount[l]--; continue; } duelMyItemCount--; mouseDownTime = 0; for (int l2 = l; l2 < duelMyItemCount; l2++) { duelMyItems[l2] = duelMyItems[l2 + 1]; duelMyItemsCount[l2] = duelMyItemsCount[l2 + 1]; } break; } super.streamClass.createPacket(123); super.streamClass.addByte(duelMyItemCount); for (int i3 = 0; i3 < duelMyItemCount; i3++) { super.streamClass.add2ByteInt(duelMyItems[i3]); super.streamClass.add4ByteInt(duelMyItemsCount[i3]); } super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } } boolean flag = false; if (i >= 93 && j >= 221 && i <= 104 && j <= 232) { duelNoRetreating = !duelNoRetreating; flag = true; } if (i >= 93 && j >= 240 && i <= 104 && j <= 251) { duelNoMagic = !duelNoMagic; flag = true; } if (i >= 191 && j >= 221 && i <= 202 && j <= 232) { duelNoPrayer = !duelNoPrayer; flag = true; } if (i >= 191 && j >= 240 && i <= 202 && j <= 251) { duelNoWeapons = !duelNoWeapons; flag = true; } if (flag) { super.streamClass.createPacket(225); super.streamClass.addByte(duelNoRetreating ? 1 : 0); super.streamClass.addByte(duelNoMagic ? 1 : 0); super.streamClass.addByte(duelNoPrayer ? 1 : 0); super.streamClass.addByte(duelNoWeapons ? 1 : 0); super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } if (i >= 217 && j >= 238 && i <= 286 && j <= 259) { duelMyAccepted = true; super.streamClass.createPacket(252); super.streamClass.formatPacket(); } if (i >= 394 && j >= 238 && i < 463 && j < 259) { showDuelWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } } else if (mouseButtonClick != 0) { showDuelWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } mouseButtonClick = 0; itemIncrement = 0; } if (!showDuelWindow) return; int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 12, 0xc90b1d); int i1 = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 468, 18, i1, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 30, 8, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 205, byte1 + 30, 11, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 462, byte1 + 30, 6, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 99, 197, 24, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 192, 197, 23, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 258, 197, 20, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 235, 246, 43, i1, 160); int k1 = 0xd0d0d0; gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 30, 197, 69, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 123, 197, 69, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 215, 197, 43, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 30, 246, 205, k1, 160); for (int j2 = 0; j2 < 3; j2++) gameGraphics.drawLineX(byte0 + 8, byte1 + 30 + j2 * 34, 197, 0); for (int j3 = 0; j3 < 3; j3++) gameGraphics.drawLineX(byte0 + 8, byte1 + 123 + j3 * 34, 197, 0); for (int l3 = 0; l3 < 7; l3++) gameGraphics.drawLineX(byte0 + 216, byte1 + 30 + l3 * 34, 246, 0); for (int k4 = 0; k4 < 6; k4++) { if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 30, 69, 0); if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 123, 69, 0); gameGraphics.drawLineY(byte0 + 216 + k4 * 49, byte1 + 30, 205, 0); } gameGraphics.drawLineX(byte0 + 8, byte1 + 215, 197, 0); gameGraphics.drawLineX(byte0 + 8, byte1 + 257, 197, 0); gameGraphics.drawLineY(byte0 + 8, byte1 + 215, 43, 0); gameGraphics.drawLineY(byte0 + 204, byte1 + 215, 43, 0); gameGraphics.drawString("Preparing to duel with: " + duelOpponentName, byte0 + 1, byte1 + 10, 1, 0xffffff); gameGraphics.drawString("Your Stake", byte0 + 9, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("Opponent's Stake", byte0 + 9, byte1 + 120, 4, 0xffffff); gameGraphics.drawString("Duel Options", byte0 + 9, byte1 + 212, 4, 0xffffff); gameGraphics.drawString("Your Inventory", byte0 + 216, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("No retreating", byte0 + 8 + 1, byte1 + 215 + 16, 3, 0xffff00); gameGraphics.drawString("No magic", byte0 + 8 + 1, byte1 + 215 + 35, 3, 0xffff00); gameGraphics.drawString("No prayer", byte0 + 8 + 102, byte1 + 215 + 16, 3, 0xffff00); gameGraphics.drawString("No weapons", byte0 + 8 + 102, byte1 + 215 + 35, 3, 0xffff00); gameGraphics.drawBoxEdge(byte0 + 93, byte1 + 215 + 6, 11, 11, 0xffff00); if (duelNoRetreating) gameGraphics.drawBox(byte0 + 95, byte1 + 215 + 8, 7, 7, 0xffff00); gameGraphics .drawBoxEdge(byte0 + 93, byte1 + 215 + 25, 11, 11, 0xffff00); if (duelNoMagic) gameGraphics.drawBox(byte0 + 95, byte1 + 215 + 27, 7, 7, 0xffff00); gameGraphics .drawBoxEdge(byte0 + 191, byte1 + 215 + 6, 11, 11, 0xffff00); if (duelNoPrayer) gameGraphics.drawBox(byte0 + 193, byte1 + 215 + 8, 7, 7, 0xffff00); gameGraphics.drawBoxEdge(byte0 + 191, byte1 + 215 + 25, 11, 11, 0xffff00); if (duelNoWeapons) gameGraphics.drawBox(byte0 + 193, byte1 + 215 + 27, 7, 7, 0xffff00); if (!duelMyAccepted) gameGraphics.drawPicture(byte0 + 217, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture(byte0 + 394, byte1 + 238, SPRITE_MEDIA_START + 26); if (duelOpponentAccepted) { gameGraphics.drawText("Other player", byte0 + 341, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("has accepted", byte0 + 341, byte1 + 256, 1, 0xffffff); } if (duelMyAccepted) { gameGraphics.drawText("Waiting for", byte0 + 217 + 35, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("other player", byte0 + 217 + 35, byte1 + 256, 1, 0xffffff); } for (int l4 = 0; l4 < inventoryCount; l4++) { int i5 = 217 + byte0 + (l4 % 5) * 49; int k5 = 31 + byte1 + (l4 / 5) * 34; gameGraphics.spriteClip4(i5, k5, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(getInventoryItems()[l4]) .getSprite(), EntityHandler.getItemDef(getInventoryItems()[l4]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(getInventoryItems()[l4]).isStackable()) gameGraphics.drawString( String.valueOf(inventoryItemsCount[l4]), i5 + 1, k5 + 10, 1, 0xffff00); } for (int j5 = 0; j5 < duelMyItemCount; j5++) { int l5 = 9 + byte0 + (j5 % 4) * 49; int j6 = 31 + byte1 + (j5 / 4) * 34; gameGraphics.spriteClip4(l5, j6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(duelMyItems[j5]).getSprite(), EntityHandler.getItemDef(duelMyItems[j5]).getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(duelMyItems[j5]).isStackable()) gameGraphics.drawString(String.valueOf(duelMyItemsCount[j5]), l5 + 1, j6 + 10, 1, 0xffff00); if (super.mouseX > l5 && super.mouseX < l5 + 48 && super.mouseY > j6 && super.mouseY < j6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(duelMyItems[j5]).getName() + ": @whi@" + EntityHandler.getItemDef(duelMyItems[j5]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } for (int i6 = 0; i6 < duelOpponentItemCount; i6++) { int k6 = 9 + byte0 + (i6 % 4) * 49; int l6 = 124 + byte1 + (i6 / 4) * 34; gameGraphics.spriteClip4(k6, l6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(duelOpponentItems[i6]) .getSprite(), EntityHandler.getItemDef(duelOpponentItems[i6]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(duelOpponentItems[i6]).isStackable()) gameGraphics.drawString( String.valueOf(duelOpponentItemsCount[i6]), k6 + 1, l6 + 10, 1, 0xffff00); if (super.mouseX > k6 && super.mouseX < k6 + 48 && super.mouseY > l6 && super.mouseY < l6 + 32) gameGraphics .drawString( EntityHandler.getItemDef(duelOpponentItems[i6]) .getName() + ": @whi@" + EntityHandler.getItemDef( duelOpponentItems[i6]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } } private final void drawServerMessageBox() { int c = '\u0190'; int c1 = 'd'; if (serverMessageBoxTop) { c1 = '\u01C2'; c1 = '\u012C'; } gameGraphics.drawBox(256 - c / 2 + xAddition, 167 - c1 / 2 + yAddition, c, c1, 0); gameGraphics.drawBoxEdge(256 - c / 2 + xAddition, 167 - c1 / 2 + yAddition, c, c1, 0xffffff); gameGraphics.drawBoxTextColour(serverMessage, 256 + xAddition, (167 - c1 / 2) + 20 + yAddition, 1, 0xffffff, c - 40); int i = 157 + c1 / 2 + yAddition; int j = 0xffffff; if (super.mouseY > i - 12 && super.mouseY <= i && super.mouseX > 106 + xAddition && super.mouseX < 406 + xAddition) j = 0xff0000; gameGraphics.drawText("Click here to close window", 256 + xAddition, i, 1, j); if (mouseButtonClick == 1) { if (j == 0xff0000) showServerMessageBox = false; if ((super.mouseX < 256 - c / 2 + xAddition || super.mouseX > 256 + c / 2 + xAddition) && (super.mouseY < 167 - c1 / 2 + yAddition || super.mouseY > 167 + c1 / 2 + yAddition)) showServerMessageBox = false; } mouseButtonClick = 0; } private final void makeLoginMenus() { menuWelcome = new Menu(gameGraphics, 50); int i = 40 + yAddition; menuWelcome.drawText(256 + xAddition, 200 + i, "Click on an option", 5, true); menuWelcome.drawBox(156 + xAddition, 240 + i, 120, 35); menuWelcome.drawBox(356 + xAddition, 240 + i, 120, 35); menuWelcome.drawText(156 + xAddition, 240 + i, "New User", 5, false); menuWelcome.drawText(356 + xAddition, 240 + i, "Existing User", 5, false); loginButtonNewUser = menuWelcome.makeButton(156 + xAddition, 240 + i, 120, 35); loginButtonExistingUser = menuWelcome.makeButton(356 + xAddition, 240 + i, 120, 35); menuNewUser = new Menu(gameGraphics, 50); i = 230 + yAddition; if (referId == 0) { menuNewUser.drawText(256 + xAddition, i + 8, "To create an account please go back to the", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "www.3hit.net", 4, true); } else if (referId == 1) { menuNewUser.drawText(256 + xAddition, i + 8, "then click account", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); } else { menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); } i += 30; menuNewUser.drawBox(256 + xAddition, i + 17, 150, 34); menuNewUser.drawText(256 + xAddition, i + 17, "Ok", 5, false); newUserOkButton = menuNewUser.makeButton(256 + xAddition, i + 17, 150, 34); menuLogin = new Menu(gameGraphics, 50); i = 230 + yAddition; loginStatusText = menuLogin.drawText(256 + xAddition, i - 10, "Please enter your username and password", 4, true); i += 28; menuLogin.drawBox(140 + xAddition, i, 200, 40); menuLogin.drawText(140 + xAddition, i - 10, "Username:", 4, false); loginUsernameTextBox = menuLogin.makeTextBox(140 + xAddition, i + 10, 200, 40, 4, 12, false, false); i += 47; menuLogin.drawBox(190 + xAddition, i, 200, 40); menuLogin.drawText(190 + xAddition, i - 10, "Password:", 4, false); loginPasswordTextBox = menuLogin.makeTextBox(190 + xAddition, i + 10, 200, 40, 4, 20, true, false); i -= 55; menuLogin.drawBox(410 + xAddition, i, 120, 25); menuLogin.drawText(410 + xAddition, i, "Play Now", 4, false); loginOkButton = menuLogin.makeButton(410 + xAddition, i, 120, 25); i += 30; menuLogin.drawBox(410 + xAddition, i, 120, 25); menuLogin.drawText(410 + xAddition, i, "Cancel", 4, false); loginCancelButton = menuLogin.makeButton(410 + xAddition, i, 120, 25); i += 30; menuLogin.setFocus(loginUsernameTextBox); } private final void drawGameWindowsMenus() { if (logoutTimeout != 0) drawLoggingOutBox(); else if (showWelcomeBox) drawWelcomeBox(); else if (showServerMessageBox) drawServerMessageBox(); else if (wildernessType == 1) // 0 = not wild, 1 = close to wild, 2 = // wild drawWildernessWarningBox(); else if (showBank && lastWalkTimeout == 0) drawBankBox(); else if (showShop && lastWalkTimeout == 0) drawShopBox(); else if (showTradeConfirmWindow) drawTradeConfirmWindow(); else if (showTradeWindow) drawTradeWindow(); else if (showDuelConfirmWindow) drawDuelConfirmWindow(); else if (showDuelWindow) drawDuelWindow(); else if (showAbuseWindow == 1) drawAbuseWindow1(); else if (showAbuseWindow == 2) drawAbuseWindow2(); else if (inputBoxType != 0) { drawInputBox(); } else { if (showQuestionMenu) drawQuestionMenu(); if ((ourPlayer.currentSprite == 8 || ourPlayer.currentSprite == 9) || combatWindow) drawCombatStyleWindow(); checkMouseOverMenus(); boolean noMenusShown = !showQuestionMenu && !showRightClickMenu; if (noMenusShown) menuLength = 0; if (mouseOverMenu == 0 && noMenusShown) drawInventoryRightClickMenu(); if (mouseOverMenu == 1) drawInventoryMenu(noMenusShown); if (mouseOverMenu == 2) drawMapMenu(noMenusShown); if (mouseOverMenu == 3) drawPlayerInfoMenu(noMenusShown); if (mouseOverMenu == 4) drawMagicWindow(noMenusShown); if (mouseOverMenu == 5) drawFriendsWindow(noMenusShown); if (mouseOverMenu == 6) drawOptionsMenu(noMenusShown); if (mouseOverMenu == 7) drawOurOptionsMenu(noMenusShown); if (!showRightClickMenu && !showQuestionMenu) checkMouseStatus(); if (showRightClickMenu && !showQuestionMenu) drawRightClickMenu(); } mouseButtonClick = 0; } public final void method112(int i, int j, int k, int l, boolean flag) { sendWalkCommand(i, j, k, l, k, l, false, flag); } private final void drawInputBox() { if (mouseButtonClick != 0) { mouseButtonClick = 0; if (inputBoxType == 1 && (super.mouseX < 106 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 406 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (inputBoxType == 2 && (super.mouseX < 6 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 506 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (inputBoxType == 3 && (super.mouseX < 106 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 406 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (super.mouseX > 236 + xAddition && super.mouseX < 276 + xAddition && super.mouseY > 193 + yAddition && super.mouseY < 213 + yAddition) { inputBoxType = 0; return; } } int i = 145 + yAddition; if (inputBoxType == 1) { gameGraphics.drawBox(106 + xAddition, i, 300, 70, 0); gameGraphics.drawBoxEdge(106 + xAddition, i, 300, 70, 0xffffff); i += 20; gameGraphics.drawText("Enter name to add to friends list", 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredText.length() > 0) { String s = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; inputBoxType = 0; if (s.length() > 0 && DataOperations.stringLength12ToLong(s) != ourPlayer.nameLong) addToFriendsList(s); } } if (inputBoxType == 2) { gameGraphics.drawBox(6 + xAddition, i, 500, 70, 0); gameGraphics.drawBoxEdge(6 + xAddition, i, 500, 70, 0xffffff); i += 20; gameGraphics .drawText( "Enter message to send to " + DataOperations .longToString(privateMessageTarget), 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputMessage + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredMessage.length() > 0) { String s1 = super.enteredMessage; super.inputMessage = ""; super.enteredMessage = ""; inputBoxType = 0; byte[] message = DataConversions.stringToByteArray(s1); sendPrivateMessage(privateMessageTarget, message, message.length); s1 = DataConversions.byteToString(message, 0, message.length); handleServerMessage("@pri@You tell " + DataOperations.longToString(privateMessageTarget) + ": " + s1); } } if (inputBoxType == 3) { gameGraphics.drawBox(106 + xAddition, i, 300, 70, 0); gameGraphics.drawBoxEdge(106 + xAddition, i, 300, 70, 0xffffff); i += 20; gameGraphics.drawText("Enter name to add to ignore list", 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredText.length() > 0) { String s2 = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; inputBoxType = 0; if (s2.length() > 0 && DataOperations.stringLength12ToLong(s2) != ourPlayer.nameLong) addToIgnoreList(s2); } } int j = 0xffffff; if (super.mouseX > 236 + xAddition && super.mouseX < 276 + xAddition && super.mouseY > 193 + yAddition && super.mouseY < 213 + yAddition) j = 0xffff00; gameGraphics.drawText("Cancel", 256 + xAddition, 208 + yAddition, 1, j); } private final boolean hasRequiredRunes(int i, int j) { if (i == 31 && (method117(197) || method117(615) || method117(682))) { return true; } if (i == 32 && (method117(102) || method117(616) || method117(683))) { return true; } if (i == 33 && (method117(101) || method117(617) || method117(684))) { return true; } if (i == 34 && (method117(103) || method117(618) || method117(685))) { return true; } return inventoryCount(i) >= j; } private final void resetPrivateMessageStrings() { super.inputMessage = ""; super.enteredMessage = ""; } private final boolean method117(int i) { for (int j = 0; j < inventoryCount; j++) if (getInventoryItems()[j] == i && wearing[j] == 1) return true; return false; } private final void setPixelsAndAroundColour(int x, int y, int colour) { gameGraphics.setPixelColour(x, y, colour); gameGraphics.setPixelColour(x - 1, y, colour); gameGraphics.setPixelColour(x + 1, y, colour); gameGraphics.setPixelColour(x, y - 1, colour); gameGraphics.setPixelColour(x, y + 1, colour); } private final void method119() { for (int i = 0; i < mobMessageCount; i++) { int j = gameGraphics.messageFontHeight(1); int l = mobMessagesX[i]; int k1 = mobMessagesY[i]; int j2 = mobMessagesWidth[i]; int i3 = mobMessagesHeight[i]; boolean flag = true; while (flag) { flag = false; for (int i4 = 0; i4 < i; i4++) if (k1 + i3 > mobMessagesY[i4] - j && k1 - j < mobMessagesY[i4] + mobMessagesHeight[i4] && l - j2 < mobMessagesX[i4] + mobMessagesWidth[i4] && l + j2 > mobMessagesX[i4] - mobMessagesWidth[i4] && mobMessagesY[i4] - j - i3 < k1) { k1 = mobMessagesY[i4] - j - i3; flag = true; } } mobMessagesY[i] = k1; gameGraphics.drawBoxTextColour(mobMessages[i], l, k1, 1, 0xffff00, 300); } for (int k = 0; k < anInt699; k++) { int i1 = anIntArray858[k]; int l1 = anIntArray859[k]; int k2 = anIntArray705[k]; int j3 = anIntArray706[k]; int l3 = (39 * k2) / 100; int j4 = (27 * k2) / 100; int k4 = l1 - j4; gameGraphics.spriteClip2(i1 - l3 / 2, k4, l3, j4, SPRITE_MEDIA_START + 9, 85); int l4 = (36 * k2) / 100; int i5 = (24 * k2) / 100; gameGraphics.spriteClip4(i1 - l4 / 2, (k4 + j4 / 2) - i5 / 2, l4, i5, EntityHandler.getItemDef(j3).getSprite() + SPRITE_ITEM_START, EntityHandler.getItemDef(j3) .getPictureMask(), 0, 0, false); } for (int j1 = 0; j1 < anInt718; j1++) { int i2 = anIntArray786[j1]; int l2 = anIntArray787[j1]; int k3 = anIntArray788[j1]; gameGraphics.drawBoxAlpha(i2 - 15, l2 - 3, k3, 5, 65280, 192); gameGraphics.drawBoxAlpha((i2 - 15) + k3, l2 - 3, 30 - k3, 5, 0xff0000, 192); } } private final void drawMapMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; char c = '\234'; char c2 = '\230'; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 2); i += 40; gameGraphics.drawBox(i, 36, c, c2, 0); gameGraphics.setDimensions(i, 36, i + c, 36 + c2); int k = 192 + anInt986; int i1 = cameraRotation + anInt985 & 0xff; int k1 = ((ourPlayer.currentX - 6040) * 3 * k) / 2048; int i3 = ((ourPlayer.currentY - 6040) * 3 * k) / 2048; int k4 = Camera.anIntArray384[1024 - i1 * 4 & 0x3ff]; int i5 = Camera.anIntArray384[(1024 - i1 * 4 & 0x3ff) + 1024]; int k5 = i3 * k4 + k1 * i5 >> 18; i3 = i3 * i5 - k1 * k4 >> 18; k1 = k5; gameGraphics.method242((i + c / 2) - k1, 36 + c2 / 2 + i3, SPRITE_MEDIA_START - 1, i1 + 64 & 0xff, k); for (int i7 = 0; i7 < objectCount; i7++) { int l1 = (((objectX[i7] * magicLoc + 64) - ourPlayer.currentX) * 3 * k) / 2048; int j3 = (((objectY[i7] * magicLoc + 64) - ourPlayer.currentY) * 3 * k) / 2048; int l5 = j3 * k4 + l1 * i5 >> 18; j3 = j3 * i5 - l1 * k4 >> 18; l1 = l5; setPixelsAndAroundColour(i + c / 2 + l1, (36 + c2 / 2) - j3, 65535); } for (int j7 = 0; j7 < groundItemCount; j7++) { int i2 = (((groundItemX[j7] * magicLoc + 64) - ourPlayer.currentX) * 3 * k) / 2048; int k3 = (((groundItemY[j7] * magicLoc + 64) - ourPlayer.currentY) * 3 * k) / 2048; int i6 = k3 * k4 + i2 * i5 >> 18; k3 = k3 * i5 - i2 * k4 >> 18; i2 = i6; setPixelsAndAroundColour(i + c / 2 + i2, (36 + c2 / 2) - k3, 0xff0000); } for (int k7 = 0; k7 < npcCount; k7++) { Mob mob = npcArray[k7]; int j2 = ((mob.currentX - ourPlayer.currentX) * 3 * k) / 2048; int l3 = ((mob.currentY - ourPlayer.currentY) * 3 * k) / 2048; int j6 = l3 * k4 + j2 * i5 >> 18; l3 = l3 * i5 - j2 * k4 >> 18; j2 = j6; setPixelsAndAroundColour(i + c / 2 + j2, (36 + c2 / 2) - l3, 0xffff00); } for (int l7 = 0; l7 < playerCount; l7++) { Mob mob_1 = playerArray[l7]; int k2 = ((mob_1.currentX - ourPlayer.currentX) * 3 * k) / 2048; int i4 = ((mob_1.currentY - ourPlayer.currentY) * 3 * k) / 2048; int k6 = i4 * k4 + k2 * i5 >> 18; i4 = i4 * i5 - k2 * k4 >> 18; k2 = k6; int j8 = 0xffffff; for (int k8 = 0; k8 < super.friendsCount; k8++) { if (mob_1.nameLong != super.friendsListLongs[k8] || super.friendsListOnlineStatus[k8] != 99) continue; j8 = 65280; break; } setPixelsAndAroundColour(i + c / 2 + k2, (36 + c2 / 2) - i4, j8); } gameGraphics.method212(i + c / 2, 36 + c2 / 2, 2, 0xffffff, 255); gameGraphics.method242(i + 19, 55, SPRITE_MEDIA_START + 24, cameraRotation + 128 & 0xff, 128); gameGraphics.setDimensions(0, 0, windowWidth, windowHeight + 12); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); int i8 = super.mouseY - 36; if (i >= 40 && i8 >= 0 && i < 196 && i8 < 152) { char c1 = '\234'; char c3 = '\230'; int l = 192 + anInt986; int j1 = cameraRotation + anInt985 & 0xff; int j = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; j += 40; int l2 = ((super.mouseX - (j + c1 / 2)) * 16384) / (3 * l); int j4 = ((super.mouseY - (36 + c3 / 2)) * 16384) / (3 * l); int l4 = Camera.anIntArray384[1024 - j1 * 4 & 0x3ff]; int j5 = Camera.anIntArray384[(1024 - j1 * 4 & 0x3ff) + 1024]; int l6 = j4 * l4 + l2 * j5 >> 15; j4 = j4 * j5 - l2 * l4 >> 15; l2 = l6; l2 += ourPlayer.currentX; j4 = ourPlayer.currentY - j4; if (mouseButtonClick == 1) method112(getSectionX(), getSectionY(), l2 / 128, j4 / 128, false); mouseButtonClick = 0; } } public mudclient() { for (int i = 0; i < questStage.length; i++) questStage[i] = (byte) 0; combatWindow = false; threadSleepTime = 10; try { localhost = InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { e.printStackTrace(); localhost = "unknown"; } if (config.getProperty("width") == null) { Config.storeConfig("width", "502"); } if (config.getProperty("height") == null) { Config.storeConfig("height", "382"); } if (config.getProperty("refreshRate") == null) { Config.storeConfig("refreshRate", "" + Resolutions.oldDisplayMode.getRefreshRate()); } if (config.getProperty("bitDepth") == null) { Config.storeConfig("bitDepth", "" + Resolutions.oldDisplayMode.getBitDepth()); } windowWidth = Integer.valueOf(config.getProperty("width")); windowHeight = Integer.valueOf(config.getProperty("height")) - 40; screenDepth = Integer.valueOf(config.getProperty("bitDepth")); screenRefreshRate = Integer.valueOf(config.getProperty("refreshRate")); if (windowWidth < defaultWidth || windowHeight < defaultHeight) { windowWidth = defaultWidth; Config.storeConfig("width", "502"); windowHeight = defaultHeight; Config.storeConfig("height", "382"); } if (windowWidth > 532) { xAddition = (windowWidth - defaultWidth) / 2; yAddition = (windowHeight - defaultHeight) / 2; } else { xAddition = 0; yAddition = 0; } startTime = System.currentTimeMillis(); duelMyItems = new int[8]; duelMyItemsCount = new int[8]; configAutoCameraAngle = true; questionMenuAnswer = new String[10]; lastNpcArray = new Mob[500]; currentUser = ""; currentPass = ""; menuText1 = new String[250]; duelOpponentAccepted = false; duelMyAccepted = false; tradeConfirmItems = new int[14]; tradeConfirmItemsCount = new int[14]; tradeConfirmOtherItems = new int[14]; tradeConfirmOtherItemsCount = new int[14]; serverMessage = ""; duelOpponentName = ""; setInventoryItems(new int[35]); inventoryItemsCount = new int[35]; wearing = new int[35]; mobMessages = new String[50]; showBank = false; doorModel = new Model[500]; mobMessagesX = new int[50]; mobMessagesY = new int[50]; mobMessagesWidth = new int[50]; mobMessagesHeight = new int[50]; npcArray = new Mob[500]; equipmentStatus = new int[6]; prayerOn = new boolean[50]; tradeOtherAccepted = false; tradeWeAccepted = false; mobArray = new Mob[8000]; anIntArray705 = new int[50]; anIntArray706 = new int[50]; lastWildYSubtract = -1; memoryError = false; bankItemsMax = 48; showQuestionMenu = false; magicLoc = 128; cameraAutoAngle = 1; anInt727 = 2; showServerMessageBox = false; hasReceivedWelcomeBoxDetails = false; playerStatCurrent = new int[18]; wildYSubtract = -1; anInt742 = -1; anInt743 = -1; anInt744 = -1; sectionXArray = new int[8000]; sectionYArray = new int[8000]; selectedItem = -1; selectedItemName = ""; duelOpponentItems = new int[8]; duelOpponentItemsCount = new int[8]; anIntArray757 = new int[50]; menuID = new int[250]; showCharacterLookScreen = false; showDrawPointsScreen = false; lastPlayerArray = new Mob[500]; appletMode = true; gameDataModels = new Model[1000]; configMouseButtons = false; duelNoRetreating = false; duelNoMagic = false; duelNoPrayer = false; duelNoWeapons = false; anIntArray782 = new int[50]; duelConfirmOpponentItems = new int[8]; duelConfirmOpponentItemsCount = new int[8]; anIntArray786 = new int[50]; anIntArray787 = new int[50]; anIntArray788 = new int[50]; objectModelArray = new Model[1500]; cameraRotation = 128; showWelcomeBox = false; characterBodyGender = 1; character2Colour = 2; characterHairColour = 2; characterTopColour = 8; characterBottomColour = 14; characterHeadGender = 1; selectedBankItem = -1; selectedBankItemType = -2; menuText2 = new String[250]; aBooleanArray827 = new boolean[1500]; playerStatBase = new int[18]; menuActionType = new int[250]; menuActionVariable = new int[250]; menuActionVariable2 = new int[250]; shopItems = new int[256]; shopItemCount = new int[256]; shopItemsSellPrice = new int[256]; shopItemsBuyPrice = new int[256]; anIntArray858 = new int[50]; anIntArray859 = new int[50]; newBankItems = new int[256]; newBankItemsCount = new int[256]; duelConfirmMyItems = new int[8]; duelConfirmMyItemsCount = new int[8]; mobArrayIndexes = new int[500]; messagesTimeout = new int[5]; objectX = new int[1500]; objectY = new int[1500]; objectType = new int[1500]; objectID = new int[1500]; menuActionX = new int[250]; menuActionY = new int[250]; ourPlayer = new Mob(); serverIndex = -1; anInt882 = 30; showTradeConfirmWindow = false; tradeConfirmAccepted = false; playerArray = new Mob[500]; serverMessageBoxTop = false; cameraHeight = 750; bankItems = new int[256]; bankItemsCount = new int[256]; notInWilderness = false; selectedSpell = -1; anInt911 = 2; tradeOtherItems = new int[14]; tradeOtherItemsCount = new int[14]; menuIndexes = new int[250]; zoomCamera = false; playerStatExperience = new int[18]; cameraAutoAngleDebug = false; npcRecordArray = new Mob[8000]; showDuelWindow = false; anIntArray923 = new int[50]; lastLoadedNull = false; experienceArray = new int[99]; showShop = false; mouseClickXArray = new int[8192]; mouseClickYArray = new int[8192]; showDuelConfirmWindow = false; duelWeAccept = false; doorX = new int[500]; doorY = new int[500]; configSoundEffects = false; showRightClickMenu = false; attackingInt40 = 40; anIntArray944 = new int[50]; doorDirection = new int[500]; doorType = new int[500]; groundItemX = new int[8000]; groundItemY = new int[8000]; groundItemType = new int[8000]; groundItemObjectVar = new int[8000]; selectedShopItemIndex = -1; selectedShopItemType = -2; messagesArray = new String[5]; showTradeWindow = false; aBooleanArray970 = new boolean[500]; tradeMyItems = new int[14]; tradeMyItemsCount = new int[14]; cameraSizeInt = 9; tradeOtherPlayerName = ""; mc = this; } private boolean combatWindow; private int lastLoggedInDays; private int subscriptionLeftDays; private int duelMyItemCount; private int duelMyItems[]; private int duelMyItemsCount[]; private boolean configAutoCameraAngle; private String questionMenuAnswer[]; private int anInt658; private Mob lastNpcArray[]; private int loginButtonNewUser; private int loginButtonExistingUser; private String currentUser; private String currentPass; private int lastWalkTimeout; private String menuText1[]; private boolean duelOpponentAccepted; private boolean duelMyAccepted; private int tradeConfirmItemCount; private int tradeConfirmItems[]; private int tradeConfirmItemsCount[]; private int tradeConfirmOtherItemCount; private int tradeConfirmOtherItems[]; private int tradeConfirmOtherItemsCount[]; static String serverMessage; private String duelOpponentName; private int mouseOverBankPageText; public int playerCount; private int lastPlayerCount; private int fightCount; private int inventoryCount; private int inventoryItems[]; private int inventoryItemsCount[]; private int wearing[]; private int mobMessageCount; String mobMessages[]; private boolean showBank; private Model doorModel[]; private int mobMessagesX[]; private int mobMessagesY[]; private int mobMessagesWidth[]; private int mobMessagesHeight[]; public Mob npcArray[]; private int equipmentStatus[]; private final int characterTopBottomColours[] = { 0xff0000, 0xff8000, 0xffe000, 0xa0e000, 57344, 32768, 41088, 45311, 33023, 12528, 0xe000e0, 0x303030, 0x604000, 0x805000, 0xffffff }; private int loginScreenNumber; private int anInt699; private boolean prayerOn[]; private boolean tradeOtherAccepted; private boolean tradeWeAccepted; private Mob mobArray[]; private int npcCombatModelArray1[] = { 0, 1, 2, 1, 0, 0, 0, 0 }; private int anIntArray705[]; private int anIntArray706[]; public int npcCount; private int lastNpcCount; private int wildX; private int wildY; private int wildYMultiplier; private int lastWildYSubtract; private boolean memoryError; private int bankItemsMax; private int mouseOverMenu; private int walkModel[] = { 0, 1, 2, 1 }; private boolean showQuestionMenu; private int anInt718; public int magicLoc; public int loggedIn; private int cameraAutoAngle; private int cameraRotationBaseAddition; private Menu spellMenu; int spellMenuHandle; int menuMagicPrayersSelected; private int screenRotationX; private int anInt727; private int showAbuseWindow; private int duelCantRetreat; private int duelUseMagic; private int duelUsePrayer; private int duelUseWeapons; static boolean showServerMessageBox; private boolean hasReceivedWelcomeBoxDetails; private String lastLoggedInAddress; private int loginTimer; private int playerStatCurrent[]; private int areaX; private int areaY; private int wildYSubtract; private int anInt742; private int anInt743; private int anInt744; public int sectionXArray[]; public int sectionYArray[]; private int selectedItem; String selectedItemName; private int menuX; private int menuY; private int menuWidth; private int menuHeight; private int menuLength; private int duelOpponentItemCount; private int duelOpponentItems[]; private int duelOpponentItemsCount[]; private int anIntArray757[]; private int menuID[]; private boolean showCharacterLookScreen; private boolean showDrawPointsScreen; private int newBankItemCount; private int npcCombatModelArray2[] = { 0, 0, 0, 0, 0, 1, 2, 1 }; private Mob lastPlayerArray[]; private int inputBoxType; private boolean appletMode; private int combatStyle; private Model gameDataModels[]; private boolean configMouseButtons; private boolean duelNoRetreating; private boolean duelNoMagic; private boolean duelNoPrayer; private boolean duelNoWeapons; private int anIntArray782[]; private int duelConfirmOpponentItemCount; private int duelConfirmOpponentItems[]; private int duelConfirmOpponentItemsCount[]; private int anIntArray786[]; private int anIntArray787[]; private int anIntArray788[]; private int anInt789; private int anInt790; private int anInt791; private int anInt792; private Menu menuLogin; private final int characterHairColours[] = { 0xffc030, 0xffa040, 0x805030, 0x604020, 0x303030, 0xff6020, 0xff4000, 0xffffff, 65280, 65535 }; private Model objectModelArray[]; private Menu menuWelcome; private int systemUpdate; private int cameraRotation; private int logoutTimeout; private Menu gameMenu; // Wilderness int messagesHandleType2; int chatHandle; int messagesHandleType5; int messagesHandleType6; int messagesTab; private boolean showWelcomeBox; private int characterHeadType; private int characterBodyGender; private int character2Colour; private int characterHairColour; private int characterTopColour; private int characterBottomColour; private int characterSkinColour; private int characterHeadGender; // shopItems private int loginStatusText; private int loginUsernameTextBox; private int loginPasswordTextBox; private int loginOkButton; private int loginCancelButton; private int selectedBankItem; private int selectedBankItemType; private String menuText2[]; int anInt826; private boolean aBooleanArray827[]; private int playerStatBase[]; private int abuseSelectedType; public int actionPictureType; int actionPictureX; int actionPictureY; private int menuActionType[]; private int menuActionVariable[]; private int menuActionVariable2[]; private int shopItems[]; private int shopItemCount[]; private int shopItemsBuyPrice[]; private int shopItemsSellPrice[]; private byte[] x = new byte[] { 111, 114, 103, 46, 114, 115, 99, 97, 110, 103, 101, 108, 46, 99, 108, 105, 101, 110, 116, 46, 109, 117, 100, 99, 108, 105, 101, 110, 116, 46, 99, 104, 101, 99, 107, 77, 111, 117, 115, 101, 83, 116, 97, 116, 117, 115, 40, 41 }; private byte[] y = new byte[] { 111, 114, 103, 46, 114, 115, 99, 97, 110, 103, 101, 108, 46, 99, 108, 105, 101, 110, 116, 46, 109, 117, 100, 99, 108, 105, 101, 110, 116, 46, 100, 114, 97, 119, 82, 105, 103, 104, 116, 67, 108, 105, 99, 107, 77, 101, 110, 117, 40, 41 }; private int npcAnimationArray[][] = { { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3, 4 }, { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3, 4 }, { 11, 3, 2, 9, 7, 1, 6, 10, 0, 5, 8, 4 }, { 3, 4, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 3, 4, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 4, 3, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 11, 4, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3 }, { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 4, 3 } }; private int bankItemCount; private int strDownButton; private int atkDownButton; private int defDownButton; private int magDownButton; private int rangeDownButton; private int strUpButton; private int atkUpButton; private int defUpButton; private int magUpButton; private int rangeUpButton; private int dPSAcceptButton; public static final int[] pkexperienceArray = { 83, 174, 276, 388, 512, 650, 801, 969, 1154, 1358, 1584, 1833, 2107, 2411, 2746, 3115, 3523, 3973, 4470, 5018, 5624, 6291, 7028, 7842, 8740, 9730, 10824, 12031, 13363, 14833, 16456, 18247, 20224, 22406, 24815, 27473, 30408, 33648, 37224, 41171, 45529, 50339, 55649, 61512, 67983, 75127, 83014, 91721, 101333, 111945, 123660, 136594, 150872, 166636, 184040, 203254, 224466, 247886, 273742, 302288, 333804, 368599, 407015, 449428, 496254, 547953, 605032, 668051, 737627, 814445, 899257, 992895, 1096278, 1210421, 1336443, 1475581, 1629200, 1798808, 1986068, 2192818, 2421087, 2673114, 2951373, 3258594, 3597792, 3972294, 4385776, 4842295, 5346332, 5902831, 6517253, 7195629, 7944614, 8771558, 9684577, 10692629, 11805606, 13034431, 14391160 }; private int pkmagic, pkrange, pkatk, pkdef, pkstr = 1; private long pkpoints = 0; private int pkmagictext, pkcombattext, pkpointstext, pkrangetext, pkatktext, pkdeftext, pkstrtext = 0; private boolean pkreset = true; private int characterDesignHeadButton1; private int characterDesignHeadButton2; private int characterDesignHairColourButton1; private int characterDesignHairColourButton2; private int characterDesignGenderButton1; private int characterDesignGenderButton2; private int characterDesignTopColourButton1; private int characterDesignTopColourButton2; private int characterDesignSkinColourButton1; private int characterDesignSkinColourButton2; private int characterDesignBottomColourButton1; private int characterDesignBottomColourButton2; private int characterDesignAcceptButton; private int anIntArray858[]; private int anIntArray859[]; private int newBankItems[]; private int newBankItemsCount[]; private int duelConfirmMyItemCount; private int duelConfirmMyItems[]; private int duelConfirmMyItemsCount[]; private int mobArrayIndexes[]; private Menu menuNewUser; private int messagesTimeout[]; private int lastAutoCameraRotatePlayerX; private int lastAutoCameraRotatePlayerY; private int questionMenuCount; public int objectX[]; public int objectY[]; public int objectType[]; private int objectID[]; private int menuActionX[]; private int menuActionY[]; public Mob ourPlayer; private int sectionX; private int sectionY; int serverIndex; private int anInt882; private int mouseDownTime; private int itemIncrement; public int groundItemCount; private int modelFireLightningSpellNumber; private int modelTorchNumber; private int modelClawSpellNumber; private boolean showTradeConfirmWindow; private boolean tradeConfirmAccepted; private int anInt892; public EngineHandle engineHandle; public Mob playerArray[];// Stats private boolean serverMessageBoxTop; private final String equipmentStatusName[] = { "Armour", "WeaponAim", "WeaponPower", "Magic", "Prayer", "Range" }; public int flagged = 0; private int referId; private int anInt900; private int newUserOkButton; private int mouseButtonClick; private int cameraHeight; private int bankItems[]; private int bankItemsCount[]; private boolean notInWilderness; private int selectedSpell; private int screenRotationY; private int anInt911; private int tradeOtherItemCount; private int tradeOtherItems[]; private int tradeOtherItemsCount[]; private int menuIndexes[]; private boolean zoomCamera; private AudioReader audioReader; private int playerStatExperience[]; private boolean cameraAutoAngleDebug; private Mob npcRecordArray[]; private final String skillArray[] = { "Attack", "Defense", "Strength", "Hits", "Ranged", "Prayer", "Magic", "Cooking", "Woodcut", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblaw", "Agility", "Thieving" }; private boolean showDuelWindow; private int anIntArray923[]; public GameImageMiddleMan gameGraphics; private final String skillArrayLong[] = { "Attack", "Defense", "Strength", "Hitpoints", "Ranged", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblaw", "Agility", "Thieving" }; private boolean lastLoadedNull; private int experienceArray[]; private Camera gameCamera; private boolean showShop; private int mouseClickArrayOffset; int mouseClickXArray[]; int mouseClickYArray[]; private boolean showDuelConfirmWindow; private boolean duelWeAccept; private Graphics aGraphics936; private int doorX[]; private int doorY[]; private int wildernessType; private boolean configSoundEffects; private boolean showRightClickMenu; private int screenRotationTimer; private int attackingInt40; private int anIntArray944[]; private Menu characterDesignMenu; private Menu drawPointsScreen; private int shopItemSellPriceModifier; private int shopItemBuyPriceModifier; private int modelUpdatingTimer; private int doorCount; private int doorDirection[]; private int doorType[]; private int anInt952; private int anInt953; private int anInt954; private int anInt955; public int groundItemX[]; public int groundItemY[]; public int groundItemType[]; private int groundItemObjectVar[]; private int selectedShopItemIndex; private int selectedShopItemType; private String messagesArray[]; private long tradeConfirmOtherNameLong; private boolean showTradeWindow; private int playerAliveTimeout; private final int characterSkinColours[] = { 0xecded0, 0xccb366, 0xb38c40, 0x997326, 0x906020 }; private byte sounds[]; // 3150 private boolean aBooleanArray970[]; public int objectCount; private int tradeMyItemCount; private int tradeMyItems[]; private int tradeMyItemsCount[]; public int windowWidth = 512; public int windowHeight = 334; public int screenDepth; public int screenRefreshRate; int defaultWidth = 512; int defaultHeight = 334; public int xAddition; public int yAddition; private int cameraSizeInt; private Menu friendsMenu; int friendsMenuHandle; int anInt981; long privateMessageTarget; private long duelOpponentNameLong; private String tradeOtherPlayerName; private int anInt985; private int anInt986; private boolean aBoolean767; // humuliat public final static void drawDownloadProgress(String s, int progress, boolean download) { try { int j = (appletWidth - 281) / 2; int k = (appletHeight - 148) / 2; j += 2 + 4; k += 122; // BAR_COLOUR int l = (281 * progress) / 100; getLoadingGraphics().setColor(BAR_COLOUR); getLoadingGraphics().fillRect(j, k, l, 20); getLoadingGraphics().setColor(Color.black); getLoadingGraphics().fillRect(j + l, k, 281 - l, 20); getLoadingGraphics().setColor(Color.WHITE); getLoadingGraphics().drawString( (download ? "Downloading: " : "") + s + " " + progress + "%", j + (download ? 54 : 54), k + 14); } catch (Exception _ex) { } } public static File getFile(String filename) { File file = new File(Config.CONF_DIR + File.separator + filename); if (file.isFile() && file.exists()) { return file; } else return null; } public void setSectionX(int sectionX) { this.sectionX = sectionX; } public int getSectionX() { return sectionX; } public void setSectionY(int sectionY) { this.sectionY = sectionY; } public int getSectionY() { return sectionY; } public void setAreaY(int areaY) { this.areaY = areaY; } public int getAreaY() { return areaY; } public void setAreaX(int areaX) { this.areaX = areaX; } public int getAreaX() { return areaX; } public static void drawPopup(String message) { serverMessage = message; showServerMessageBox = true; } public void sendSmithingItem(int spriteID) { streamClass.createPacket(201); streamClass.add4ByteInt(spriteID); streamClass.formatPacket(); } public void sendSmithingClose() { streamClass.createPacket(202); streamClass.formatPacket(); } public void setInventoryItems(int inventoryItems[]) { this.inventoryItems = inventoryItems; } public int[] getInventoryItems() { return inventoryItems; } }
false
true
private final void drawGame() throws Exception { cur_fps++; if (System.currentTimeMillis() - lastFps < 0) { lastFps = System.currentTimeMillis(); } if (System.currentTimeMillis() - lastFps >= 1000) { fps = cur_fps; cur_fps = 0; lastFps = System.currentTimeMillis(); } // sleepTime = (int) ((long) threadSleepModifier - (l1 - // currentTimeArray[i]) / 10L); /* * long now = System.currentTimeMillis(); if (now - lastFrame > (1000 / * Config.MOVIE_FPS) && recording) { try { lastFrame = now; * frames.add(getImage()); } catch (Exception e) { e.printStackTrace(); * } } */ if (playerAliveTimeout != 0) { gameGraphics.fadePixels(); gameGraphics.drawText("Oh dear! You are dead...", windowWidth / 2, windowHeight / 2, 7, 0xff0000); drawChatMessageTabs(); drawOurSpritesOnScreen(); gameGraphics.drawImage(aGraphics936, 0, 0); return; } if (sleeping) { boolean drawEquation = true; // gameGraphics.fadePixels(); // if(Math.random() < 0.14999999999999999D) // gameGraphics.drawText("ZZZ", (int)(Math.random() * 80D), // (int)(Math.random() * (double)windowHeight), 5, // (int)(Math.random() * 16777215D)); // if(Math.random() < 0.14999999999999999D) // gameGraphics.drawText("ZZZ", windowWidth - (int)(Math.random() * // 80D), (int)(Math.random() * (double)windowHeight), 5, // (int)(Math.random() * 16777215D)); // gameGraphics.drawBox(windowWidth / 2 - 100, 160, 200, 40, 0); // gameGraphics.drawText("You are sleeping", windowWidth / 2, 50, 7, // 0xffff00); // gameGraphics.drawText("Fatigue: " + (tfatigue * 100) / 750 + "%", // windowWidth / 2, 90, 7, 0xffff00); // gameGraphics.drawText("When you want to wake up just use your", // windowWidth / 2, 140, 5, 0xffffff); // gameGraphics.drawText("keyboard to type the solution in the box below", // windowWidth / 2, 160, 5, 0xffffff); // gameGraphics.drawText(super.inputText + "*", windowWidth / 2, // 180, 5, 65535); // if(sleepMessage != null) { // gameGraphics.drawText(sleepMessage, windowWidth / 2, 260, 5, // 0xff0000); // drawEquation = false; // } // gameGraphics.drawBoxEdge(windowWidth / 2 - 128, 229, 257, 42, // 0xffffff); // drawChatMessageTabs(); // gameGraphics.drawText("If you can't read the equation", // windowWidth / 2, 290, 1, 0xffffff); // gameGraphics.drawText("@yel@click here@whi@ to get a different one", // windowWidth / 2, 305, 1, 0xffffff); // gameGraphics.drawImage(aGraphics936, 0, 0); if (drawEquation && sleepEquation != null) { gameGraphics.drawImage(aGraphics936, 0, 0, fixSleeping(sleepEquation)); // gameGraphics.drawImage(aGraphics936, windowWidth / 2 - 127, // 230, fixSleeping(sleepEquation)); } return; } if (showDrawPointsScreen) { showDPS(); return; } if (showCharacterLookScreen) { method62(); return; }// fog if (!engineHandle.playerIsAlive) { return; } for (int i = 0; i < 64; i++) { gameCamera .removeModel(engineHandle.aModelArrayArray598[lastWildYSubtract][i]); if (lastWildYSubtract == 0) { gameCamera.removeModel(engineHandle.aModelArrayArray580[1][i]); gameCamera.removeModel(engineHandle.aModelArrayArray598[1][i]); gameCamera.removeModel(engineHandle.aModelArrayArray580[2][i]); gameCamera.removeModel(engineHandle.aModelArrayArray598[2][i]); } zoomCamera = true; if (lastWildYSubtract == 0 && (engineHandle.walkableValue[ourPlayer.currentX / 128][ourPlayer.currentY / 128] & 0x80) == 0) { if (showRoof) { gameCamera .addModel(engineHandle.aModelArrayArray598[lastWildYSubtract][i]); if (lastWildYSubtract == 0) { gameCamera .addModel(engineHandle.aModelArrayArray580[1][i]); gameCamera .addModel(engineHandle.aModelArrayArray598[1][i]); gameCamera .addModel(engineHandle.aModelArrayArray580[2][i]); gameCamera .addModel(engineHandle.aModelArrayArray598[2][i]); } } zoomCamera = false; } } if (modelFireLightningSpellNumber != anInt742) { anInt742 = modelFireLightningSpellNumber; for (int j = 0; j < objectCount; j++) { if (objectType[j] == 97) method98(j, "firea" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 274) method98(j, "fireplacea" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1031) method98(j, "lightning" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1036) method98(j, "firespell" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1147) method98(j, "spellcharge" + (modelFireLightningSpellNumber + 1)); } } if (modelTorchNumber != anInt743) { anInt743 = modelTorchNumber; for (int k = 0; k < objectCount; k++) { if (objectType[k] == 51) method98(k, "torcha" + (modelTorchNumber + 1)); if (objectType[k] == 143) method98(k, "skulltorcha" + (modelTorchNumber + 1)); } } if (modelClawSpellNumber != anInt744) { anInt744 = modelClawSpellNumber; for (int l = 0; l < objectCount; l++) if (objectType[l] == 1142) method98(l, "clawspell" + (modelClawSpellNumber + 1)); } gameCamera.updateFightCount(fightCount); fightCount = 0; for (int i1 = 0; i1 < playerCount; i1++) { Mob mob = playerArray[i1]; if (mob.colourBottomType != 255) { int k1 = mob.currentX; int i2 = mob.currentY; int k2 = -engineHandle.getAveragedElevation(k1, i2); int l3 = gameCamera.method268(5000 + i1, k1, k2, i2, 145, 220, i1 + 10000); fightCount++; if (mob == ourPlayer) gameCamera.setOurPlayer(l3); if (mob.currentSprite == 8) gameCamera.setCombat(l3, -30); if (mob.currentSprite == 9) gameCamera.setCombat(l3, 30); } } for (int j1 = 0; j1 < playerCount; j1++) { Mob player = playerArray[j1]; if (player.anInt176 > 0) { Mob npc = null; if (player.attackingNpcIndex != -1) npc = npcRecordArray[player.attackingNpcIndex]; else if (player.attackingMobIndex != -1) npc = mobArray[player.attackingMobIndex]; if (npc != null) { int px = player.currentX; int py = player.currentY; int pi = -engineHandle.getAveragedElevation(px, py) - 110; int nx = npc.currentX; int ny = npc.currentY; int ni = -engineHandle.getAveragedElevation(nx, ny) - EntityHandler.getNpcDef(npc.type).getCamera2() / 2; int i10 = (px * player.anInt176 + nx * (attackingInt40 - player.anInt176)) / attackingInt40; int j10 = (pi * player.anInt176 + ni * (attackingInt40 - player.anInt176)) / attackingInt40; int k10 = (py * player.anInt176 + ny * (attackingInt40 - player.anInt176)) / attackingInt40; gameCamera.method268(SPRITE_PROJECTILE_START + player.attackingCameraInt, i10, j10, k10, 32, 32, 0); fightCount++; } } } for (int l1 = 0; l1 < npcCount; l1++) { Mob npc = npcArray[l1]; int mobx = npc.currentX; int moby = npc.currentY; int i7 = -engineHandle.getAveragedElevation(mobx, moby); int i9 = gameCamera.method268(20000 + l1, mobx, i7, moby, EntityHandler.getNpcDef(npc.type).getCamera1(), EntityHandler.getNpcDef(npc.type).getCamera2(), l1 + 30000); fightCount++; if (npc.currentSprite == 8) gameCamera.setCombat(i9, -30); if (npc.currentSprite == 9) gameCamera.setCombat(i9, 30); } if (LOOT_ENABLED) { for (int j2 = 0; j2 < groundItemCount; j2++) { int j3 = groundItemX[j2] * magicLoc + 64; int k4 = groundItemY[j2] * magicLoc + 64; gameCamera.method268(40000 + groundItemType[j2], j3, -engineHandle.getAveragedElevation(j3, k4) - groundItemObjectVar[j2], k4, 96, 64, j2 + 20000); fightCount++; } }// if (systemUpdate != 0) { for (int k3 = 0; k3 < anInt892; k3++) { int l4 = anIntArray944[k3] * magicLoc + 64; int j7 = anIntArray757[k3] * magicLoc + 64; int j9 = anIntArray782[k3]; if (j9 == 0) { gameCamera.method268(50000 + k3, l4, -engineHandle.getAveragedElevation(l4, j7), j7, 128, 256, k3 + 50000); fightCount++; } if (j9 == 1) { gameCamera.method268(50000 + k3, l4, -engineHandle.getAveragedElevation(l4, j7), j7, 128, 64, k3 + 50000); fightCount++; } } gameGraphics.f1Toggle = false; gameGraphics.method211(); gameGraphics.f1Toggle = super.keyF1Toggle; if (lastWildYSubtract == 3) { int i5 = 40 + (int) (Math.random() * 3D); int k7 = 40 + (int) (Math.random() * 7D); gameCamera.method304(i5, k7, -50, -10, -50); } anInt699 = 0; mobMessageCount = 0; anInt718 = 0; if (cameraAutoAngleDebug) { if (configAutoCameraAngle && !zoomCamera) { int lastCameraAutoAngle = cameraAutoAngle; autoRotateCamera(); if (cameraAutoAngle != lastCameraAutoAngle) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } } if (fog) { gameCamera.zoom1 = 3000 + fogVar; gameCamera.zoom2 = 3000 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2800 + fogVar; } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } cameraRotation = cameraAutoAngle * 32; int k5 = lastAutoCameraRotatePlayerX + screenRotationX; int l7 = lastAutoCameraRotatePlayerY + screenRotationY; gameCamera.setCamera(k5, -engineHandle.getAveragedElevation(k5, l7), l7, cameraVertical, cameraRotation * 4, 0, 2000); } else { if (configAutoCameraAngle && !zoomCamera) autoRotateCamera(); if (fog) { if (!super.keyF1Toggle) { gameCamera.zoom1 = 2400 + fogVar; gameCamera.zoom2 = 2400 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2300 + fogVar; } else { gameCamera.zoom1 = 2200; gameCamera.zoom2 = 2200; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2100; } } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } int l5 = lastAutoCameraRotatePlayerX + screenRotationX; int i8 = lastAutoCameraRotatePlayerY + screenRotationY; gameCamera.setCamera(l5, -engineHandle.getAveragedElevation(l5, i8), i8, cameraVertical, cameraRotation * 4, 0, cameraHeight * 2); } gameCamera.finishCamera(); /* * e.printStackTrace(); System.out.println("Camera error: " + e); * cameraHeight = 750; cameraVertical = 920; fogVar = 0; */ method119(); if (actionPictureType > 0) gameGraphics.drawPicture(actionPictureX - 8, actionPictureY - 8, SPRITE_MEDIA_START + 14 + (24 - actionPictureType) / 6); if (actionPictureType < 0) gameGraphics.drawPicture(actionPictureX - 8, actionPictureY - 8, SPRITE_MEDIA_START + 18 + (24 + actionPictureType) / 6); try { MessageQueue.getQueue().checkProcessMessages(); int height = 55; if (MessageQueue.getQueue().hasMessages()) { for (Message m : MessageQueue.getQueue().getList()) { if (m.isBIG) continue; gameGraphics.drawString(m.message, 8, height, 1, 0xffff00); height += 12; } for (Message m : MessageQueue.getQueue().getList()) { if (m.isBIG) { gameGraphics.drawString(m.message, 120, 100, 7, 0xffff00); } } } } catch (Exception e) { e.printStackTrace(); } if (systemUpdate != 0) { int i6 = systemUpdate / 50; int j8 = i6 / 60; i6 %= 60; if (i6 < 10)// redflag gameGraphics.drawText("System update in: " + j8 + ":0" + i6, 256 + xAddition, windowHeight - 7, 1, 0xffff00); else gameGraphics.drawText("System update in: " + j8 + ":" + i6, 256 + xAddition, windowHeight - 7, 1, 0xffff00); } // #pmd# if (!notInWilderness) { int j6 = 2203 - (getSectionY() + wildY + getAreaY()); if (getSectionX() + wildX + getAreaX() >= 2640) j6 = -50; if (j6 > 0) { int k8 = 1 + j6 / 6; gameGraphics.drawPicture(windowWidth - 50, windowHeight - 56, SPRITE_MEDIA_START + 13); int minx = 12; int maxx = 91; int miny = 4; int maxy = 33; // command == 1 int ourX = (getSectionX() + getAreaX()); int ourY = (getSectionY() + getAreaY()); if (ourX > minx && ourX < maxx && ourY > miny && ourY < maxy) { gameGraphics.drawText("@whi@CTF", windowWidth - 40, windowHeight - 20, 1, 0xffff00); gameGraphics.drawText("@red@Red: @whi@" + GameWindowMiddleMan.redPoints + " @blu@Blue: @whi@" + GameWindowMiddleMan.bluePoints, windowWidth - 40, windowHeight - 7, 1, 0xffff00); } else { // Coords: gameGraphics.drawText("Wilderness", windowWidth - 40, windowHeight - 20, 1, 0xffff00); gameGraphics.drawText("Level: " + k8, windowWidth - 40, windowHeight - 7, 1, 0xffff00); } if (wildernessType == 0) wildernessType = 2; } if (wildernessType == 0 && j6 > -10 && j6 <= 0) wildernessType = 1; } if (messagesTab == 0) { for (int k6 = 0; k6 < messagesArray.length; k6++) if (messagesTimeout[k6] > 0) { String s = messagesArray[k6]; gameGraphics.drawString(s, 7, windowHeight - 18 - k6 * 12, 1, 0xffff00); } } gameMenu.method171(messagesHandleType2); gameMenu.method171(messagesHandleType5); gameMenu.method171(messagesHandleType6); if (messagesTab == 1) gameMenu.method170(messagesHandleType2); else if (messagesTab == 2) gameMenu.method170(messagesHandleType5); else if (messagesTab == 3) gameMenu.method170(messagesHandleType6); Menu.anInt225 = 2; gameMenu.drawMenu(); Menu.anInt225 = 0; gameGraphics.method232( ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 197, 3, SPRITE_MEDIA_START, 128); drawGameWindowsMenus(); gameGraphics.drawStringShadows = false; drawChatMessageTabs(); drawOurSpritesOnScreen(); InterfaceHandler.tick(); gameGraphics.drawImage(aGraphics936, 0, 0); } /** * Draws our sprites on screen when needed */ private void drawOurSpritesOnScreen() { if (mouseOverMenu != 7) gameGraphics.drawBoxAlpha( ((GameImage) (gameGraphics)).menuDefaultWidth - 232, 3, 31, 32, GameImage.convertRGBToLong(181, 181, 181), 128); gameGraphics.drawPicture(windowWidth - 240, 2, SPRITE_ITEM_START + EntityHandler.getItemDef(167).getSprite()); } private final void drawRightClickMenu() { if (mouseButtonClick != 0) { for (int i = 0; i < menuLength; i++) { int k = menuX + 2; int i1 = menuY + 27 + i * 15; if (super.mouseX <= k - 2 || super.mouseY <= i1 - 12 || super.mouseY >= i1 + 4 || super.mouseX >= (k - 3) + menuWidth) continue; menuClick(menuIndexes[i]); break; } mouseButtonClick = 0; showRightClickMenu = false; return; } if (super.mouseX < menuX - 10 || super.mouseY < menuY - 10 || super.mouseX > menuX + menuWidth + 10 || super.mouseY > menuY + menuHeight + 10) { showRightClickMenu = false; return; } gameGraphics.drawBoxAlpha(menuX, menuY, menuWidth, menuHeight, 0xd0d0d0, 160); gameGraphics.drawString("Choose option", menuX + 2, menuY + 12, 1, 65535); for (int j = 0; j < menuLength; j++) { int l = menuX + 2; int j1 = menuY + 27 + j * 15; int k1 = 0xffffff; if (super.mouseX > l - 2 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && super.mouseX < (l - 3) + menuWidth) k1 = 0xffff00; gameGraphics.drawString(menuText1[menuIndexes[j]] + " " + menuText2[menuIndexes[j]], l, j1, 1, k1); } } protected final void resetIntVars() { systemUpdate = 0; loginScreenNumber = 0; loggedIn = 0; logoutTimeout = 0; for (int i = 0; i < questStage.length; i++) questStage[i] = 0; questPoints = 0; } private final void drawQuestionMenu() { if (mouseButtonClick != 0) { for (int i = 0; i < questionMenuCount; i++) { if (super.mouseX >= gameGraphics.textWidth( questionMenuAnswer[i], 1) || super.mouseY <= i * 12 || super.mouseY >= 12 + i * 12) continue; super.streamClass.createPacket(154); super.streamClass.addByte(i); super.streamClass.formatPacket(); break; } mouseButtonClick = 0; showQuestionMenu = false; return; } for (int j = 0; j < questionMenuCount; j++) { int k = 65535; if (super.mouseX < gameGraphics.textWidth(questionMenuAnswer[j], 1) && super.mouseY > j * 12 && super.mouseY < 12 + j * 12) k = 0xff0000; gameGraphics .drawString(questionMenuAnswer[j], 6, 12 + j * 12, 1, k); // KO9 breaking! // questionmenu.Questions[j] = questionMenuAnswer[j]; } // questionmenu.isVisible = true; } private final void walkToAction(int actionX, int actionY, int actionType) { if (actionType == 0) { sendWalkCommand(getSectionX(), getSectionY(), actionX, actionY - 1, actionX, actionY, false, true); return; } if (actionType == 1) { sendWalkCommand(getSectionX(), getSectionY(), actionX - 1, actionY, actionX, actionY, false, true); return; } else { sendWalkCommand(getSectionX(), getSectionY(), actionX, actionY, actionX, actionY, true, true); return; } } private final void garbageCollect() { try { if (gameGraphics != null) { gameGraphics.cleanupSprites(); gameGraphics.imagePixelArray = null; gameGraphics = null; } if (gameCamera != null) { gameCamera.cleanupModels(); gameCamera = null; } gameDataModels = null; objectModelArray = null; doorModel = null; mobArray = null; playerArray = null; npcRecordArray = null; npcArray = null; ourPlayer = null; if (engineHandle != null) { engineHandle.aModelArray596 = null; engineHandle.aModelArrayArray580 = null; engineHandle.aModelArrayArray598 = null; engineHandle.aModel = null; engineHandle = null; } System.gc(); return; } catch (Exception _ex) { return; } } protected final void loginScreenPrint(String s, String s1) { if (loginScreenNumber == 1) menuNewUser.updateText(anInt900, s + " " + s1); if (loginScreenNumber == 2) menuLogin.updateText(loginStatusText, s + " " + s1); drawLoginScreen(); resetCurrentTimeArray(); } private final void drawInventoryRightClickMenu() { int i = 2203 - (getSectionY() + wildY + getAreaY()); if (getSectionX() + wildX + getAreaX() >= 2640) i = -50; int j = -1; for (int k = 0; k < objectCount; k++) aBooleanArray827[k] = false; for (int l = 0; l < doorCount; l++) aBooleanArray970[l] = false; int i1 = gameCamera.method272(); Model models[] = gameCamera.getVisibleModels(); int ai[] = gameCamera.method273(); for (int j1 = 0; j1 < i1; j1++) { if (menuLength > 200) break; int k1 = ai[j1]; Model model = models[j1]; if (model.anIntArray258[k1] <= 65535 || model.anIntArray258[k1] >= 0x30d40 && model.anIntArray258[k1] <= 0x493e0) if (model == gameCamera.aModel_423) { int i2 = model.anIntArray258[k1] % 10000; int l2 = model.anIntArray258[k1] / 10000; if (l2 == 1) { String s = ""; int k3 = 0; if (ourPlayer.level > 0 && playerArray[i2].level > 0) k3 = ourPlayer.level - playerArray[i2].level; if (k3 < 0) s = "@or1@"; if (k3 < -3) s = "@or2@"; if (k3 < -6) s = "@or3@"; if (k3 < -9) s = "@red@"; if (k3 > 0) s = "@gr1@"; if (k3 > 3) s = "@gr2@"; if (k3 > 6) s = "@gr3@"; if (k3 > 9) s = "@gre@"; s = " " + s + "(level-" + playerArray[i2].level + ")"; if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 1 || EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 2) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 800; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 810; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { // Max hit if (i > 0 && (playerArray[i2].currentY - 64) / magicLoc + wildY + getAreaY() < 2203) { menuText1[menuLength] = "Attack"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; if (k3 >= 0 && k3 < 5) menuID[menuLength] = 805; else menuID[menuLength] = 2805; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } else { menuText1[menuLength] = "Duel with"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + "@whi@" + playerArray[i2].name + s; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuID[menuLength] = 2806; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Trade with"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 2810; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; menuText1[menuLength] = "Follow"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 2820; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } } else if (l2 == 2) { ItemDef itemDef = EntityHandler .getItemDef(groundItemType[i2]); if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 3) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 200; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 210; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { menuText1[menuLength] = "Take"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 220; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuLength++; menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@lre@" + itemDef.getName() + (ourPlayer.admin >= 1 ? " @or1@(" + groundItemType[i2] + ":" + (groundItemX[i2] + getAreaX()) + "," + (groundItemY[i2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3200; menuActionType[menuLength] = groundItemType[i2]; menuLength++; } } else if (l2 == 3) { String s1 = ""; int l3 = -1; NPCDef npcDef = EntityHandler .getNpcDef(npcArray[i2].type); if (npcDef.isAttackable()) { int j4 = (npcDef.getAtt() + npcDef.getDef() + npcDef.getStr() + npcDef.getHits()) / 4; int k4 = (playerStatBase[0] + playerStatBase[1] + playerStatBase[2] + playerStatBase[3] + 27) / 4; l3 = k4 - j4; s1 = "@yel@"; if (l3 < 0) s1 = "@or1@"; if (l3 < -3) s1 = "@or2@"; if (l3 < -6) s1 = "@or3@"; if (l3 < -9) s1 = "@red@"; if (l3 > 0) s1 = "@gr1@"; if (l3 > 3) s1 = "@gr2@"; if (l3 > 6) s1 = "@gr3@"; if (l3 > 9) s1 = "@gre@"; s1 = " " + s1 + "(level-" + j4 + ")"; } if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 2) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 700; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 710; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { if (npcDef.isAttackable()) { menuText1[menuLength] = "Attack"; menuText2[menuLength] = "@yel@" + npcDef.getName() + s1; if (l3 >= 0) menuID[menuLength] = 715; else menuID[menuLength] = 2715; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Talk-to"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 720; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; if (!npcDef.getCommand().equals("")) { menuText1[menuLength] = npcDef.getCommand(); menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 725; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@yel@" + npcDef.getName() + (ourPlayer.admin >= 1 ? " @or1@(" + npcArray[i2].type + ")" : ""); menuID[menuLength] = 3700; menuActionType[menuLength] = npcArray[i2].type; menuLength++; } }// "Skills } else if (model != null && model.anInt257 >= 10000) { int j2 = model.anInt257 - 10000; int i3 = doorType[j2]; if (!aBooleanArray970[j2]) { if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 4) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 300; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3).getName(); menuID[menuLength] = 310; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { if (!EntityHandler.getDoorDef(i3).getCommand1() .equalsIgnoreCase("WalkTo")) { menuText1[menuLength] = EntityHandler .getDoorDef(i3).getCommand1(); menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 320; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuLength++; } if (!EntityHandler.getDoorDef(i3).getCommand2() .equalsIgnoreCase("Examine")) { menuText1[menuLength] = EntityHandler .getDoorDef(i3).getCommand2(); menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 2300; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3).getName() + (ourPlayer.admin >= 1 ? " @or1@(" + i3 + ":" + (doorX[j2] + getAreaX()) + "," + (doorY[j2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3300; menuActionType[menuLength] = i3; menuLength++; } aBooleanArray970[j2] = true; } } else if (model != null && model.anInt257 >= 0) { int k2 = model.anInt257; int j3 = objectType[k2]; if (!aBooleanArray827[k2]) { if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 5) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 400; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuActionVariable2[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3).getName(); menuID[menuLength] = 410; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuActionVariable2[menuLength] = selectedItem; menuLength++; } else { if (!EntityHandler.getObjectDef(j3).getCommand1() .equalsIgnoreCase("WalkTo")) { menuText1[menuLength] = EntityHandler .getObjectDef(j3).getCommand1(); menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 420; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuLength++; } if (!EntityHandler.getObjectDef(j3).getCommand2() .equalsIgnoreCase("Examine")) { menuText1[menuLength] = EntityHandler .getObjectDef(j3).getCommand2(); menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 2400; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3).getName() + (ourPlayer.admin >= 1 ? " @or1@(" + j3 + ":" + (objectX[k2] + getAreaX()) + "," + (objectY[k2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3400; menuActionType[menuLength] = j3; menuLength++; } aBooleanArray827[k2] = true; } } else { if (k1 >= 0) k1 = model.anIntArray258[k1] - 0x30d40; if (k1 >= 0) j = k1; } } if (selectedSpell >= 0 && EntityHandler.getSpellDef(selectedSpell).getSpellType() <= 1) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef(selectedSpell).getName() + " on self"; menuText2[menuLength] = ""; menuID[menuLength] = 1000; menuActionType[menuLength] = selectedSpell; menuLength++; } if (j != -1) { int l1 = j; if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell).getSpellType() == 6) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef(selectedSpell) .getName() + " on ground"; menuText2[menuLength] = ""; menuID[menuLength] = 900; menuActionX[menuLength] = engineHandle.selectedX[l1]; menuActionY[menuLength] = engineHandle.selectedY[l1]; menuActionType[menuLength] = selectedSpell; menuLength++; return; } } else if (selectedItem < 0) { menuText1[menuLength] = "Walk here"; menuText2[menuLength] = ""; menuID[menuLength] = 920; menuActionX[menuLength] = engineHandle.selectedX[l1]; menuActionY[menuLength] = engineHandle.selectedY[l1]; menuLength++; } } } protected final void startGame() { int i = 0; for (int j = 0; j < 99; j++) { int k = j + 1; int i1 = (int) ((double) k + 300D * Math.pow(2D, (double) k / 7D)); i += i1; experienceArray[j] = (i & 0xffffffc) / 4; } super.yOffset = 0; GameWindowMiddleMan.maxPacketReadCount = 500; if (appletMode) { CacheManager.load("Loading.rscd"); setLogo(Toolkit.getDefaultToolkit().getImage( Config.CONF_DIR + File.separator + "Loading.rscd")); } loadConfigFilter(); // 15% if (lastLoadedNull) { return; } aGraphics936 = getGraphics(); changeThreadSleepModifier(50); gameGraphics = new GameImageMiddleMan(windowWidth, windowHeight + 12, 4000, this); gameGraphics._mudclient = this; GameFrame.setClient(mc); GameWindow.setClient(this); gameGraphics.setDimensions(0, 0, windowWidth, windowHeight + 12); Menu.aBoolean220 = false; /* Menu.anInt221 = anInt902; */ spellMenu = new Menu(gameGraphics, 5); int l = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; spellMenuHandle = spellMenu.method162(l, byte0 + 24, 196, 90, 1, 500, true); friendsMenu = new Menu(gameGraphics, 5); friendsMenuHandle = friendsMenu.method162(l, byte0 + 40, 196, 126, 1, 500, true); questMenu = new Menu(gameGraphics, 5); questMenuHandle = questMenu.method162(l, byte0 + 40, 196, 235, 1, 500, true); loadMedia(); // 30% if (lastLoadedNull) return; loadEntity(); // 45% if (lastLoadedNull) return; gameCamera = new Camera(gameGraphics, 15000, 15000, 1000); gameCamera.setCameraSize(windowWidth / 2, windowHeight / 2, windowWidth / 2, windowHeight / 2, windowWidth, cameraSizeInt); if (fog) { gameCamera.zoom1 = 2400 + fogVar; gameCamera.zoom2 = 2400 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2300 + fogVar; } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } gameCamera.method303(-50, -10, -50); engineHandle = new EngineHandle(gameCamera, gameGraphics); loadTextures(); // 60% if (lastLoadedNull) return; loadModels(); // 75% if (lastLoadedNull) return; loadSounds(); // 90% if (lastLoadedNull) return; CacheManager.doneLoading(); drawDownloadProgress("Starting game...", 100, false); drawGameMenu(); makeLoginMenus(); makeCharacterDesignMenu(); makeDPSMenu(); resetLoginVars(); menusLoaded = true; } private final void loadSprite(int id, String packageName, int amount) { for (int i = id; i < id + amount; i++) { if (!gameGraphics.loadSprite(i, packageName)) { lastLoadedNull = true; return; } } } private final void loadMedia() { drawDownloadProgress("Unpacking media", 30, false); loadSprite(SPRITE_MEDIA_START, "media", 1); loadSprite(SPRITE_MEDIA_START + 1, "media", 6); loadSprite(SPRITE_MEDIA_START + 9, "media", 1); loadSprite(SPRITE_MEDIA_START + 10, "media", 1); loadSprite(SPRITE_MEDIA_START + 11, "media", 3); loadSprite(SPRITE_MEDIA_START + 14, "media", 8); loadSprite(SPRITE_MEDIA_START + 22, "media", 1); loadSprite(SPRITE_MEDIA_START + 23, "media", 1); loadSprite(SPRITE_MEDIA_START + 24, "media", 1); loadSprite(SPRITE_MEDIA_START + 25, "media", 2); loadSprite(SPRITE_UTIL_START, "media", 2); loadSprite(SPRITE_UTIL_START + 2, "media", 4); loadSprite(SPRITE_UTIL_START + 6, "media", 2); loadSprite(SPRITE_PROJECTILE_START, "media", 7); loadSprite(SPRITE_LOGO_START, "media", 1); int i = EntityHandler.invPictureCount(); for (int j = 1; i > 0; j++) { int k = i; i -= 30; if (k > 30) { k = 30; } loadSprite(SPRITE_ITEM_START + (j - 1) * 30, "media.object", k); } } private final void loadEntity() { drawDownloadProgress("Unpacking entities", 45, false); int animationNumber = 0; label0: for (int animationIndex = 0; animationIndex < EntityHandler .animationCount(); animationIndex++) { String s = EntityHandler.getAnimationDef(animationIndex).getName(); for (int nextAnimationIndex = 0; nextAnimationIndex < animationIndex; nextAnimationIndex++) { if (!EntityHandler.getAnimationDef(nextAnimationIndex) .getName().equalsIgnoreCase(s)) { continue; } EntityHandler.getAnimationDef(animationIndex).number = EntityHandler .getAnimationDef(nextAnimationIndex).getNumber(); continue label0; } loadSprite(animationNumber, "entity", 15); if (EntityHandler.getAnimationDef(animationIndex).hasA()) { loadSprite(animationNumber + 15, "entity", 3); } if (EntityHandler.getAnimationDef(animationIndex).hasF()) { loadSprite(animationNumber + 18, "entity", 9); } EntityHandler.getAnimationDef(animationIndex).number = animationNumber; animationNumber += 27; } } private final void loadTextures() { drawDownloadProgress("Unpacking textures", 60, false); gameCamera.method297(EntityHandler.textureCount(), 7, 11); for (int i = 0; i < EntityHandler.textureCount(); i++) { loadSprite(SPRITE_TEXTURE_START + i, "texture", 1); Sprite sprite = ((GameImage) (gameGraphics)).sprites[SPRITE_TEXTURE_START + i]; int length = sprite.getWidth() * sprite.getHeight(); int[] pixels = sprite.getPixels(); int ai1[] = new int[32768]; for (int k = 0; k < length; k++) { ai1[((pixels[k] & 0xf80000) >> 9) + ((pixels[k] & 0xf800) >> 6) + ((pixels[k] & 0xf8) >> 3)]++; } int[] dictionary = new int[256]; dictionary[0] = 0xff00ff; int[] temp = new int[256]; for (int i1 = 0; i1 < ai1.length; i1++) { int j1 = ai1[i1]; if (j1 > temp[255]) { for (int k1 = 1; k1 < 256; k1++) { if (j1 <= temp[k1]) { continue; } for (int i2 = 255; i2 > k1; i2--) { dictionary[i2] = dictionary[i2 - 1]; temp[i2] = temp[i2 - 1]; } dictionary[k1] = ((i1 & 0x7c00) << 9) + ((i1 & 0x3e0) << 6) + ((i1 & 0x1f) << 3) + 0x40404; temp[k1] = j1; break; } } ai1[i1] = -1; } byte[] indices = new byte[length]; for (int l1 = 0; l1 < length; l1++) { int j2 = pixels[l1]; int k2 = ((j2 & 0xf80000) >> 9) + ((j2 & 0xf800) >> 6) + ((j2 & 0xf8) >> 3); int l2 = ai1[k2]; if (l2 == -1) { int i3 = 0x3b9ac9ff; int j3 = j2 >> 16 & 0xff; int k3 = j2 >> 8 & 0xff; int l3 = j2 & 0xff; for (int i4 = 0; i4 < 256; i4++) { int j4 = dictionary[i4]; int k4 = j4 >> 16 & 0xff; int l4 = j4 >> 8 & 0xff; int i5 = j4 & 0xff; int j5 = (j3 - k4) * (j3 - k4) + (k3 - l4) * (k3 - l4) + (l3 - i5) * (l3 - i5); if (j5 < i3) { i3 = j5; l2 = i4; } } ai1[k2] = l2; } indices[l1] = (byte) l2; } gameCamera.method298(i, indices, dictionary, sprite.getSomething1() / 64 - 1); } } /* * private int lastMouseButton = -1; private int lastMouseX = -1; private * int lastMouseY = -1; private double camVert = 0.0D; private double camRot * = 0.0D; private java.awt.Robot robot; protected final void * handleMouseDrag(MouseEvent mouse, int x, int y, int button) { * if(controlDown && button == 2) { int unitX = x - lastMouseX; * * if(unitX > 1) unitX = 1; else if(unitX < -1) unitX = -1; * * int unitY = lastMouseY - y; * * if(unitY > 1) unitY = 1; else if(unitY < -1) unitY = -1; * * cameraVertical += unitY; //cameraRotation += unitX; * * System.out.println("Y: " + y + ", LastY: " + lastMouseY + " dif: (" + (y * - lastMouseY) + ")"); * * lastMouseX = x; lastMouseY = y; //super.mouseX = lastMouseX; * //super.mouseY = lastMouseY; //robot.mouseMove(super.mouseX, * super.mouseY); } } */ private final void checkMouseStatus() { /* * lastMouseX = * (int)java.awt.MouseInfo.getPointerInfo().getLocation().getX(); * lastMouseY = * (int)java.awt.MouseInfo.getPointerInfo().getLocation().getY(); * lastMouseButton = mouseButtonClick; * * if(mouseButtonClick == 2 && controlDown) return; */ if (selectedSpell >= 0 || selectedItem >= 0) { menuText1[menuLength] = "Cancel"; menuText2[menuLength] = ""; menuID[menuLength] = 4000; menuLength++; } for (int i = 0; i < menuLength; i++) menuIndexes[i] = i; for (boolean flag = false; !flag;) { flag = true; for (int j = 0; j < menuLength - 1; j++) { int l = menuIndexes[j]; int j1 = menuIndexes[j + 1]; if (menuID[l] > menuID[j1]) { menuIndexes[j] = j1; menuIndexes[j + 1] = l; flag = false; } } } if (menuLength > 20) menuLength = 20; if (menuLength > 0) { int k = -1; for (int i1 = 0; i1 < menuLength; i1++) { if (menuText2[menuIndexes[i1]] == null || menuText2[menuIndexes[i1]].length() <= 0) continue; k = i1; break; } String s = null; if ((selectedItem >= 0 || selectedSpell >= 0) && menuLength == 1) s = "Choose a target"; else if ((selectedItem >= 0 || selectedSpell >= 0) && menuLength > 1) s = "@whi@" + menuText1[menuIndexes[0]] + " " + menuText2[menuIndexes[0]]; else if (k != -1) s = menuText2[menuIndexes[k]] + ": @whi@" + menuText1[menuIndexes[0]]; if (menuLength == 2 && s != null) s = s + "@whi@ / 1 more option"; if (menuLength > 2 && s != null) s = s + "@whi@ / " + (menuLength - 1) + " more options"; if (s != null) gameGraphics.drawString(s, 6, 14, 1, 0xffff00); if (!configMouseButtons && mouseButtonClick == 1 || configMouseButtons && mouseButtonClick == 1 && menuLength == 1) { menuClick(menuIndexes[0]); mouseButtonClick = 0; return; } if (!configMouseButtons && mouseButtonClick == 2 || configMouseButtons && mouseButtonClick == 1) { menuHeight = (menuLength + 1) * 15; menuWidth = gameGraphics.textWidth("Choose option", 1) + 5; for (int k1 = 0; k1 < menuLength; k1++) { int l1 = gameGraphics.textWidth(menuText1[k1] + " " + menuText2[k1], 1) + 5; if (l1 > menuWidth) menuWidth = l1; } menuX = super.mouseX - menuWidth / 2; menuY = super.mouseY - 7; showRightClickMenu = true; if (menuX < 0) menuX = 0; if (menuY < 0) menuY = 0; if (menuX + menuWidth > (windowWidth - 10)) menuX = (windowWidth - 10) - menuWidth; if (menuY + menuHeight > (windowHeight)) menuY = (windowHeight - 10) - menuHeight; mouseButtonClick = 0; } } } protected final void cantLogout() { logoutTimeout = 0; displayMessage("@cya@Sorry, you can't logout at the moment", 3, 0); } private final void drawFriendsWindow(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 5); char c = '\304'; char c1 = '\266'; int l; int k = l = GameImage.convertRGBToLong(160, 160, 160); if (anInt981 == 0) k = GameImage.convertRGBToLong(220, 220, 220); else l = GameImage.convertRGBToLong(220, 220, 220); int maxWidth = windowWidth - 23; int minWidth = windowWidth - 83; gameGraphics.drawBoxAlpha(i, j, c / 2, 24, k, 128); gameGraphics.drawBoxAlpha(i + c / 2, j, c / 2, 24, l, 128); gameGraphics.drawBoxAlpha(i, j + 24, c, c1 - 24, GameImage.convertRGBToLong(220, 220, 220), 128); gameGraphics.drawLineX(i, j + 24, c, 0); gameGraphics.drawLineY(i + c / 2, j, 24, 0); gameGraphics.drawLineX(i, (j + c1) - 16, c, 0); gameGraphics.drawText("Friends", i + c / 4, j + 16, 4, 0); gameGraphics.drawText("Ignore", i + c / 4 + c / 2, j + 16, 4, 0); friendsMenu.resetListTextCount(friendsMenuHandle); if (anInt981 == 0) { for (int i1 = 0; i1 < super.friendsCount; i1++) { String s; if (super.friendsListOnlineStatus[i1] == 99) s = "@gre@"; else if (super.friendsListOnlineStatus[i1] > 0) s = "@yel@"; else s = "@red@"; friendsMenu .drawMenuListText( friendsMenuHandle, i1, s + DataOperations .longToString(super.friendsListLongs[i1]) + "~" + (windowWidth - 73) + "~" + "@whi@Remove WWWWWWWWWW"); } } if (anInt981 == 1) { for (int j1 = 0; j1 < super.ignoreListCount; j1++) friendsMenu .drawMenuListText( friendsMenuHandle, j1, "@yel@" + DataOperations .longToString(super.ignoreListLongs[j1]) + "~" + (windowWidth - 73) + "~" + "@whi@Remove WWWWWWWWWW"); } friendsMenu.drawMenu(); if (anInt981 == 0) { int k1 = friendsMenu.selectedListIndex(friendsMenuHandle); if (k1 >= 0 && super.mouseX < maxWidth) { if (super.mouseX > minWidth) gameGraphics .drawText( "Click to remove " + DataOperations .longToString(super.friendsListLongs[k1]), i + c / 2, j + 35, 1, 0xffffff); else if (super.friendsListOnlineStatus[k1] == 99) gameGraphics .drawText( "Click to message " + DataOperations .longToString(super.friendsListLongs[k1]), i + c / 2, j + 35, 1, 0xffffff); else if (super.friendsListOnlineStatus[k1] > 0) gameGraphics.drawText( DataOperations .longToString(super.friendsListLongs[k1]) + " is on world " + super.friendsListOnlineStatus[k1], i + c / 2, j + 35, 1, 0xffffff); else gameGraphics.drawText( DataOperations .longToString(super.friendsListLongs[k1]) + " is offline", i + c / 2, j + 35, 1, 0xffffff); } else gameGraphics.drawText("Click a name to send a message", i + c / 2, j + 35, 1, 0xffffff); int k2; if (super.mouseX > i && super.mouseX < i + c && super.mouseY > (j + c1) - 16 && super.mouseY < j + c1) k2 = 0xffff00; else k2 = 0xffffff; gameGraphics.drawText("Click here to add a friend", i + c / 2, (j + c1) - 3, 1, k2); } if (anInt981 == 1) { int l1 = friendsMenu.selectedListIndex(friendsMenuHandle); if (l1 >= 0 && super.mouseX < maxWidth && super.mouseX > minWidth) { if (super.mouseX > minWidth) gameGraphics .drawText( "Click to remove " + DataOperations .longToString(super.ignoreListLongs[l1]), i + c / 2, j + 35, 1, 0xffffff); } else { gameGraphics.drawText("Blocking messages from:", i + c / 2, j + 35, 1, 0xffffff); } int l2; if (super.mouseX > i && super.mouseX < i + c && super.mouseY > (j + c1) - 16 && super.mouseY < j + c1) l2 = 0xffff00; else l2 = 0xffffff; gameGraphics.drawText("Click here to add a name", i + c / 2, (j + c1) - 3, 1, l2); } if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 182) { friendsMenu.updateActions(i + (((GameImage) (gameGraphics)).menuDefaultWidth - 199), j + 36, super.lastMouseDownButton, super.mouseDownButton); if (j <= 24 && mouseButtonClick == 1) if (i < 98 && anInt981 == 1) { anInt981 = 0; friendsMenu.method165(friendsMenuHandle, 0); } else if (i > 98 && anInt981 == 0) { anInt981 = 1; friendsMenu.method165(friendsMenuHandle, 0); } if (mouseButtonClick == 1 && anInt981 == 0) { int i2 = friendsMenu.selectedListIndex(friendsMenuHandle); if (i2 >= 0 && super.mouseX < maxWidth) if (super.mouseX > minWidth) removeFromFriends(super.friendsListLongs[i2]); else if (super.friendsListOnlineStatus[i2] != 0) { inputBoxType = 2; privateMessageTarget = super.friendsListLongs[i2]; super.inputMessage = ""; super.enteredMessage = ""; } } if (mouseButtonClick == 1 && anInt981 == 1) { int j2 = friendsMenu.selectedListIndex(friendsMenuHandle); if (j2 >= 0 && super.mouseX < maxWidth && super.mouseX > minWidth) removeFromIgnoreList(super.ignoreListLongs[j2]); } if (j > 166 && mouseButtonClick == 1 && anInt981 == 0) { inputBoxType = 1; super.inputText = ""; super.enteredText = ""; } if (j > 166 && mouseButtonClick == 1 && anInt981 == 1) { inputBoxType = 3; super.inputText = ""; super.enteredText = ""; } mouseButtonClick = 0; } } private final boolean loadSection(int i, int j) { if (playerAliveTimeout != 0) { engineHandle.playerIsAlive = false; return false; } notInWilderness = false; i += wildX; j += wildY; if (lastWildYSubtract == wildYSubtract && i > anInt789 && i < anInt791 && j > anInt790 && j < anInt792) { engineHandle.playerIsAlive = true; return false; } gameGraphics.drawText("Loading... Please wait", 256 + xAddition, 192 + yAddition, 1, 0xffffff); drawChatMessageTabs(); drawOurSpritesOnScreen(); gameGraphics.drawImage(aGraphics936, 0, 0); int k = getAreaX(); int l = getAreaY(); int i1 = (i + 24) / 48; int j1 = (j + 24) / 48; lastWildYSubtract = wildYSubtract; setAreaX(i1 * 48 - 48); setAreaY(j1 * 48 - 48); anInt789 = i1 * 48 - 32; anInt790 = j1 * 48 - 32; anInt791 = i1 * 48 + 32; anInt792 = j1 * 48 + 32; engineHandle.method401(i, j, lastWildYSubtract); setAreaX(getAreaX() - wildX); setAreaY(getAreaY() - wildY); int k1 = getAreaX() - k; int l1 = getAreaY() - l; for (int i2 = 0; i2 < objectCount; i2++) { objectX[i2] -= k1; objectY[i2] -= l1; int j2 = objectX[i2]; int l2 = objectY[i2]; int k3 = objectType[i2]; int m4 = objectID[i2]; Model model = objectModelArray[i2]; try { int l4 = objectID[i2]; int k5; int i6; if (l4 == 0 || l4 == 4) { k5 = EntityHandler.getObjectDef(k3).getWidth(); i6 = EntityHandler.getObjectDef(k3).getHeight(); } else { i6 = EntityHandler.getObjectDef(k3).getWidth(); k5 = EntityHandler.getObjectDef(k3).getHeight(); } int j6 = ((j2 + j2 + k5) * magicLoc) / 2; int k6 = ((l2 + l2 + i6) * magicLoc) / 2; if (j2 >= 0 && l2 >= 0 && j2 < 96 && l2 < 96) { gameCamera.addModel(model); model.method191(j6, -engineHandle.getAveragedElevation(j6, k6), k6); engineHandle.method412(j2, l2, k3, m4); if (k3 == 74) model.method190(0, -480, 0); } } catch (RuntimeException runtimeexception) { System.out.println("Loc Error: " + runtimeexception.getMessage()); System.out.println("i:" + i2 + " obj:" + model); runtimeexception.printStackTrace(); } } for (int k2 = 0; k2 < doorCount; k2++) { doorX[k2] -= k1; doorY[k2] -= l1; int i3 = doorX[k2]; int l3 = doorY[k2]; int j4 = doorType[k2]; int i5 = doorDirection[k2]; try { engineHandle.method408(i3, l3, i5, j4); Model model_1 = makeModel(i3, l3, i5, j4, k2); doorModel[k2] = model_1; } catch (RuntimeException runtimeexception1) { System.out.println("Bound Error: " + runtimeexception1.getMessage()); runtimeexception1.printStackTrace(); } } for (int j3 = 0; j3 < groundItemCount; j3++) { groundItemX[j3] -= k1; groundItemY[j3] -= l1; } for (int i4 = 0; i4 < playerCount; i4++) { Mob mob = playerArray[i4]; mob.currentX -= k1 * magicLoc; mob.currentY -= l1 * magicLoc; for (int j5 = 0; j5 <= mob.waypointCurrent; j5++) { mob.waypointsX[j5] -= k1 * magicLoc; mob.waypointsY[j5] -= l1 * magicLoc; } } for (int k4 = 0; k4 < npcCount; k4++) { Mob mob_1 = npcArray[k4]; mob_1.currentX -= k1 * magicLoc; mob_1.currentY -= l1 * magicLoc; for (int l5 = 0; l5 <= mob_1.waypointCurrent; l5++) { mob_1.waypointsX[l5] -= k1 * magicLoc; mob_1.waypointsY[l5] -= l1 * magicLoc; } } engineHandle.playerIsAlive = true; return true; } private final void drawMagicWindow(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 4); char c = '\304'; char c1 = '\266'; int l; int k = l = GameImage.convertRGBToLong(160, 160, 160); if (menuMagicPrayersSelected == 0) k = GameImage.convertRGBToLong(220, 220, 220); else l = GameImage.convertRGBToLong(220, 220, 220); gameGraphics.drawBoxAlpha(i, j, c / 2, 24, k, 128); gameGraphics.drawBoxAlpha(i + c / 2, j, c / 2, 24, l, 128); gameGraphics.drawBoxAlpha(i, j + 24, c, 90, GameImage.convertRGBToLong(220, 220, 220), 128); gameGraphics.drawBoxAlpha(i, j + 24 + 90, c, c1 - 90 - 24, GameImage.convertRGBToLong(160, 160, 160), 128); gameGraphics.drawLineX(i, j + 24, c, 0); gameGraphics.drawLineY(i + c / 2, j, 24, 0); gameGraphics.drawLineX(i, j + 113, c, 0); gameGraphics.drawText("Magic", i + c / 4, j + 16, 4, 0); gameGraphics.drawText("Prayers", i + c / 4 + c / 2, j + 16, 4, 0); if (menuMagicPrayersSelected == 0) { spellMenu.resetListTextCount(spellMenuHandle); int i1 = 0; for (int spellIndex = 0; spellIndex < EntityHandler.spellCount(); spellIndex++) { String s = "@yel@"; for (Entry e : EntityHandler.getSpellDef(spellIndex) .getRunesRequired()) { if (hasRequiredRunes((Integer) e.getKey(), (Integer) e.getValue())) { continue; } s = "@whi@"; break; } int spellLevel = playerStatCurrent[6]; if (EntityHandler.getSpellDef(spellIndex).getReqLevel() > spellLevel) { s = "@bla@"; } spellMenu.drawMenuListText(spellMenuHandle, i1++, s + "Level " + EntityHandler.getSpellDef(spellIndex).getReqLevel() + ": " + EntityHandler.getSpellDef(spellIndex).getName()); } spellMenu.drawMenu(); int selectedSpellIndex = spellMenu .selectedListIndex(spellMenuHandle); if (selectedSpellIndex != -1) { gameGraphics .drawString( "Level " + EntityHandler.getSpellDef( selectedSpellIndex) .getReqLevel() + ": " + EntityHandler.getSpellDef( selectedSpellIndex).getName(), i + 2, j + 124, 1, 0xffff00); gameGraphics.drawString( EntityHandler.getSpellDef(selectedSpellIndex) .getDescription(), i + 2, j + 136, 0, 0xffffff); int i4 = 0; for (Entry<Integer, Integer> e : EntityHandler.getSpellDef( selectedSpellIndex).getRunesRequired()) { int runeID = e.getKey(); gameGraphics.drawPicture(i + 2 + i4 * 44, j + 150, SPRITE_ITEM_START + EntityHandler.getItemDef(runeID) .getSprite()); int runeInvCount = inventoryCount(runeID); int runeCount = e.getValue(); String s2 = "@red@"; if (hasRequiredRunes(runeID, runeCount)) { s2 = "@gre@"; } gameGraphics.drawString( s2 + runeInvCount + "/" + runeCount, i + 2 + i4 * 44, j + 150, 1, 0xffffff); i4++; } } else { gameGraphics.drawString("Point at a spell for a description", i + 2, j + 124, 1, 0); } } if (menuMagicPrayersSelected == 1) { spellMenu.resetListTextCount(spellMenuHandle); int j1 = 0; for (int j2 = 0; j2 < EntityHandler.prayerCount(); j2++) { String s1 = "@whi@"; if (EntityHandler.getPrayerDef(j2).getReqLevel() > playerStatBase[5]) s1 = "@bla@"; if (prayerOn[j2]) s1 = "@gre@"; spellMenu.drawMenuListText(spellMenuHandle, j1++, s1 + "Level " + EntityHandler.getPrayerDef(j2).getReqLevel() + ": " + EntityHandler.getPrayerDef(j2).getName()); } spellMenu.drawMenu(); int j3 = spellMenu.selectedListIndex(spellMenuHandle); if (j3 != -1) { gameGraphics.drawText("Level " + EntityHandler.getPrayerDef(j3).getReqLevel() + ": " + EntityHandler.getPrayerDef(j3).getName(), i + c / 2, j + 130, 1, 0xffff00); if (j3 == 13) { if (playerStatBase[5] > 39) { int percent = (int) ((playerStatBase[5] - 40) * 0.6); percent += 60; if (percent > 100) percent = 100; gameGraphics.drawText(percent + "% protection from ranged attack", i + c / 2, j + 145, 0, 0xffffff); } else gameGraphics.drawText( "60% protection from ranged attack", i + c / 2, j + 145, 0, 0xffffff); } else gameGraphics.drawText(EntityHandler.getPrayerDef(j3) .getDescription(), i + c / 2, j + 145, 0, 0xffffff); gameGraphics.drawText("Drain rate: " + EntityHandler.getPrayerDef(j3).getDrainRate(), i + c / 2, j + 160, 1, 0); } else { gameGraphics.drawString("Point at a prayer for a description", i + 2, j + 124, 1, 0); } } if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 182) { spellMenu.updateActions(i + (((GameImage) (gameGraphics)).menuDefaultWidth - 199), j + 36, super.lastMouseDownButton, super.mouseDownButton); if (j <= 24 && mouseButtonClick == 1) if (i < 98 && menuMagicPrayersSelected == 1) { menuMagicPrayersSelected = 0; prayerMenuIndex = spellMenu.getMenuIndex(spellMenuHandle); spellMenu.method165(spellMenuHandle, magicMenuIndex); } else if (i > 98 && menuMagicPrayersSelected == 0) { menuMagicPrayersSelected = 1; magicMenuIndex = spellMenu.getMenuIndex(spellMenuHandle); spellMenu.method165(spellMenuHandle, prayerMenuIndex); } if (mouseButtonClick == 1 && menuMagicPrayersSelected == 0) { int k1 = spellMenu.selectedListIndex(spellMenuHandle); if (k1 != -1) { int k2 = playerStatCurrent[6]; if (EntityHandler.getSpellDef(k1).getReqLevel() > k2) { displayMessage( "Your magic ability is not high enough for this spell", 3, 0); } else { int k3 = 0; for (Entry<Integer, Integer> e : EntityHandler .getSpellDef(k1).getRunesRequired()) { if (!hasRequiredRunes(e.getKey(), e.getValue())) { displayMessage( "You don't have all the reagents you need for this spell", 3, 0); k3 = -1; break; } k3++; } if (k3 == EntityHandler.getSpellDef(k1).getRuneCount()) { selectedSpell = k1; selectedItem = -1; } } } } if (mouseButtonClick == 1 && menuMagicPrayersSelected == 1) { int l1 = spellMenu.selectedListIndex(spellMenuHandle); if (l1 != -1) { int l2 = playerStatBase[5]; if (EntityHandler.getPrayerDef(l1).getReqLevel() > l2) displayMessage( "Your prayer ability is not high enough for this prayer", 3, 0); else if (playerStatCurrent[5] == 0) displayMessage( "You have run out of prayer points. Return to a church to recharge", 3, 0); else if (prayerOn[l1]) { super.streamClass.createPacket(248); super.streamClass.addByte(l1); super.streamClass.formatPacket(); prayerOn[l1] = false; playSound("prayeroff"); } else { super.streamClass.createPacket(56); super.streamClass.addByte(l1); super.streamClass.formatPacket(); prayerOn[l1] = true; playSound("prayeron"); } } } mouseButtonClick = 0; } } protected final void handleWheelRotate(int units) { if (super.controlDown) { if (units > -1) { if (cameraVertical >= 1000) return; } else { if (cameraVertical <= 850) return; } cameraVertical += units * 2; } } protected final void handleMenuKeyDown(int key, char keyChar) { if (!menusLoaded) return; switch (key) { case 123: // F12 takeScreenshot(true); break; case 33: { if (cameraHeight < 300) { cameraHeight += 25; } else { cameraHeight -= 25; } break; } case 34: { // Page Down { if (cameraHeight > 1500) { cameraHeight -= 25; } else { cameraHeight += 25; } break; } case 36: { cameraHeight = 750; break; } } if (loggedIn == 0) { if (loginScreenNumber == 0) menuWelcome.keyDown(key, keyChar); if (loginScreenNumber == 1) menuNewUser.keyDown(key, keyChar); if (loginScreenNumber == 2) menuLogin.keyDown(key, keyChar); } if (loggedIn == 1) { if (showCharacterLookScreen) { characterDesignMenu.keyDown(key, keyChar); return; } if (showDrawPointsScreen) { drawPointsScreen.keyDown(key, keyChar); return; } if (inputBoxType == 0 && showAbuseWindow == 0) gameMenu.keyDown(key, keyChar); } } private final void drawShopBox() { if (mouseButtonClick != 0) { mouseButtonClick = 0; int i = super.mouseX - 52 - xAddition; int j = super.mouseY - 44 - yAddition; if (i >= 0 && j >= 12 && i < 408 && j < 246) { int k = 0; for (int i1 = 0; i1 < 5; i1++) { for (int i2 = 0; i2 < 8; i2++) { int l2 = 7 + i2 * 49; int l3 = 28 + i1 * 34; if (i > l2 && i < l2 + 49 && j > l3 && j < l3 + 34 && shopItems[k] != -1) { selectedShopItemIndex = k; selectedShopItemType = shopItems[k]; } k++; } } if (selectedShopItemIndex >= 0) { int j2 = shopItems[selectedShopItemIndex]; if (j2 != -1) { if (shopItemCount[selectedShopItemIndex] > 0 && i > 298 && j >= 204 && i < 408 && j <= 215) { int i4 = shopItemsBuyPrice[selectedShopItemIndex];// (shopItemBuyPriceModifier // * // EntityHandler.getItemDef(j2).getBasePrice()) // / // 100; super.streamClass.createPacket(128); super.streamClass .add2ByteInt(shopItems[selectedShopItemIndex]); super.streamClass.add4ByteInt(i4); super.streamClass.formatPacket(); } if (inventoryCount(j2) > 0 && i > 2 && j >= 229 && i < 112 && j <= 240) { int j4 = shopItemsSellPrice[selectedShopItemIndex];// (shopItemSellPriceModifier // * // EntityHandler.getItemDef(j2).getBasePrice()) // / // 100; super.streamClass.createPacket(255); super.streamClass .add2ByteInt(shopItems[selectedShopItemIndex]); super.streamClass.add4ByteInt(j4); super.streamClass.formatPacket(); } } } } else { super.streamClass.createPacket(253); super.streamClass.formatPacket(); showShop = false; return; } } int byte0 = 52 + xAddition; int byte1 = 44 + yAddition; gameGraphics.drawBox(byte0, byte1, 408, 12, 192); int l = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 408, 17, l, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 29, 8, 170, l, 160); gameGraphics.drawBoxAlpha(byte0 + 399, byte1 + 29, 9, 170, l, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 199, 408, 47, l, 160); gameGraphics.drawString("Buying and selling items", byte0 + 1, byte1 + 10, 1, 0xffffff); int j1 = 0xffffff; if (super.mouseX > byte0 + 320 && super.mouseY >= byte1 && super.mouseX < byte0 + 408 && super.mouseY < byte1 + 12) j1 = 0xff0000; gameGraphics.drawBoxTextRight("Close window", byte0 + 406, byte1 + 10, 1, j1); gameGraphics.drawString("Shops stock in green", byte0 + 2, byte1 + 24, 1, 65280); gameGraphics.drawString("Number you own in blue", byte0 + 135, byte1 + 24, 1, 65535); gameGraphics.drawString("Your money: " + inventoryCount(10) + "gp", byte0 + 280, byte1 + 24, 1, 0xffff00); int k2 = 0xd0d0d0; int k3 = 0; for (int k4 = 0; k4 < 5; k4++) { for (int l4 = 0; l4 < 8; l4++) { int j5 = byte0 + 7 + l4 * 49; int i6 = byte1 + 28 + k4 * 34; if (selectedShopItemIndex == k3) gameGraphics.drawBoxAlpha(j5, i6, 49, 34, 0xff0000, 160); else gameGraphics.drawBoxAlpha(j5, i6, 49, 34, k2, 160); gameGraphics.drawBoxEdge(j5, i6, 50, 35, 0); if (shopItems[k3] != -1) { gameGraphics.spriteClip4(j5, i6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(shopItems[k3]) .getSprite(), EntityHandler.getItemDef(shopItems[k3]) .getPictureMask(), 0, 0, false); gameGraphics.drawString(String.valueOf(shopItemCount[k3]), j5 + 1, i6 + 10, 1, 65280); gameGraphics.drawBoxTextRight( String.valueOf(inventoryCount(shopItems[k3])), j5 + 47, i6 + 10, 1, 65535); } k3++; } } gameGraphics.drawLineX(byte0 + 5, byte1 + 222, 398, 0); if (selectedShopItemIndex == -1) { gameGraphics.drawText("Select an object to buy or sell", byte0 + 204, byte1 + 214, 3, 0xffff00); return; } int i5 = shopItems[selectedShopItemIndex]; if (i5 != -1) { if (shopItemCount[selectedShopItemIndex] > 0) { int j6 = shopItemsBuyPrice[selectedShopItemIndex];// (shopItemBuyPriceModifier // * // EntityHandler.getItemDef( // i5).getBasePrice()) / 100; gameGraphics.drawString("Buy a new " + EntityHandler.getItemDef(i5).getName() + " for " + j6 + "gp", byte0 + 2, byte1 + 214, 1, 0xffff00); int k1 = 0xffffff; if (super.mouseX > byte0 + 298 && super.mouseY >= byte1 + 204 && super.mouseX < byte0 + 408 && super.mouseY <= byte1 + 215) k1 = 0xff0000; gameGraphics.drawBoxTextRight("Click here to buy", byte0 + 405, byte1 + 214, 3, k1); } else { gameGraphics.drawText( "This item is not currently available to buy", byte0 + 204, byte1 + 214, 3, 0xffff00); } if (inventoryCount(i5) > 0) { int k6 = shopItemsSellPrice[selectedShopItemIndex];// (shopItemSellPriceModifier // * // EntityHandler.getItemDef( // i5).getBasePrice()) / 100; gameGraphics.drawBoxTextRight("Sell your " + EntityHandler.getItemDef(i5).getName() + " for " + k6 + "gp", byte0 + 405, byte1 + 239, 1, 0xffff00); int l1 = 0xffffff; if (super.mouseX > byte0 + 2 && super.mouseY >= byte1 + 229 && super.mouseX < byte0 + 112 && super.mouseY <= byte1 + 240) l1 = 0xff0000; gameGraphics.drawString("Click here to sell", byte0 + 2, byte1 + 239, 3, l1); return; } gameGraphics.drawText("You do not have any of this item to sell", byte0 + 204, byte1 + 239, 3, 0xffff00); } } private final void drawGameMenu() { gameMenu = new Menu(gameGraphics, 10); messagesHandleType2 = gameMenu.method159(5, windowHeight - 85, windowWidth - 10, 56, 1, 20, true); chatHandle = gameMenu.method160(7, windowHeight - 10, windowWidth - 14, 14, 1, 80, false, true); messagesHandleType5 = gameMenu.method159(5, windowHeight - 65, windowWidth - 10, 56, 1, 20, true); messagesHandleType6 = gameMenu.method159(5, windowHeight - 65, windowWidth - 10, 56, 1, 20, true); gameMenu.setFocus(chatHandle); } protected final byte[] load(String filename) { CacheManager.load(filename); return super.load(Config.CONF_DIR + File.separator + filename); } /** * Draws our options menu (client size etc) * * @param flag */ private final void drawOurOptionsMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 232; int j = 36; int c = 360; gameGraphics.drawBoxAlpha(i, 36, c, 176, GameImage.convertRGBToLong(181, 181, 181), 160); /** * Draws the gray box behind the icon */ gameGraphics.drawBox(i, 3, 31, 32, GameImage.convertRGBToLong(0, 0, 131)); int temp = 10; gameGraphics.drawBox(i, 26, 274, temp, GameImage.convertRGBToLong(0, 0, 131)); gameGraphics.drawBox(i, 26 + temp, 274, 1, GameImage.convertRGBToLong(0, 0, 0)); gameGraphics.drawString("screen size", i + 147, 26 + temp, 4, 0xffffff); int k = i + 3; int i1 = j + 15; i1 += 15; if (Resolutions.fs) gameGraphics.drawString( " Fullscreen @gre@On", k, i1, 1, 0xffffff); else gameGraphics.drawString( " Fullscreen @red@Off", k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" Screen size @gre@" + reso.getResolution(), k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" Refresh rate @gre@" + reso.getRefreshRate(), k, i1, 1, 0xffffff); i1 += 30; gameGraphics.drawString(" Window size will change after you", k, i1, 1, 0xffffff); i1 += 15; gameGraphics .drawString(" restart the client.", k, i1, 1, 0xffffff); i1 += 30; gameGraphics.drawString(" Going to fullsreen and back does", k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" not require a client restart.", k, i1, 1, 0xffffff); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 265) { int l1 = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; char c1 = '\304'; int l = l1 + 3; int j1 = byte0 + 30; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { if (gameFrame == null) { mudclient .drawPopup("You cannot switch to fullscreen from the webclient, sorry!"); return; } if (Resolutions.fs) { gameFrame.makeRegularScreen(); } else { gameFrame.makeFullScreen(); } } j1 += 15; // amera error if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { reso.findNextResolution(); Config.storeConfig( "width", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getWidth()); Config.storeConfig( "height", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getHeight()); Config.storeConfig( "refreshRate", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getRefreshRate()); Config.storeConfig( "bitDepth", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getBitDepth()); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; boolean flag1 = false; j1 += 35; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; j1 += 20; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) mouseButtonClick = 0; } } private final void drawOptionsMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 6); char c = '\304'; gameGraphics.drawBoxAlpha(i, 36, c, 65, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 101, c, 65, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 166, c, 95, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 261, c, 52, GameImage.convertRGBToLong(181, 181, 181), 160); int k = i + 3; int i1 = j + 15; gameGraphics.drawString("Game options - click to toggle", k, i1, 1, 0); i1 += 15; if (configAutoCameraAngle) gameGraphics.drawString("Camera angle mode - @gre@Auto", k, i1, 1, 0xffffff); else gameGraphics.drawString("Camera angle mode - @red@Manual", k, i1, 1, 0xffffff); i1 += 15; if (configMouseButtons) gameGraphics.drawString("Mouse buttons - @red@One", k, i1, 1, 0xffffff); else gameGraphics.drawString("Mouse buttons - @gre@Two", k, i1, 1, 0xffffff); i1 += 15; if (configSoundEffects) gameGraphics.drawString("Sound effects - @red@off", k, i1, 1, 0xffffff); else gameGraphics.drawString("Sound effects - @gre@on", k, i1, 1, 0xffffff); i1 += 15; gameGraphics .drawString("Client assists - click to toggle", k, i1, 1, 0); i1 += 15; if (showRoof) gameGraphics .drawString("Hide Roofs - @red@off", k, i1, 1, 0xffffff); else gameGraphics.drawString("Hide Roofs - @gre@on", k, i1, 1, 0xffffff); i1 += 15; if (autoScreenshot) gameGraphics.drawString("Auto Screenshots - @gre@on", k, i1, 1, 0xffffff); else gameGraphics.drawString("Auto Screenshots - @red@off", k, i1, 1, 0xffffff); i1 += 15; if (combatWindow) gameGraphics.drawString("Fightmode Selector - @gre@on", k, i1, 1, 0xffffff); else gameGraphics.drawString("Fightmode Selector - @red@off", k, i1, 1, 0xffffff); i1 += 15; if (fog) gameGraphics.drawString("Fog of War - @gre@on", k, i1, 1, 0xffffff); else gameGraphics .drawString("Fog of War - @red@off", k, i1, 1, 0xffffff); i1 += 15; i1 += 5; gameGraphics.drawString("Privacy settings. Will be applied to", i + 3, i1, 1, 0); i1 += 15; gameGraphics.drawString("all people not on your friends list", i + 3, i1, 1, 0); i1 += 15; if (super.blockChatMessages == 0) gameGraphics.drawString("Block chat messages: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block chat messages: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockPrivateMessages == 0) gameGraphics.drawString("Block private messages: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block private messages: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockTradeRequests == 0) gameGraphics.drawString("Block trade requests: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block trade requests: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockDuelRequests == 0) gameGraphics.drawString("Block duel requests: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block duel requests: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; i1 += 5; gameGraphics.drawString("Always logout when you finish", k, i1, 1, 0); i1 += 15; int k1 = 0xffffff; if (super.mouseX > k && super.mouseX < k + c && super.mouseY > i1 - 12 && super.mouseY < i1 + 4) k1 = 0xffff00; gameGraphics.drawString("Click here to logout", i + 3, i1, 1, k1); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 265) { int l1 = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; char c1 = '\304'; int l = l1 + 3; int j1 = byte0 + 30; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configAutoCameraAngle = !configAutoCameraAngle; super.streamClass.createPacket(157); super.streamClass.addByte(0); super.streamClass.addByte(configAutoCameraAngle ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; // amera error if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configMouseButtons = !configMouseButtons; super.streamClass.createPacket(157); super.streamClass.addByte(2); super.streamClass.addByte(configMouseButtons ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configSoundEffects = !configSoundEffects; super.streamClass.createPacket(157); super.streamClass.addByte(3); super.streamClass.addByte(configSoundEffects ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { showRoof = !showRoof; super.streamClass.createPacket(157); super.streamClass.addByte(4); super.streamClass.addByte(showRoof ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { autoScreenshot = !autoScreenshot; super.streamClass.createPacket(157); super.streamClass.addByte(5); super.streamClass.addByte(autoScreenshot ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { combatWindow = !combatWindow; super.streamClass.createPacket(157); super.streamClass.addByte(6); super.streamClass.addByte(combatWindow ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { fog = !fog; } j1 += 15; boolean flag1 = false; j1 += 35; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockChatMessages = 1 - super.blockChatMessages; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockPrivateMessages = 1 - super.blockPrivateMessages; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockTradeRequests = 1 - super.blockTradeRequests; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockDuelRequests = 1 - super.blockDuelRequests; flag1 = true; } j1 += 15; if (flag1) sendUpdatedPrivacyInfo(super.blockChatMessages, super.blockPrivateMessages, super.blockTradeRequests, super.blockDuelRequests); j1 += 20; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) logout(); mouseButtonClick = 0; } } private final void processGame() { try { if (super.keyDownDown) { currentChat++; if (currentChat >= messages.size()) { currentChat = messages.size() - 1; super.keyDownDown = false; return; } gameMenu.updateText(chatHandle, messages.get(currentChat)); super.keyDownDown = false; } if (super.keyUpDown) { currentChat--; if (currentChat < 0) { currentChat = 0; super.keyUpDown = false; return; } gameMenu.updateText(chatHandle, messages.get(currentChat)); super.keyUpDown = false; } } catch (Exception e) { e.printStackTrace(); } if (systemUpdate > 1) { systemUpdate--; } sendPingPacketReadPacketData(); if (logoutTimeout > 0) { logoutTimeout--; } if (ourPlayer.currentSprite == 8 || ourPlayer.currentSprite == 9) { lastWalkTimeout = 500; } if (lastWalkTimeout > 0) { lastWalkTimeout--; } if (showCharacterLookScreen) { drawCharacterLookScreen(); return; } if (showDrawPointsScreen) { drawPointsScreen(); return; } for (int i = 0; i < playerCount; i++) { Mob mob = playerArray[i]; int k = (mob.waypointCurrent + 1) % 10; if (mob.waypointEndSprite != k) { int i1 = -1; int l2 = mob.waypointEndSprite; int j4; if (l2 < k) j4 = k - l2; else j4 = (10 + k) - l2; int j5 = 4; if (j4 > 2) j5 = (j4 - 1) * 4; if (mob.waypointsX[l2] - mob.currentX > magicLoc * 3 || mob.waypointsY[l2] - mob.currentY > magicLoc * 3 || mob.waypointsX[l2] - mob.currentX < -magicLoc * 3 || mob.waypointsY[l2] - mob.currentY < -magicLoc * 3 || j4 > 8) { mob.currentX = mob.waypointsX[l2]; mob.currentY = mob.waypointsY[l2]; } else { if (mob.currentX < mob.waypointsX[l2]) { mob.currentX += j5; mob.stepCount++; i1 = 2; } else if (mob.currentX > mob.waypointsX[l2]) { mob.currentX -= j5; mob.stepCount++; i1 = 6; } if (mob.currentX - mob.waypointsX[l2] < j5 && mob.currentX - mob.waypointsX[l2] > -j5) mob.currentX = mob.waypointsX[l2]; if (mob.currentY < mob.waypointsY[l2]) { mob.currentY += j5; mob.stepCount++; if (i1 == -1) i1 = 4; else if (i1 == 2) i1 = 3; else i1 = 5; } else if (mob.currentY > mob.waypointsY[l2]) { mob.currentY -= j5; mob.stepCount++; if (i1 == -1) i1 = 0; else if (i1 == 2) i1 = 1; else i1 = 7; } if (mob.currentY - mob.waypointsY[l2] < j5 && mob.currentY - mob.waypointsY[l2] > -j5) mob.currentY = mob.waypointsY[l2]; } if (i1 != -1) mob.currentSprite = i1; if (mob.currentX == mob.waypointsX[l2] && mob.currentY == mob.waypointsY[l2]) mob.waypointEndSprite = (l2 + 1) % 10; } else { mob.currentSprite = mob.nextSprite; } if (mob.lastMessageTimeout > 0) mob.lastMessageTimeout--; if (mob.anInt163 > 0) mob.anInt163--; if (mob.combatTimer > 0) mob.combatTimer--; if (playerAliveTimeout > 0) { playerAliveTimeout--; if (playerAliveTimeout == 0) displayMessage( "You have been granted another life. Be more careful this time!", 3, 0); if (playerAliveTimeout == 0) displayMessage( "You retain your skills. Your objects land where you died", 3, 0); } } for (int j = 0; j < npcCount; j++) { Mob mob_1 = npcArray[j]; if (mob_1 == null) { System.out.println("MOB == NULL, npcCount: " + npcCount + ", j: " + j); System.exit(1); } int j1 = (mob_1.waypointCurrent + 1) % 10; if (mob_1.waypointEndSprite != j1) { int i3 = -1; int k4 = mob_1.waypointEndSprite; int k5; if (k4 < j1) k5 = j1 - k4; else k5 = (10 + j1) - k4; int l5 = 4; if (k5 > 2) l5 = (k5 - 1) * 4; if (mob_1.waypointsX[k4] - mob_1.currentX > magicLoc * 3 || mob_1.waypointsY[k4] - mob_1.currentY > magicLoc * 3 || mob_1.waypointsX[k4] - mob_1.currentX < -magicLoc * 3 || mob_1.waypointsY[k4] - mob_1.currentY < -magicLoc * 3 || k5 > 8) { mob_1.currentX = mob_1.waypointsX[k4]; mob_1.currentY = mob_1.waypointsY[k4]; } else { if (mob_1.currentX < mob_1.waypointsX[k4]) { mob_1.currentX += l5; mob_1.stepCount++; i3 = 2; } else if (mob_1.currentX > mob_1.waypointsX[k4]) { mob_1.currentX -= l5; mob_1.stepCount++; i3 = 6; } if (mob_1.currentX - mob_1.waypointsX[k4] < l5 && mob_1.currentX - mob_1.waypointsX[k4] > -l5) mob_1.currentX = mob_1.waypointsX[k4]; if (mob_1.currentY < mob_1.waypointsY[k4]) { mob_1.currentY += l5; mob_1.stepCount++; if (i3 == -1) i3 = 4; else if (i3 == 2) i3 = 3; else i3 = 5; } else if (mob_1.currentY > mob_1.waypointsY[k4]) { mob_1.currentY -= l5; mob_1.stepCount++; if (i3 == -1) i3 = 0; else if (i3 == 2) i3 = 1; else i3 = 7; } if (mob_1.currentY - mob_1.waypointsY[k4] < l5 && mob_1.currentY - mob_1.waypointsY[k4] > -l5) mob_1.currentY = mob_1.waypointsY[k4]; } if (i3 != -1) mob_1.currentSprite = i3; if (mob_1.currentX == mob_1.waypointsX[k4] && mob_1.currentY == mob_1.waypointsY[k4]) mob_1.waypointEndSprite = (k4 + 1) % 10; } else { mob_1.currentSprite = mob_1.nextSprite; if (mob_1.type == 43) mob_1.stepCount++; } if (mob_1.lastMessageTimeout > 0) mob_1.lastMessageTimeout--; if (mob_1.anInt163 > 0) mob_1.anInt163--; if (mob_1.combatTimer > 0) mob_1.combatTimer--; } if (mouseOverMenu != 2) { if (GameImage.anInt346 > 0) anInt658++; if (GameImage.anInt347 > 0) anInt658 = 0; GameImage.anInt346 = 0; GameImage.anInt347 = 0; } for (int l = 0; l < playerCount; l++) { Mob mob_2 = playerArray[l]; if (mob_2.anInt176 > 0) mob_2.anInt176--; } if (cameraAutoAngleDebug) { if (lastAutoCameraRotatePlayerX - ourPlayer.currentX < -500 || lastAutoCameraRotatePlayerX - ourPlayer.currentX > 500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY < -500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY > 500) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } } else { if (lastAutoCameraRotatePlayerX - ourPlayer.currentX < -500 || lastAutoCameraRotatePlayerX - ourPlayer.currentX > 500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY < -500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY > 500) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } if (lastAutoCameraRotatePlayerX != ourPlayer.currentX) lastAutoCameraRotatePlayerX += (ourPlayer.currentX - lastAutoCameraRotatePlayerX) / (16 + (cameraHeight - 500) / 15); if (lastAutoCameraRotatePlayerY != ourPlayer.currentY) lastAutoCameraRotatePlayerY += (ourPlayer.currentY - lastAutoCameraRotatePlayerY) / (16 + (cameraHeight - 500) / 15); if (configAutoCameraAngle) { int k1 = cameraAutoAngle * 32; int j3 = k1 - cameraRotation; byte byte0 = 1; if (j3 != 0) { cameraRotationBaseAddition++; if (j3 > 128) { byte0 = -1; j3 = 256 - j3; } else if (j3 > 0) byte0 = 1; else if (j3 < -128) { byte0 = 1; j3 = 256 + j3; } else if (j3 < 0) { byte0 = -1; j3 = -j3; } cameraRotation += ((cameraRotationBaseAddition * j3 + 255) / 256) * byte0; cameraRotation &= 0xff; } else { cameraRotationBaseAddition = 0; } } } if (anInt658 > 20) { aBoolean767 = false; anInt658 = 0; } if (sleeping) { ignoreNext = true; if (super.enteredText.length() > 0) { super.streamClass.createPacket(200); super.streamClass.addString(super.enteredText); if (!aBoolean767) { super.streamClass.addByte(0); aBoolean767 = true; } super.streamClass.formatPacket(); super.inputText = ""; super.enteredText = ""; gameMenu.updateText(chatHandle, ""); sleepMessage = "Please wait..."; } // PLZ CAN I HAS NEW SLEEP EKWAZION? if (super.lastMouseDownButton != 0 && super.mouseX >= ((windowWidth / 2) - 100) && super.mouseX < ((windowWidth / 2) + 100) && super.mouseY > 280 && super.mouseY < 310) { super.streamClass.createPacket(200); super.streamClass.addString("-null-"); if (!aBoolean767) { super.streamClass.addByte(0); aBoolean767 = true; } super.streamClass.formatPacket(); super.inputText = ""; super.enteredText = ""; sleepMessage = " Please wait..."; } super.lastMouseDownButton = 0; return; } if (super.mouseY > windowHeight - 4) { if (super.mouseX > 15 + xAddition && super.mouseX < 96 + xAddition && super.lastMouseDownButton == 1) messagesTab = 0; if (super.mouseX > 110 + xAddition && super.mouseX < 194 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 1; gameMenu.anIntArray187[messagesHandleType2] = 0xf423f; } if (super.mouseX > 215 + xAddition && super.mouseX < 295 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 2; gameMenu.anIntArray187[messagesHandleType5] = 0xf423f; } if (super.mouseX > 315 + xAddition && super.mouseX < 395 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 3; gameMenu.anIntArray187[messagesHandleType6] = 0xf423f; } if (super.mouseX > 417 + xAddition && super.mouseX < 497 + xAddition && super.lastMouseDownButton == 1) { showAbuseWindow = 1; abuseSelectedType = 0; super.inputText = ""; super.enteredText = ""; } super.lastMouseDownButton = 0; super.mouseDownButton = 0; } gameMenu.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); if (messagesTab > 0 && super.mouseX >= 494 && super.mouseY >= windowHeight - 66) super.lastMouseDownButton = 0; if (gameMenu.hasActivated(chatHandle)) { String s = gameMenu.getText(chatHandle); gameMenu.updateText(chatHandle, ""); if (ignoreNext) { ignoreNext = false; return; } if (s.startsWith("::")) { s = s.substring(2); if (!handleCommand(s) && !sleeping && !ignoreNext) { sendChatString(s); if (messages.size() == 0 || !messages.get(messages.size() - 1) .equalsIgnoreCase("::" + s)) { messages.add("::" + s); currentChat = messages.size(); } else if (messages.get(messages.size() - 1) .equalsIgnoreCase("::" + s)) { currentChat = messages.size(); } } } else if (!sleeping && !ignoreNext) { byte[] chatMessage = DataConversions.stringToByteArray(s); sendChatMessage(chatMessage, chatMessage.length); s = DataConversions.byteToString(chatMessage, 0, chatMessage.length).trim(); if (s.toLowerCase().trim().startsWith(";;")) return; if (messages.size() == 0 || !messages.get(messages.size() - 1).equalsIgnoreCase( s)) { messages.add(s); currentChat = messages.size(); } else if (messages.get(messages.size() - 1) .equalsIgnoreCase(s)) { currentChat = messages.size(); } ourPlayer.lastMessageTimeout = 150; ourPlayer.lastMessage = s; displayMessage(ourPlayer.name + ": " + s, 2, ourPlayer.admin); } } if (messagesTab == 0) { for (int l1 = 0; l1 < messagesTimeout.length; l1++) if (messagesTimeout[l1] > 0) messagesTimeout[l1]--; } if (playerAliveTimeout != 0) super.lastMouseDownButton = 0; if (showTradeWindow || showDuelWindow) { if (super.mouseDownButton != 0) mouseDownTime++; else mouseDownTime = 0; if (mouseDownTime > 500) itemIncrement += 100000; else if (mouseDownTime > 350) itemIncrement += 10000; else if (mouseDownTime > 250) itemIncrement += 1000; else if (mouseDownTime > 150) itemIncrement += 100; else if (mouseDownTime > 100) itemIncrement += 10; else if (mouseDownTime > 50) itemIncrement++; else if (mouseDownTime > 20 && (mouseDownTime & 5) == 0) itemIncrement++; } else { mouseDownTime = 0; itemIncrement = 0; } if (super.lastMouseDownButton == 1) mouseButtonClick = 1; else if (super.lastMouseDownButton == 2) mouseButtonClick = 2; gameCamera.updateMouseCoords(super.mouseX, super.mouseY); super.lastMouseDownButton = 0; if (configAutoCameraAngle) { if (cameraRotationBaseAddition == 0 || cameraAutoAngleDebug) { if (super.keyLeftDown) { cameraAutoAngle = cameraAutoAngle + 1 & 7; super.keyLeftDown = false; if (!zoomCamera) { if ((cameraAutoAngle & 1) == 0) cameraAutoAngle = cameraAutoAngle + 1 & 7; for (int i2 = 0; i2 < 8; i2++) { if (enginePlayerVisible(cameraAutoAngle)) break; cameraAutoAngle = cameraAutoAngle + 1 & 7; } } } if (super.keyRightDown) { cameraAutoAngle = cameraAutoAngle + 7 & 7; super.keyRightDown = false; if (!zoomCamera) { if ((cameraAutoAngle & 1) == 0) cameraAutoAngle = cameraAutoAngle + 7 & 7; for (int j2 = 0; j2 < 8; j2++) { if (enginePlayerVisible(cameraAutoAngle)) break; cameraAutoAngle = cameraAutoAngle + 7 & 7; } } } } } else try { if (super.keyLeftDown) cameraRotation = cameraRotation + 2 & 0xff; else if (super.keyRightDown) cameraRotation = cameraRotation - 2 & 0xff; if (super.home) { cameraHeight = 750; cameraVertical = 920; fogVar = 0; } else if (super.pageUp) { if (cameraHeight > 400) cameraHeight -= 6; } else if (super.pageDown) { if (cameraHeight < 3000) cameraHeight += 6; } if (controlDown && fog) { if (minus) fogVar += 20; else if (plus) fogVar -= 20; } } catch (Exception e) { e.printStackTrace(); System.out.println("Camera error: " + e); cameraHeight = 750; cameraVertical = 920; fogVar = 0; } if (actionPictureType > 0) actionPictureType--; else if (actionPictureType < 0) actionPictureType++; gameCamera.method301(17); modelUpdatingTimer++; if (modelUpdatingTimer > 5) { modelUpdatingTimer = 0; modelFireLightningSpellNumber = (modelFireLightningSpellNumber + 1) % 3; modelTorchNumber = (modelTorchNumber + 1) % 4; modelClawSpellNumber = (modelClawSpellNumber + 1) % 5; } for (int k2 = 0; k2 < objectCount; k2++) { int l3 = objectX[k2]; int l4 = objectY[k2]; if (l3 >= 0 && l4 >= 0 && l3 < 96 && l4 < 96 && objectType[k2] == 74) objectModelArray[k2].method188(1, 0, 0); } for (int i4 = 0; i4 < anInt892; i4++) { anIntArray923[i4]++; if (anIntArray923[i4] > 50) { anInt892--; for (int i5 = i4; i5 < anInt892; i5++) { anIntArray944[i5] = anIntArray944[i5 + 1]; anIntArray757[i5] = anIntArray757[i5 + 1]; anIntArray923[i5] = anIntArray923[i5 + 1]; anIntArray782[i5] = anIntArray782[i5 + 1]; } } } }// command == 11 public static HashMap<String, File> ctfsounds = new HashMap<String, File>(); private final void loadSounds() { try { drawDownloadProgress("Unpacking Sound effects", 90, false); sounds = load("sounds1.mem"); audioReader = new AudioReader(); return; } catch (Throwable throwable) { System.out.println("Unable to init sounds:" + throwable); } } private final void drawCombatStyleWindow() { byte byte0 = 7; byte byte1 = 15; char c = '\257'; if (mouseButtonClick != 0) { for (int i = 0; i < 5; i++) { if (i <= 0 || super.mouseX <= byte0 || super.mouseX >= byte0 + c || super.mouseY <= byte1 + i * 20 || super.mouseY >= byte1 + i * 20 + 20) continue; combatStyle = i - 1; mouseButtonClick = 0; super.streamClass.createPacket(42); super.streamClass.addByte(combatStyle); super.streamClass.formatPacket(); break; } } for (int j = 0; j < 5; j++) { if (j == combatStyle + 1) gameGraphics.drawBoxAlpha(byte0, byte1 + j * 20, c, 20, GameImage.convertRGBToLong(255, 0, 0), 128); else gameGraphics.drawBoxAlpha(byte0, byte1 + j * 20, c, 20, GameImage.convertRGBToLong(190, 190, 190), 128); gameGraphics.drawLineX(byte0, byte1 + j * 20, c, 0); gameGraphics.drawLineX(byte0, byte1 + j * 20 + 20, c, 0); } gameGraphics.drawText("Select combat style", byte0 + c / 2, byte1 + 16, 3, 0xffffff); gameGraphics.drawText("Controlled (+1 of each)", byte0 + c / 2, byte1 + 36, 3, 0); gameGraphics.drawText("Aggressive (+3 strength)", byte0 + c / 2, byte1 + 56, 3, 0); gameGraphics.drawText("Accurate (+3 attack)", byte0 + c / 2, byte1 + 76, 3, 0); gameGraphics.drawText("Defensive (+3 defense)", byte0 + c / 2, byte1 + 96, 3, 0); } private final void drawDuelConfirmWindow() { int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 16, 192); int i = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 16, 468, 246, i, 160); gameGraphics.drawText("Please confirm your duel with @yel@" + DataOperations.longToString(duelOpponentNameLong), byte0 + 234, byte1 + 12, 1, 0xffffff); gameGraphics.drawText("Your stake:", byte0 + 117, byte1 + 30, 1, 0xffff00); for (int j = 0; j < duelConfirmMyItemCount; j++) { String s = EntityHandler.getItemDef(duelConfirmMyItems[j]) .getName(); if (EntityHandler.getItemDef(duelConfirmMyItems[j]).isStackable()) s = s + " x " + method74(duelConfirmMyItemsCount[j]); gameGraphics.drawText(s, byte0 + 117, byte1 + 42 + j * 12, 1, 0xffffff); } if (duelConfirmMyItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 117, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("Your opponent's stake:", byte0 + 351, byte1 + 30, 1, 0xffff00); for (int k = 0; k < duelConfirmOpponentItemCount; k++) { String s1 = EntityHandler.getItemDef(duelConfirmOpponentItems[k]) .getName(); if (EntityHandler.getItemDef(duelConfirmOpponentItems[k]) .isStackable()) s1 = s1 + " x " + method74(duelConfirmOpponentItemsCount[k]); gameGraphics.drawText(s1, byte0 + 351, byte1 + 42 + k * 12, 1, 0xffffff); } if (duelConfirmOpponentItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 351, byte1 + 42, 1, 0xffffff); if (duelCantRetreat == 0) gameGraphics.drawText("You can retreat from this duel", byte0 + 234, byte1 + 180, 1, 65280); else gameGraphics.drawText("No retreat is possible!", byte0 + 234, byte1 + 180, 1, 0xff0000); if (duelUseMagic == 0) gameGraphics.drawText("Magic may be used", byte0 + 234, byte1 + 192, 1, 65280); else gameGraphics.drawText("Magic cannot be used", byte0 + 234, byte1 + 192, 1, 0xff0000); if (duelUsePrayer == 0) gameGraphics.drawText("Prayer may be used", byte0 + 234, byte1 + 204, 1, 65280); else gameGraphics.drawText("Prayer cannot be used", byte0 + 234, byte1 + 204, 1, 0xff0000); if (duelUseWeapons == 0) gameGraphics.drawText("Weapons may be used", byte0 + 234, byte1 + 216, 1, 65280); else gameGraphics.drawText("Weapons cannot be used", byte0 + 234, byte1 + 216, 1, 0xff0000); gameGraphics.drawText( "If you are sure click 'Accept' to begin the duel", byte0 + 234, byte1 + 230, 1, 0xffffff); if (!duelWeAccept) { gameGraphics.drawPicture((byte0 + 118) - 35, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture((byte0 + 352) - 35, byte1 + 238, SPRITE_MEDIA_START + 26); } else { gameGraphics.drawText("Waiting for other player...", byte0 + 234, byte1 + 250, 1, 0xffff00); } if (mouseButtonClick == 1) { if (super.mouseX < byte0 || super.mouseY < byte1 || super.mouseX > byte0 + 468 || super.mouseY > byte1 + 262) { showDuelConfirmWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 118) - 35 && super.mouseX <= byte0 + 118 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { duelWeAccept = true; super.streamClass.createPacket(87); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 352) - 35 && super.mouseX <= byte0 + 353 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { showDuelConfirmWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } mouseButtonClick = 0; } } private final void updateBankItems() { bankItemCount = newBankItemCount; for (int i = 0; i < newBankItemCount; i++) { bankItems[i] = newBankItems[i]; bankItemsCount[i] = newBankItemsCount[i]; } for (int j = 0; j < inventoryCount; j++) { if (bankItemCount >= bankItemsMax) break; int k = getInventoryItems()[j]; boolean flag = false; for (int l = 0; l < bankItemCount; l++) { if (bankItems[l] != k) continue; flag = true; break; } if (!flag) { bankItems[bankItemCount] = k; bankItemsCount[bankItemCount] = 0; bankItemCount++; } } } private final void makeDPSMenu() { drawPointsScreen = new Menu(gameGraphics, 100); final Menu dPS = drawPointsScreen; dPS.drawText(256, 10, "Please select your points", 4, true); int i = 140; int j = 34; i += 116; j -= 10; byte byte0 = 54; j += 145; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Str", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); strDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); strUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); dPS.method157(i + byte0, j, 53, 41); dPS.drawText(i + byte0, j - 8, "Atk", 1, true); dPS.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); atkDownButton = dPS.makeButton((i + byte0) - 40, j, 20, 20); dPS.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); atkUpButton = dPS.makeButton(i + byte0 + 40, j, 20, 20); j += 50; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Def", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); defDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); defUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); dPS.method157(i + byte0, j, 53, 41); dPS.drawText(i + byte0, j - 8, "Range", 1, true); dPS.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); rangeDownButton = dPS.makeButton((i + byte0) - 40, j, 20, 20); dPS.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); rangeUpButton = dPS.makeButton(i + byte0 + 40, j, 20, 20); j += 50; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Magic", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); magDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); magUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); j += 82; j -= 35; dPS.drawBox(i, j, 200, 30); dPS.drawText(i, j, "Accept", 4, false); dPSAcceptButton = dPS.makeButton(i, j, 200, 30); } private final void makeCharacterDesignMenu() { characterDesignMenu = new Menu(gameGraphics, 100); characterDesignMenu.drawText(256, 10, "Please design Your Character", 4, true); int i = 140; int j = 34; i += 116; j -= 10; characterDesignMenu.drawText(i - 55, j + 110, "Front", 3, true); characterDesignMenu.drawText(i, j + 110, "Side", 3, true); characterDesignMenu.drawText(i + 55, j + 110, "Back", 3, true); byte byte0 = 54; j += 145; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j - 8, "Head", 1, true); characterDesignMenu.drawText(i - byte0, j + 8, "Type", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignHeadButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignHeadButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Hair", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignHairColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignHairColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 50; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j, "Gender", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignGenderButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignGenderButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Top", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignTopColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignTopColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 50; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j - 8, "Skin", 1, true); characterDesignMenu.drawText(i - byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignSkinColourButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignSkinColourButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Bottom", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignBottomColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignBottomColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 82; j -= 35; characterDesignMenu.drawBox(i, j, 200, 30); characterDesignMenu.drawText(i, j, "Accept", 4, false); characterDesignAcceptButton = characterDesignMenu.makeButton(i, j, 200, 30); } private final void drawAbuseWindow2() { if (super.enteredText.length() > 0) { String s = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; if (s.length() > 0) { long l = DataOperations.stringLength12ToLong(s); super.streamClass.createPacket(7); super.streamClass.addTwo4ByteInts(l); super.streamClass.addByte(abuseSelectedType); super.streamClass.formatPacket(); } showAbuseWindow = 0; return; } gameGraphics.drawBox(56 + xAddition, 130 + yAddition, 400, 100, 0); gameGraphics.drawBoxEdge(56 + xAddition, 130 + yAddition, 400, 100, 0xffffff); int i = 160 + yAddition; gameGraphics.drawText( "Now type the name of the offending player, and press enter", 256 + xAddition, i, 1, 0xffff00); i += 18; gameGraphics.drawText("Name: " + super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); i = 222 + yAddition; int j = 0xffffff; if (super.mouseX > 196 + xAddition && super.mouseX < 316 + xAddition && super.mouseY > i - 13 && super.mouseY < i + 2) { j = 0xffff00; if (mouseButtonClick == 1) { mouseButtonClick = 0; showAbuseWindow = 0; } } gameGraphics.drawText("Click here to cancel", 256 + xAddition, i, 1, j); if (mouseButtonClick == 1 && (super.mouseX < 56 + xAddition || super.mouseX > 456 + xAddition || super.mouseY < 130 + yAddition || super.mouseY > 230 + yAddition)) { mouseButtonClick = 0; showAbuseWindow = 0; } } public final void displayMessage(String message, int type, int status) { if (type == 2 || type == 4 || type == 6) { for (; message.length() > 5 && message.charAt(0) == '@' && message.charAt(4) == '@'; message = message.substring(5)) ; } if (message.startsWith("%", 0)) { message = message.substring(1); status = 4; } if (message.startsWith("&", 0)) { message = message.substring(1); status = 33; } // if (command == 131) { message = message.replaceAll("\\#pmd\\#", ""); message = message.replaceAll("\\#mod\\#", ""); message = message.replaceAll("\\#adm\\#", ""); if (type == 2) message = "@yel@" + message; if (type == 3 || type == 4) message = "@whi@" + message; if (type == 6) message = "@cya@" + message; if (status == 1) message = "#pmd#" + message; if (status == 2) message = "#mod#" + message; if (status == 3) message = "#adm#" + message; if (status == 4) { message = "#pmd#" + message; MessageQueue.getQueue(); MessageQueue.addMessage(new Message(message)); gameMenu.addString(messagesHandleType6, message, false); return; } // MessageQueue if (status == 33) { MessageQueue.getQueue(); MessageQueue.addMessage(new Message(message, true)); gameMenu.addString(messagesHandleType6, message, false); return; } if (messagesTab != 0) { if (type == 4 || type == 3) anInt952 = 200; if (type == 2 && messagesTab != 1) anInt953 = 200; if (type == 5 && messagesTab != 2) anInt954 = 200; if (type == 6 && messagesTab != 3) anInt955 = 200; if (type == 3 && messagesTab != 0) messagesTab = 0; if (type == 6 && messagesTab != 3 && messagesTab != 0) messagesTab = 0; } for (int k = messagesArray.length - 1; k > 0; k--) { messagesArray[k] = messagesArray[k - 1]; messagesTimeout[k] = messagesTimeout[k - 1]; } messagesArray[0] = message; /** * Change this to add longer chat msg time */ messagesTimeout[0] = 300; if (type == 2) if (gameMenu.anIntArray187[messagesHandleType2] == gameMenu.menuListTextCount[messagesHandleType2] - 4) gameMenu.addString(messagesHandleType2, message, true); else gameMenu.addString(messagesHandleType2, message, false); if (type == 5) if (gameMenu.anIntArray187[messagesHandleType5] == gameMenu.menuListTextCount[messagesHandleType5] - 4) gameMenu.addString(messagesHandleType5, message, true); else gameMenu.addString(messagesHandleType5, message, false); if (type == 6) { if (gameMenu.anIntArray187[messagesHandleType6] == gameMenu.menuListTextCount[messagesHandleType6] - 4) { gameMenu.addString(messagesHandleType6, message, true); return; } gameMenu.addString(messagesHandleType6, message, false); } } protected final void logoutAndStop() { sendLogoutPacket(); garbageCollect(); if (audioReader != null) { audioReader.stopAudio(); } } private final void method98(int i, String s) { int j = objectX[i]; int k = objectY[i]; int l = j - ourPlayer.currentX / 128; int i1 = k - ourPlayer.currentY / 128; byte byte0 = 7; if (j >= 0 && k >= 0 && j < 96 && k < 96 && l > -byte0 && l < byte0 && i1 > -byte0 && i1 < byte0) { try { gameCamera.removeModel(objectModelArray[i]); int j1 = EntityHandler.storeModel(s); Model model = gameDataModels[j1].method203(); gameCamera.addModel(model); model.method184(true, 48, 48, -50, -10, -50); model.method205(objectModelArray[i]); model.anInt257 = i; objectModelArray[i] = model; } catch (Exception e) { // e.printStackTrace(); } } } protected final void resetVars() { systemUpdate = 0; combatStyle = 0; logoutTimeout = 0; loginScreenNumber = 0; loggedIn = 1; flagged = 0; resetPrivateMessageStrings(); gameGraphics.method211(); gameGraphics.drawImage(aGraphics936, 0, 0); for (int i = 0; i < objectCount; i++) { gameCamera.removeModel(objectModelArray[i]); engineHandle.updateObject(objectX[i], objectY[i], objectType[i], objectID[i]); } for (int j = 0; j < doorCount; j++) { gameCamera.removeModel(doorModel[j]); engineHandle.updateDoor(doorX[j], doorY[j], doorDirection[j], doorType[j]); } objectCount = 0; doorCount = 0; groundItemCount = 0; playerCount = 0; for (int k = 0; k < mobArray.length; k++) mobArray[k] = null; for (int l = 0; l < playerArray.length; l++) playerArray[l] = null; npcCount = 0; for (int i1 = 0; i1 < npcRecordArray.length; i1++) npcRecordArray[i1] = null; for (int j1 = 0; j1 < npcArray.length; j1++) npcArray[j1] = null; for (int k1 = 0; k1 < prayerOn.length; k1++) prayerOn[k1] = false; mouseButtonClick = 0; super.lastMouseDownButton = 0; super.mouseDownButton = 0; showShop = false; showBank = false; super.friendsCount = 0; } private final void drawTradeWindow() { if (mouseButtonClick != 0 && itemIncrement == 0) itemIncrement = 1; if (itemIncrement > 0) { int i = super.mouseX - 22 - xAddition; int j = super.mouseY - 36 - yAddition; if (i >= 0 && j >= 0 && i < 468 && j < 262) { if (i > 216 && j > 30 && i < 462 && j < 235) { int k = (i - 217) / 49 + ((j - 31) / 34) * 5; if (k >= 0 && k < inventoryCount) { boolean flag = false; int l1 = 0; int k2 = getInventoryItems()[k]; for (int k3 = 0; k3 < tradeMyItemCount; k3++) if (tradeMyItems[k3] == k2) if (EntityHandler.getItemDef(k2).isStackable()) { for (int i4 = 0; i4 < itemIncrement; i4++) { if (tradeMyItemsCount[k3] < inventoryItemsCount[k]) tradeMyItemsCount[k3]++; flag = true; } } else { l1++; } if (inventoryCount(k2) <= l1) flag = true; if (!flag && tradeMyItemCount < 12) { tradeMyItems[tradeMyItemCount] = k2; tradeMyItemsCount[tradeMyItemCount] = 1; tradeMyItemCount++; flag = true; } if (flag) { super.streamClass.createPacket(70); super.streamClass.addByte(tradeMyItemCount); for (int j4 = 0; j4 < tradeMyItemCount; j4++) { super.streamClass.add2ByteInt(tradeMyItems[j4]); super.streamClass .add4ByteInt(tradeMyItemsCount[j4]); } super.streamClass.formatPacket(); tradeOtherAccepted = false; tradeWeAccepted = false; } } } if (i > 8 && j > 30 && i < 205 && j < 133) { int l = (i - 9) / 49 + ((j - 31) / 34) * 4; if (l >= 0 && l < tradeMyItemCount) { int j1 = tradeMyItems[l]; for (int i2 = 0; i2 < itemIncrement; i2++) { if (EntityHandler.getItemDef(j1).isStackable() && tradeMyItemsCount[l] > 1) { tradeMyItemsCount[l]--; continue; }// shopItem tradeMyItemCount--; mouseDownTime = 0; for (int l2 = l; l2 < tradeMyItemCount; l2++) { tradeMyItems[l2] = tradeMyItems[l2 + 1]; tradeMyItemsCount[l2] = tradeMyItemsCount[l2 + 1]; } break; } super.streamClass.createPacket(70); super.streamClass.addByte(tradeMyItemCount); for (int i3 = 0; i3 < tradeMyItemCount; i3++) { super.streamClass.add2ByteInt(tradeMyItems[i3]); super.streamClass .add4ByteInt(tradeMyItemsCount[i3]); } super.streamClass.formatPacket(); tradeOtherAccepted = false; tradeWeAccepted = false; } } if (i >= 217 && j >= 238 && i <= 286 && j <= 259) { tradeWeAccepted = true; super.streamClass.createPacket(211); super.streamClass.formatPacket(); } if (i >= 394 && j >= 238 && i < 463 && j < 259) { showTradeWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } } else if (mouseButtonClick != 0) { showTradeWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } mouseButtonClick = 0; itemIncrement = 0; } if (!showTradeWindow) return; int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 12, 192); int i1 = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 468, 18, i1, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 30, 8, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 205, byte1 + 30, 11, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 462, byte1 + 30, 6, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 133, 197, 22, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 258, 197, 20, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 235, 246, 43, i1, 160); int k1 = 0xd0d0d0; gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 30, 197, 103, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 155, 197, 103, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 30, 246, 205, k1, 160); for (int j2 = 0; j2 < 4; j2++) gameGraphics.drawLineX(byte0 + 8, byte1 + 30 + j2 * 34, 197, 0); for (int j3 = 0; j3 < 4; j3++) gameGraphics.drawLineX(byte0 + 8, byte1 + 155 + j3 * 34, 197, 0); for (int l3 = 0; l3 < 7; l3++) gameGraphics.drawLineX(byte0 + 216, byte1 + 30 + l3 * 34, 246, 0); for (int k4 = 0; k4 < 6; k4++) { if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 30, 103, 0); if (k4 < 5) gameGraphics .drawLineY(byte0 + 8 + k4 * 49, byte1 + 155, 103, 0); gameGraphics.drawLineY(byte0 + 216 + k4 * 49, byte1 + 30, 205, 0); } gameGraphics.drawString("Trading with: " + tradeOtherPlayerName, byte0 + 1, byte1 + 10, 1, 0xffffff); gameGraphics.drawString("Your Offer", byte0 + 9, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("Opponent's Offer", byte0 + 9, byte1 + 152, 4, 0xffffff); gameGraphics.drawString("Your Inventory", byte0 + 216, byte1 + 27, 4, 0xffffff); if (!tradeWeAccepted) gameGraphics.drawPicture(byte0 + 217, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture(byte0 + 394, byte1 + 238, SPRITE_MEDIA_START + 26); if (tradeOtherAccepted) { gameGraphics.drawText("Other player", byte0 + 341, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("has accepted", byte0 + 341, byte1 + 256, 1, 0xffffff); } if (tradeWeAccepted) { gameGraphics.drawText("Waiting for", byte0 + 217 + 35, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("other player", byte0 + 217 + 35, byte1 + 256, 1, 0xffffff); } for (int l4 = 0; l4 < inventoryCount; l4++) { int i5 = 217 + byte0 + (l4 % 5) * 49; int k5 = 31 + byte1 + (l4 / 5) * 34; gameGraphics.spriteClip4(i5, k5, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(getInventoryItems()[l4]) .getSprite(), EntityHandler.getItemDef(getInventoryItems()[l4]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(getInventoryItems()[l4]).isStackable()) gameGraphics.drawString( String.valueOf(inventoryItemsCount[l4]), i5 + 1, k5 + 10, 1, 0xffff00); } for (int j5 = 0; j5 < tradeMyItemCount; j5++) { int l5 = 9 + byte0 + (j5 % 4) * 49; int j6 = 31 + byte1 + (j5 / 4) * 34; gameGraphics .spriteClip4(l5, j6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(tradeMyItems[j5]) .getSprite(), EntityHandler.getItemDef(tradeMyItems[j5]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(tradeMyItems[j5]).isStackable()) gameGraphics.drawString(String.valueOf(tradeMyItemsCount[j5]), l5 + 1, j6 + 10, 1, 0xffff00); if (super.mouseX > l5 && super.mouseX < l5 + 48 && super.mouseY > j6 && super.mouseY < j6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(tradeMyItems[j5]).getName() + ": @whi@" + EntityHandler.getItemDef(tradeMyItems[j5]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } for (int i6 = 0; i6 < tradeOtherItemCount; i6++) { int k6 = 9 + byte0 + (i6 % 4) * 49; int l6 = 156 + byte1 + (i6 / 4) * 34; gameGraphics.spriteClip4( k6, l6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(tradeOtherItems[i6]) .getSprite(), EntityHandler.getItemDef(tradeOtherItems[i6]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(tradeOtherItems[i6]).isStackable()) gameGraphics.drawString( String.valueOf(tradeOtherItemsCount[i6]), k6 + 1, l6 + 10, 1, 0xffff00); if (super.mouseX > k6 && super.mouseX < k6 + 48 && super.mouseY > l6 && super.mouseY < l6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(tradeOtherItems[i6]).getName() + ": @whi@" + EntityHandler.getItemDef(tradeOtherItems[i6]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } } private final boolean enginePlayerVisible(int i) { int j = ourPlayer.currentX / 128; int k = ourPlayer.currentY / 128; for (int l = 2; l >= 1; l--) { if (i == 1 && ((engineHandle.walkableValue[j][k - l] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k - l] & 0x80) == 128)) return false; if (i == 3 && ((engineHandle.walkableValue[j][k + l] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k + l] & 0x80) == 128)) return false; if (i == 5 && ((engineHandle.walkableValue[j][k + l] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k + l] & 0x80) == 128)) return false; if (i == 7 && ((engineHandle.walkableValue[j][k - l] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k - l] & 0x80) == 128)) return false; if (i == 0 && (engineHandle.walkableValue[j][k - l] & 0x80) == 128) return false; if (i == 2 && (engineHandle.walkableValue[j - l][k] & 0x80) == 128) return false; if (i == 4 && (engineHandle.walkableValue[j][k + l] & 0x80) == 128) return false; if (i == 6 && (engineHandle.walkableValue[j + l][k] & 0x80) == 128) return false; } return true; } private Mob getLastPlayer(int serverIndex) { for (int i1 = 0; i1 < lastPlayerCount; i1++) { if (lastPlayerArray[i1].serverIndex == serverIndex) { return lastPlayerArray[i1]; } } return null; } private Mob getLastNpc(int serverIndex) { for (int i1 = 0; i1 < lastNpcCount; i1++) { if (lastNpcArray[i1].serverIndex == serverIndex) { return lastNpcArray[i1]; } } return null; } protected final void handleIncomingPacket(int command, int length, byte data[]) { try { if (command == 254) { int bar = DataOperations.getUnsigned4Bytes(data, 1); // System.out.println(bar); if (bar == -1) { smithingscreen.isVisible = false; } else { SmithingScreen.changeItems(smithingscreen, bar); smithingscreen.isVisible = true; } } if (command == 231) { // PS = DataOperations.getUnsigned4Bytes(data, 1); return; } if (command == 233) { questPoints = DataOperations.getUnsignedByte(data[1]); int k = DataOperations.getUnsignedByte(data[2]); int r = 3; newQuestNames = new String[k]; questStage = new byte[k]; for (int i = 0; i < k; i++) { int uid = DataOperations.getUnsignedByte(data[r]); r++; newQuestNames[i] = questName[uid]; questStage[i] = (byte) DataOperations .getUnsignedByte(data[r]); // System.out.println(newQuestNames[i] + " " + // questStage[i]); r++; } }// command == 177 if (command == 110) { int i = 1; serverStartTime = DataOperations.getUnsigned8Bytes(data, i); i += 8; serverLocation = new String(data, i, length - i); return; } if (command == 145) { if (!hasWorldInfo) { return; } loading = true; lastPlayerCount = playerCount; for (int k = 0; k < lastPlayerCount; k++) lastPlayerArray[k] = playerArray[k]; int currentOffset = 8; setSectionX(DataOperations.getIntFromByteArray(data, currentOffset, 11)); currentOffset += 11; setSectionY(DataOperations.getIntFromByteArray(data, currentOffset, 13)); currentOffset += 13; int mobSprite = DataOperations.getIntFromByteArray(data, currentOffset, 4); currentOffset += 4; boolean sectionLoaded = loadSection(getSectionX(), getSectionY()); setSectionX(getSectionX() - getAreaX()); setSectionY(getSectionY() - getAreaY()); int mapEnterX = getSectionX() * magicLoc + 64; int mapEnterY = getSectionY() * magicLoc + 64; if (sectionLoaded) { ourPlayer.waypointCurrent = 0; ourPlayer.waypointEndSprite = 0; ourPlayer.currentX = ourPlayer.waypointsX[0] = mapEnterX; ourPlayer.currentY = ourPlayer.waypointsY[0] = mapEnterY; } playerCount = 0; ourPlayer = makePlayer(serverIndex, mapEnterX, mapEnterY, mobSprite); int newPlayerCount = DataOperations.getIntFromByteArray(data, currentOffset, 8); currentOffset += 8; for (int currentNewPlayer = 0; currentNewPlayer < newPlayerCount; currentNewPlayer++) { Mob lastMob = getLastPlayer(DataOperations .getIntFromByteArray(data, currentOffset, 16)); currentOffset += 16; int nextPlayer = DataOperations.getIntFromByteArray(data, currentOffset, 1); // 1 currentOffset++; if (nextPlayer != 0) { int waypointsLeft = DataOperations.getIntFromByteArray( data, currentOffset, 1); // 2 currentOffset++; if (waypointsLeft == 0) { int currentNextSprite = DataOperations .getIntFromByteArray(data, currentOffset, 3); // 3 currentOffset += 3; int currentWaypoint = lastMob.waypointCurrent; int newWaypointX = lastMob.waypointsX[currentWaypoint]; int newWaypointY = lastMob.waypointsY[currentWaypoint]; if (currentNextSprite == 2 || currentNextSprite == 1 || currentNextSprite == 3) newWaypointX += magicLoc; if (currentNextSprite == 6 || currentNextSprite == 5 || currentNextSprite == 7) newWaypointX -= magicLoc; if (currentNextSprite == 4 || currentNextSprite == 3 || currentNextSprite == 5) newWaypointY += magicLoc; if (currentNextSprite == 0 || currentNextSprite == 1 || currentNextSprite == 7) newWaypointY -= magicLoc; lastMob.nextSprite = currentNextSprite; lastMob.waypointCurrent = currentWaypoint = (currentWaypoint + 1) % 10; lastMob.waypointsX[currentWaypoint] = newWaypointX; lastMob.waypointsY[currentWaypoint] = newWaypointY; } else { int needsNextSprite = DataOperations .getIntFromByteArray(data, currentOffset, 4); currentOffset += 4; if ((needsNextSprite & 0xc) == 12) { continue; } lastMob.nextSprite = needsNextSprite; } } playerArray[playerCount++] = lastMob; } int mobCount = 0; while (currentOffset + 24 < length * 8) { int mobIndex = DataOperations.getIntFromByteArray(data, currentOffset, 16); currentOffset += 16; int areaMobX = DataOperations.getIntFromByteArray(data, currentOffset, 5); currentOffset += 5; if (areaMobX > 15) areaMobX -= 32; int areaMobY = DataOperations.getIntFromByteArray(data, currentOffset, 5); currentOffset += 5; if (areaMobY > 15) areaMobY -= 32; int mobArrayMobID = DataOperations.getIntFromByteArray( data, currentOffset, 4); currentOffset += 4; int addIndex = DataOperations.getIntFromByteArray(data, currentOffset, 1); currentOffset++; int mobX = (getSectionX() + areaMobX) * magicLoc + 64; int mobY = (getSectionY() + areaMobY) * magicLoc + 64; makePlayer(mobIndex, mobX, mobY, mobArrayMobID); if (addIndex == 0) mobArrayIndexes[mobCount++] = mobIndex; } if (mobCount > 0) { super.streamClass.createPacket(83); super.streamClass.add2ByteInt(mobCount); for (int currentMob = 0; currentMob < mobCount; currentMob++) { Mob dummyMob = mobArray[mobArrayIndexes[currentMob]]; super.streamClass.add2ByteInt(dummyMob.serverIndex); super.streamClass.add2ByteInt(dummyMob.mobIntUnknown); } super.streamClass.formatPacket(); mobCount = 0; } loading = false; return; } if (command == 109) { if (needsClear) { for (int i = 0; i < groundItemType.length; i++) { groundItemType[i] = -1; groundItemX[i] = -1; groundItemY[i] = -1; } needsClear = false; } for (int l = 1; l < length;) if (DataOperations.getUnsignedByte(data[l]) == 255) { // ??? int newCount = 0; int newSectionX = getSectionX() + data[l + 1] >> 3; int newSectionY = getSectionY() + data[l + 2] >> 3; l += 3; for (int groundItem = 0; groundItem < groundItemCount; groundItem++) { int newX = (groundItemX[groundItem] >> 3) - newSectionX; int newY = (groundItemY[groundItem] >> 3) - newSectionY; if (newX != 0 || newY != 0) { if (groundItem != newCount) { groundItemX[newCount] = groundItemX[groundItem]; groundItemY[newCount] = groundItemY[groundItem]; groundItemType[newCount] = groundItemType[groundItem]; groundItemObjectVar[newCount] = groundItemObjectVar[groundItem]; } newCount++; } } groundItemCount = newCount; } else { int i8 = DataOperations.getUnsigned2Bytes(data, l); l += 2; int k14 = getSectionX() + data[l++]; int j19 = getSectionY() + data[l++]; if ((i8 & 0x8000) == 0) { // New Item groundItemX[groundItemCount] = k14; groundItemY[groundItemCount] = j19; groundItemType[groundItemCount] = i8; groundItemObjectVar[groundItemCount] = 0; for (int k23 = 0; k23 < objectCount; k23++) { if (objectX[k23] != k14 || objectY[k23] != j19) continue; groundItemObjectVar[groundItemCount] = EntityHandler .getObjectDef(objectType[k23]) .getGroundItemVar(); break; } groundItemCount++; } else { // Known Item i8 &= 0x7fff; int l23 = 0; for (int k26 = 0; k26 < groundItemCount; k26++) { if (groundItemX[k26] != k14 || groundItemY[k26] != j19 || groundItemType[k26] != i8) { // Keep // how // it is if (k26 != l23) { groundItemX[l23] = groundItemX[k26]; groundItemY[l23] = groundItemY[k26]; groundItemType[l23] = groundItemType[k26]; groundItemObjectVar[l23] = groundItemObjectVar[k26]; } l23++; } else { // Remove i8 = -123; } } groundItemCount = l23; } } return; } if (command == 27) { for (int i1 = 1; i1 < length;) if (DataOperations.getUnsignedByte(data[i1]) == 255) { int j8 = 0; int l14 = getSectionX() + data[i1 + 1] >> 3; int k19 = getSectionY() + data[i1 + 2] >> 3; i1 += 3; for (int i24 = 0; i24 < objectCount; i24++) { int l26 = (objectX[i24] >> 3) - l14; int k29 = (objectY[i24] >> 3) - k19; if (l26 != 0 || k29 != 0) { if (i24 != j8) { objectModelArray[j8] = objectModelArray[i24]; objectModelArray[j8].anInt257 = j8; objectX[j8] = objectX[i24]; objectY[j8] = objectY[i24]; objectType[j8] = objectType[i24]; objectID[j8] = objectID[i24]; } j8++; } else { gameCamera.removeModel(objectModelArray[i24]); engineHandle.updateObject(objectX[i24], objectY[i24], objectType[i24], objectID[i24]); } } objectCount = j8; } else { int k8 = DataOperations.getUnsigned2Bytes(data, i1); i1 += 2; int i15 = getSectionX() + data[i1++]; int l19 = getSectionY() + data[i1++]; int l29 = data[i1++]; int j24 = 0; for (int i27 = 0; i27 < objectCount; i27++) if (objectX[i27] != i15 || objectY[i27] != l19 || objectID[i27] != l29) { if (i27 != j24) { objectModelArray[j24] = objectModelArray[i27]; objectModelArray[j24].anInt257 = j24; objectX[j24] = objectX[i27]; objectY[j24] = objectY[i27]; objectType[j24] = objectType[i27]; objectID[j24] = objectID[i27]; } j24++; } else { gameCamera.removeModel(objectModelArray[i27]); engineHandle.updateObject(objectX[i27], objectY[i27], objectType[i27], objectID[i27]); } objectCount = j24; if (k8 != 60000) { engineHandle.registerObjectDir(i15, l19, l29); int i34; int j37; if (l29 == 0 || l29 == 4) { i34 = EntityHandler.getObjectDef(k8).getWidth(); j37 = EntityHandler.getObjectDef(k8) .getHeight(); } else { j37 = EntityHandler.getObjectDef(k8).getWidth(); i34 = EntityHandler.getObjectDef(k8) .getHeight(); } int j40 = ((i15 + i15 + i34) * magicLoc) / 2; int i42 = ((l19 + l19 + j37) * magicLoc) / 2; int k43 = EntityHandler.getObjectDef(k8).modelID; Model model_1 = gameDataModels[k43].method203(); gameCamera.addModel(model_1); model_1.anInt257 = objectCount; model_1.method188(0, l29 * 32, 0); model_1.method190(j40, -engineHandle .getAveragedElevation(j40, i42), i42); model_1.method184(true, 48, 48, -50, -10, -50); engineHandle.method412(i15, l19, k8, l29); if (k8 == 74) model_1.method190(0, -480, 0); objectX[objectCount] = i15; objectY[objectCount] = l19; objectType[objectCount] = k8; objectID[objectCount] = l29; objectModelArray[objectCount++] = model_1; } } return; }// command == 48 if (command == 114) { int invOffset = 1; inventoryCount = data[invOffset++] & 0xff; for (int invItem = 0; invItem < inventoryCount; invItem++) { int j15 = DataOperations.getUnsigned2Bytes(data, invOffset); invOffset += 2; getInventoryItems()[invItem] = (j15 & 0x7fff); wearing[invItem] = j15 / 32768; if (EntityHandler.getItemDef(j15 & 0x7fff).isStackable()) { inventoryItemsCount[invItem] = DataOperations.readInt( data, invOffset); invOffset += 4; } else { inventoryItemsCount[invItem] = 1; } } return; } if (command == 53) { int mobCount = DataOperations.getUnsigned2Bytes(data, 1); int mobUpdateOffset = 3; for (int currentMob = 0; currentMob < mobCount; currentMob++) { int mobArrayIndex = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mobArrayIndex < 0 || mobArrayIndex > mobArray.length) { return; } Mob mob = mobArray[mobArrayIndex]; if (mob == null) { return; } byte mobUpdateType = data[mobUpdateOffset++]; if (mobUpdateType == 0) { int i30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.anInt163 = 150; mob.anInt162 = i30; } } else if (mobUpdateType == 1) { // Player talking byte byte7 = data[mobUpdateOffset++]; if (mob != null) { String s2 = DataConversions.byteToString(data, mobUpdateOffset, byte7); mob.lastMessageTimeout = 150; mob.lastMessage = s2; displayMessage(mob.name + ": " + mob.lastMessage, 2, mob.admin); } mobUpdateOffset += byte7; } else if (mobUpdateType == 2) { // Someone getting hit. int j30 = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); int hits = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); int hitsBase = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); if (mob != null) { mob.anInt164 = j30; mob.hitPointsCurrent = hits; mob.hitPointsBase = hitsBase; mob.combatTimer = 200; if (mob == ourPlayer) { playerStatCurrent[3] = hits; playerStatBase[3] = hitsBase; showWelcomeBox = false; // showServerMessageBox = false; } } } else if (mobUpdateType == 3) { // Projectile an npc.. int k30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; int k34 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.attackingCameraInt = k30; mob.attackingNpcIndex = k34; mob.attackingMobIndex = -1; mob.anInt176 = attackingInt40; } } else if (mobUpdateType == 4) { // Projectile another // player. int l30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; int l34 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.attackingCameraInt = l30; mob.attackingMobIndex = l34; mob.attackingNpcIndex = -1; mob.anInt176 = attackingInt40; } } else if (mobUpdateType == 5) { // Apperance update if (mob != null) { mob.mobIntUnknown = DataOperations .getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; mob.nameLong = DataOperations.getUnsigned8Bytes( data, mobUpdateOffset); mobUpdateOffset += 8; mob.name = DataOperations .longToString(mob.nameLong); int i31 = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset++; for (int i35 = 0; i35 < i31; i35++) { mob.animationCount[i35] = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset++; } for (int l37 = i31; l37 < 12; l37++) mob.animationCount[l37] = 0; mob.colourHairType = data[mobUpdateOffset++] & 0xff; mob.colourTopType = data[mobUpdateOffset++] & 0xff; mob.colourBottomType = data[mobUpdateOffset++] & 0xff; mob.colourSkinType = data[mobUpdateOffset++] & 0xff; mob.level = data[mobUpdateOffset++] & 0xff; mob.anInt179 = data[mobUpdateOffset++] & 0xff; mob.admin = data[mobUpdateOffset++] & 0xff; } else { mobUpdateOffset += 14; int j31 = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset += j31 + 1; } } else if (mobUpdateType == 6) { // private player talking byte byte8 = data[mobUpdateOffset]; mobUpdateOffset++; if (mob != null) { String s3 = DataConversions.byteToString(data, mobUpdateOffset, byte8); mob.lastMessageTimeout = 150; mob.lastMessage = s3; if (mob == ourPlayer) displayMessage(mob.name + ": " + mob.lastMessage, 5, mob.admin); } mobUpdateOffset += byte8; } } return; } if (command == 129) { combatStyle = DataOperations.getUnsignedByte(data[1]); return; } if (command == 95) { for (int l1 = 1; l1 < length;) if (DataOperations.getUnsignedByte(data[l1]) == 255) { int j9 = 0; int l15 = getSectionX() + data[l1 + 1] >> 3; int j20 = getSectionY() + data[l1 + 2] >> 3; l1 += 3; for (int currentDoor = 0; currentDoor < doorCount; currentDoor++) { int j27 = (doorX[currentDoor] >> 3) - l15; int k31 = (doorY[currentDoor] >> 3) - j20; if (j27 != 0 || k31 != 0) { if (currentDoor != j9) { doorModel[j9] = doorModel[currentDoor]; doorModel[j9].anInt257 = j9 + 10000; doorX[j9] = doorX[currentDoor]; doorY[j9] = doorY[currentDoor]; doorDirection[j9] = doorDirection[currentDoor]; doorType[j9] = doorType[currentDoor]; } j9++; } else { gameCamera.removeModel(doorModel[currentDoor]); engineHandle.updateDoor(doorX[currentDoor], doorY[currentDoor], doorDirection[currentDoor], doorType[currentDoor]); } } doorCount = j9; } else { int k9 = DataOperations.getUnsigned2Bytes(data, l1); l1 += 2; int i16 = getSectionX() + data[l1++]; int k20 = getSectionY() + data[l1++]; byte byte5 = data[l1++]; int k27 = 0; for (int l31 = 0; l31 < doorCount; l31++) if (doorX[l31] != i16 || doorY[l31] != k20 || doorDirection[l31] != byte5) { if (l31 != k27) { doorModel[k27] = doorModel[l31]; doorModel[k27].anInt257 = k27 + 10000; doorX[k27] = doorX[l31]; doorY[k27] = doorY[l31]; doorDirection[k27] = doorDirection[l31]; doorType[k27] = doorType[l31]; } k27++; } else { gameCamera.removeModel(doorModel[l31]); engineHandle.updateDoor(doorX[l31], doorY[l31], doorDirection[l31], doorType[l31]); } doorCount = k27; if (k9 != 60000) { // 65535) { engineHandle.method408(i16, k20, byte5, k9); Model model = makeModel(i16, k20, byte5, k9, doorCount); doorModel[doorCount] = model; doorX[doorCount] = i16; doorY[doorCount] = k20; doorType[doorCount] = k9; doorDirection[doorCount++] = byte5; } } return; } if (command == 77) { lastNpcCount = npcCount; npcCount = 0; for (int lastNpcIndex = 0; lastNpcIndex < lastNpcCount; lastNpcIndex++) lastNpcArray[lastNpcIndex] = npcArray[lastNpcIndex]; int newNpcOffset = 8; int newNpcCount = DataOperations.getIntFromByteArray(data, newNpcOffset, 8); newNpcOffset += 8; for (int newNpcIndex = 0; newNpcIndex < newNpcCount; newNpcIndex++) { Mob newNPC = getLastNpc(DataOperations.getIntFromByteArray( data, newNpcOffset, 16)); newNpcOffset += 16; int npcNeedsUpdate = DataOperations.getIntFromByteArray( data, newNpcOffset, 1); newNpcOffset++; if (npcNeedsUpdate != 0) { int i32 = DataOperations.getIntFromByteArray(data, newNpcOffset, 1); newNpcOffset++; if (i32 == 0) { int nextSprite = DataOperations .getIntFromByteArray(data, newNpcOffset, 3); newNpcOffset += 3; int waypointCurrent = newNPC.waypointCurrent; int waypointX = newNPC.waypointsX[waypointCurrent]; int waypointY = newNPC.waypointsY[waypointCurrent]; if (nextSprite == 2 || nextSprite == 1 || nextSprite == 3) waypointX += magicLoc; if (nextSprite == 6 || nextSprite == 5 || nextSprite == 7) waypointX -= magicLoc; if (nextSprite == 4 || nextSprite == 3 || nextSprite == 5) waypointY += magicLoc; if (nextSprite == 0 || nextSprite == 1 || nextSprite == 7) waypointY -= magicLoc; newNPC.nextSprite = nextSprite; newNPC.waypointCurrent = waypointCurrent = (waypointCurrent + 1) % 10; newNPC.waypointsX[waypointCurrent] = waypointX; newNPC.waypointsY[waypointCurrent] = waypointY; } else { int nextSpriteOffset = DataOperations .getIntFromByteArray(data, newNpcOffset, 4); newNpcOffset += 4; if ((nextSpriteOffset & 0xc) == 12) { continue; } newNPC.nextSprite = nextSpriteOffset; } } npcArray[npcCount++] = newNPC; } while (newNpcOffset + 34 < length * 8) { int serverIndex = DataOperations.getIntFromByteArray(data, newNpcOffset, 16); newNpcOffset += 16; int i28 = DataOperations.getIntFromByteArray(data, newNpcOffset, 5); newNpcOffset += 5; if (i28 > 15) i28 -= 32; int j32 = DataOperations.getIntFromByteArray(data, newNpcOffset, 5); newNpcOffset += 5; if (j32 > 15) j32 -= 32; int nextSprite = DataOperations.getIntFromByteArray(data, newNpcOffset, 4); newNpcOffset += 4; int x = (getSectionX() + i28) * magicLoc + 64; int y = (getSectionY() + j32) * magicLoc + 64; int type = DataOperations.getIntFromByteArray(data, newNpcOffset, 10); newNpcOffset += 10; if (type >= EntityHandler.npcCount()) type = 24; addNPC(serverIndex, x, y, nextSprite, type); } return; } if (command == 190) { int j2 = DataOperations.getUnsigned2Bytes(data, 1); int i10 = 3; for (int k16 = 0; k16 < j2; k16++) { int i21 = DataOperations.getUnsigned2Bytes(data, i10); i10 += 2; Mob mob_2 = npcRecordArray[i21]; int j28 = DataOperations.getUnsignedByte(data[i10]); i10++; if (j28 == 1) { int k32 = DataOperations.getUnsigned2Bytes(data, i10); i10 += 2; byte byte9 = data[i10]; i10++; if (mob_2 != null) { String s4 = DataConversions.byteToString(data, i10, byte9); mob_2.lastMessageTimeout = 150; mob_2.lastMessage = s4; if (k32 == ourPlayer.serverIndex) displayMessage("@yel@" + EntityHandler.getNpcDef(mob_2.type) .getName() + ": " + mob_2.lastMessage, 5, 0); } i10 += byte9; } else if (j28 == 2) { int l32 = DataOperations.getUnsignedByte(data[i10]); i10++; int i36 = DataOperations.getUnsignedByte(data[i10]); i10++; int k38 = DataOperations.getUnsignedByte(data[i10]); i10++; if (mob_2 != null) { mob_2.anInt164 = l32; mob_2.hitPointsCurrent = i36; mob_2.hitPointsBase = k38; mob_2.combatTimer = 200; } } } return; } if (command == 223) { showQuestionMenu = true; int newQuestionMenuCount = DataOperations .getUnsignedByte(data[1]); questionMenuCount = newQuestionMenuCount; int newQuestionMenuOffset = 2; for (int l16 = 0; l16 < newQuestionMenuCount; l16++) { int newQuestionMenuQuestionLength = DataOperations .getUnsignedByte(data[newQuestionMenuOffset]); newQuestionMenuOffset++; questionMenuAnswer[l16] = new String(data, newQuestionMenuOffset, newQuestionMenuQuestionLength); newQuestionMenuOffset += newQuestionMenuQuestionLength; } return; } if (command == 127) { showQuestionMenu = false; return; }// if (command == 109) { if (command == 131) { needsClear = true; notInWilderness = true; hasWorldInfo = true; serverIndex = DataOperations.getUnsigned2Bytes(data, 1); wildX = DataOperations.getUnsigned2Bytes(data, 3); wildY = DataOperations.getUnsigned2Bytes(data, 5); wildYSubtract = DataOperations.getUnsigned2Bytes(data, 7); wildYMultiplier = DataOperations.getUnsigned2Bytes(data, 9); wildY -= wildYSubtract * wildYMultiplier; return; } if (command == 180) { int l2 = 1; for (int k10 = 0; k10 < 18; k10++) { playerStatCurrent[k10] = DataOperations .getUnsignedByte(data[l2++]); } for (int i17 = 0; i17 < 18; i17++) { playerStatBase[i17] = DataOperations .getUnsignedByte(data[l2++]); } for (int k21 = 0; k21 < 18; k21++) { playerStatExperience[k21] = DataOperations .readInt(data, l2); l2 += 4; } expGained = 0; return; }// command == 114 if (command == 177) { int i3 = 1; for (int x = 0; x < 6; x++) { equipmentStatus[x] = DataOperations.getSigned2Bytes(data, i3); i3 += 2; } return; } if (command == 165) { playerAliveTimeout = 250; return; } if (command == 115) { int thingLength = (length - 1) / 4; for (int currentThing = 0; currentThing < thingLength; currentThing++) { int currentItemSectionX = getSectionX() + DataOperations.getSigned2Bytes(data, 1 + currentThing * 4) >> 3; int currentItemSectionY = getSectionY() + DataOperations.getSigned2Bytes(data, 3 + currentThing * 4) >> 3; int currentCount = 0; for (int currentItem = 0; currentItem < groundItemCount; currentItem++) { int currentItemOffsetX = (groundItemX[currentItem] >> 3) - currentItemSectionX; int currentItemOffsetY = (groundItemY[currentItem] >> 3) - currentItemSectionY; if (currentItemOffsetX != 0 || currentItemOffsetY != 0) { if (currentItem != currentCount) { groundItemX[currentCount] = groundItemX[currentItem]; groundItemY[currentCount] = groundItemY[currentItem]; groundItemType[currentCount] = groundItemType[currentItem]; groundItemObjectVar[currentCount] = groundItemObjectVar[currentItem]; } currentCount++; } } groundItemCount = currentCount; currentCount = 0; for (int j33 = 0; j33 < objectCount; j33++) { int k36 = (objectX[j33] >> 3) - currentItemSectionX; int l38 = (objectY[j33] >> 3) - currentItemSectionY; if (k36 != 0 || l38 != 0) { if (j33 != currentCount) { objectModelArray[currentCount] = objectModelArray[j33]; objectModelArray[currentCount].anInt257 = currentCount; objectX[currentCount] = objectX[j33]; objectY[currentCount] = objectY[j33]; objectType[currentCount] = objectType[j33]; objectID[currentCount] = objectID[j33]; } currentCount++; } else { gameCamera.removeModel(objectModelArray[j33]); engineHandle.updateObject(objectX[j33], objectY[j33], objectType[j33], objectID[j33]); } } objectCount = currentCount; currentCount = 0; for (int l36 = 0; l36 < doorCount; l36++) { int i39 = (doorX[l36] >> 3) - currentItemSectionX; int j41 = (doorY[l36] >> 3) - currentItemSectionY; if (i39 != 0 || j41 != 0) { if (l36 != currentCount) { doorModel[currentCount] = doorModel[l36]; doorModel[currentCount].anInt257 = currentCount + 10000; doorX[currentCount] = doorX[l36]; doorY[currentCount] = doorY[l36]; doorDirection[currentCount] = doorDirection[l36]; doorType[currentCount] = doorType[l36]; } currentCount++; } else { gameCamera.removeModel(doorModel[l36]); engineHandle.updateDoor(doorX[l36], doorY[l36], doorDirection[l36], doorType[l36]); } } doorCount = currentCount; } return; } if (command == 230) { showDrawPointsScreen = true; int pkbytes = 1; pkatk = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkdef = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkstr = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkrange = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkmagic = DataOperations.readInt(data, pkbytes); } if (command == 207) { showCharacterLookScreen = true; return; } if (command == 4) { int currentMob = DataOperations.getUnsigned2Bytes(data, 1); if (mobArray[currentMob] != null) // todo: check what that // mobArray is tradeOtherPlayerName = mobArray[currentMob].name; showTradeWindow = true; tradeOtherAccepted = false; tradeWeAccepted = false; tradeMyItemCount = 0; tradeOtherItemCount = 0; return; } if (command == 187) { showTradeWindow = false; showTradeConfirmWindow = false; return; } if (command == 250) { tradeOtherItemCount = data[1] & 0xff; int l3 = 2; for (int i11 = 0; i11 < tradeOtherItemCount; i11++) { tradeOtherItems[i11] = DataOperations.getUnsigned2Bytes( data, l3); l3 += 2; tradeOtherItemsCount[i11] = DataOperations .readInt(data, l3); l3 += 4; } tradeOtherAccepted = false; tradeWeAccepted = false; return; } if (command == 92) { tradeOtherAccepted = data[1] == 1; } if (command == 253) { showShop = true; int i4 = 1; int j11 = data[i4++] & 0xff; byte byte4 = data[i4++]; shopItemSellPriceModifier = data[i4++] & 0xff; shopItemBuyPriceModifier = data[i4++] & 0xff; for (int i22 = 0; i22 < 40; i22++) shopItems[i22] = -1; for (int j25 = 0; j25 < j11; j25++) { shopItems[j25] = DataOperations.getUnsigned2Bytes(data, i4); i4 += 2; shopItemCount[j25] = DataOperations.getUnsigned2Bytes(data, i4); i4 += 2; shopItemsBuyPrice[j25] = DataOperations.getUnsigned4Bytes( data, i4); i4 += 4; shopItemsSellPrice[j25] = DataOperations.getUnsigned4Bytes( data, i4); i4 += 4; } if (byte4 == 1) { int l28 = 39; for (int k33 = 0; k33 < inventoryCount; k33++) { if (l28 < j11) break; boolean flag2 = false; for (int j39 = 0; j39 < 40; j39++) { if (shopItems[j39] != getInventoryItems()[k33]) continue; flag2 = true; break; } if (getInventoryItems()[k33] == 10) flag2 = true; if (!flag2) { // our own item that's not in stock. shopItems[l28] = getInventoryItems()[k33] & 0x7fff; shopItemsSellPrice[l28] = EntityHandler .getItemDef(shopItems[l28]).basePrice - (int) (EntityHandler .getItemDef(shopItems[l28]).basePrice / 2.5); shopItemsSellPrice[l28] = shopItemsSellPrice[l28] - (int) (shopItemsSellPrice[l28] * 0.10); shopItemCount[l28] = 0; l28--; } } } if (selectedShopItemIndex >= 0 && selectedShopItemIndex < 40 && shopItems[selectedShopItemIndex] != selectedShopItemType) { selectedShopItemIndex = -1; selectedShopItemType = -2; } return; } if (command == 220) { showShop = false; return; } if (command == 18) { tradeWeAccepted = data[1] == 1; } if (command == 152) { configAutoCameraAngle = DataOperations.getUnsignedByte(data[1]) == 1; configMouseButtons = DataOperations.getUnsignedByte(data[2]) == 1; configSoundEffects = DataOperations.getUnsignedByte(data[3]) == 1; showRoof = DataOperations.getUnsignedByte(data[4]) == 1; autoScreenshot = DataOperations.getUnsignedByte(data[5]) == 1; combatWindow = DataOperations.getUnsignedByte(data[6]) == 1; return; } if (command == 209) { for (int currentPrayer = 0; currentPrayer < length - 1; currentPrayer++) { boolean prayerOff = data[currentPrayer + 1] == 1; if (!prayerOn[currentPrayer] && prayerOff) playSound("prayeron"); if (prayerOn[currentPrayer] && !prayerOff) playSound("prayeroff"); prayerOn[currentPrayer] = prayerOff; } return; } if (command == 93) { showBank = true; int l4 = 1; newBankItemCount = data[l4++] & 0xff; bankItemsMax = data[l4++] & 0xff; for (int k11 = 0; k11 < newBankItemCount; k11++) { newBankItems[k11] = DataOperations.getUnsigned2Bytes(data, l4); l4 += 2; newBankItemsCount[k11] = DataOperations.getUnsigned4Bytes( data, l4); l4 += 4; } updateBankItems(); return; } if (command == 171) { showBank = false; return; } if (command == 211) { int idx = data[1] & 0xFF; int oldExp = playerStatExperience[idx]; playerStatExperience[idx] = DataOperations.readInt(data, 2); if (playerStatExperience[idx] > oldExp) { expGained += (playerStatExperience[idx] - oldExp); } return; } if (command == 229) { int j5 = DataOperations.getUnsigned2Bytes(data, 1); if (mobArray[j5] != null) { duelOpponentName = mobArray[j5].name; } showDuelWindow = true; duelMyItemCount = 0; duelOpponentItemCount = 0; duelOpponentAccepted = false; duelMyAccepted = false; duelNoRetreating = false; duelNoMagic = false; duelNoPrayer = false; duelNoWeapons = false; return; } if (command == 160) { showDuelWindow = false; showDuelConfirmWindow = false; return; } if (command == 251) { showTradeConfirmWindow = true; tradeConfirmAccepted = false; showTradeWindow = false; int k5 = 1; tradeConfirmOtherNameLong = DataOperations.getUnsigned8Bytes( data, k5); k5 += 8; tradeConfirmOtherItemCount = data[k5++] & 0xff; for (int l11 = 0; l11 < tradeConfirmOtherItemCount; l11++) { tradeConfirmOtherItems[l11] = DataOperations .getUnsigned2Bytes(data, k5); k5 += 2; tradeConfirmOtherItemsCount[l11] = DataOperations.readInt( data, k5); k5 += 4; } tradeConfirmItemCount = data[k5++] & 0xff; for (int k17 = 0; k17 < tradeConfirmItemCount; k17++) { tradeConfirmItems[k17] = DataOperations.getUnsigned2Bytes( data, k5); k5 += 2; tradeConfirmItemsCount[k17] = DataOperations.readInt(data, k5); k5 += 4; } return; } if (command == 63) { duelOpponentItemCount = data[1] & 0xff; int l5 = 2; for (int i12 = 0; i12 < duelOpponentItemCount; i12++) { duelOpponentItems[i12] = DataOperations.getUnsigned2Bytes( data, l5); l5 += 2; duelOpponentItemsCount[i12] = DataOperations.readInt(data, l5); l5 += 4; } duelOpponentAccepted = false; duelMyAccepted = false; return; } if (command == 198) { duelNoRetreating = data[1] == 1; duelNoMagic = data[2] == 1; duelNoPrayer = data[3] == 1; duelNoWeapons = data[4] == 1; duelOpponentAccepted = false; duelMyAccepted = false; return; } if (command == 139) { int bankDataOffset = 1; int bankSlot = data[bankDataOffset++] & 0xff; int bankItemId = DataOperations.getUnsigned2Bytes(data, bankDataOffset); bankDataOffset += 2; int bankItemCount = DataOperations.getUnsigned4Bytes(data, bankDataOffset); bankDataOffset += 4; if (bankItemCount == 0) { newBankItemCount--; for (int currentBankSlot = bankSlot; currentBankSlot < newBankItemCount; currentBankSlot++) { newBankItems[currentBankSlot] = newBankItems[currentBankSlot + 1]; newBankItemsCount[currentBankSlot] = newBankItemsCount[currentBankSlot + 1]; } } else { newBankItems[bankSlot] = bankItemId; newBankItemsCount[bankSlot] = bankItemCount; if (bankSlot >= newBankItemCount) newBankItemCount = bankSlot + 1; } updateBankItems(); return; } if (command == 228) { int j6 = 1; int k12 = 1; int i18 = data[j6++] & 0xff; int k22 = DataOperations.getUnsigned2Bytes(data, j6); j6 += 2; if (EntityHandler.getItemDef(k22 & 0x7fff).isStackable()) { k12 = DataOperations.readInt(data, j6); j6 += 4; } getInventoryItems()[i18] = k22 & 0x7fff; wearing[i18] = k22 / 32768; inventoryItemsCount[i18] = k12; if (i18 >= inventoryCount) inventoryCount = i18 + 1; return; } if (command == 191) { int k6 = data[1] & 0xff; inventoryCount--; for (int l12 = k6; l12 < inventoryCount; l12++) { getInventoryItems()[l12] = getInventoryItems()[l12 + 1]; inventoryItemsCount[l12] = inventoryItemsCount[l12 + 1]; wearing[l12] = wearing[l12 + 1]; } return; } if (command == 208) { int pointer = 1; int idx = data[pointer++] & 0xff; int oldExp = playerStatExperience[idx]; playerStatCurrent[idx] = DataOperations .getUnsignedByte(data[pointer++]); playerStatBase[idx] = DataOperations .getUnsignedByte(data[pointer++]); playerStatExperience[idx] = DataOperations.readInt(data, pointer); pointer += 4; if (playerStatExperience[idx] > oldExp) { expGained += (playerStatExperience[idx] - oldExp); } return; } if (command == 65) { duelOpponentAccepted = data[1] == 1; } if (command == 197) { duelMyAccepted = data[1] == 1; } if (command == 147) { showDuelConfirmWindow = true; duelWeAccept = false; showDuelWindow = false; int i7 = 1; duelOpponentNameLong = DataOperations.getUnsigned8Bytes(data, i7); i7 += 8; duelConfirmOpponentItemCount = data[i7++] & 0xff; for (int j13 = 0; j13 < duelConfirmOpponentItemCount; j13++) { duelConfirmOpponentItems[j13] = DataOperations .getUnsigned2Bytes(data, i7); i7 += 2; duelConfirmOpponentItemsCount[j13] = DataOperations .readInt(data, i7); i7 += 4; } duelConfirmMyItemCount = data[i7++] & 0xff; for (int j18 = 0; j18 < duelConfirmMyItemCount; j18++) { duelConfirmMyItems[j18] = DataOperations.getUnsigned2Bytes( data, i7); i7 += 2; duelConfirmMyItemsCount[j18] = DataOperations.readInt(data, i7); i7 += 4; } duelCantRetreat = data[i7++] & 0xff; duelUseMagic = data[i7++] & 0xff; duelUsePrayer = data[i7++] & 0xff; duelUseWeapons = data[i7++] & 0xff; return; } if (command == 11) { String s = new String(data, 1, length - 1); playSound(s); return; } if (command == 23) { if (anInt892 < 50) { int j7 = data[1] & 0xff; int k13 = data[2] + getSectionX(); int k18 = data[3] + getSectionY(); anIntArray782[anInt892] = j7; anIntArray923[anInt892] = 0; anIntArray944[anInt892] = k13; anIntArray757[anInt892] = k18; anInt892++; } return; } if (command == 248) { if (!hasReceivedWelcomeBoxDetails) { lastLoggedInDays = DataOperations .getUnsigned2Bytes(data, 1); subscriptionLeftDays = DataOperations.getUnsigned2Bytes( data, 3); lastLoggedInAddress = new String(data, 5, length - 5); showWelcomeBox = true; hasReceivedWelcomeBoxDetails = true; } return; } if (command == 148) { serverMessage = new String(data, 1, length - 1); showServerMessageBox = true; serverMessageBoxTop = false; return; } if (command == 64) { serverMessage = new String(data, 1, length - 1); showServerMessageBox = true; serverMessageBoxTop = true; return; } if (command == 126) { fatigue = DataOperations.getUnsigned2Bytes(data, 1); return; } if (command == 206) { if (!sleeping) { } sleeping = true; gameMenu.updateText(chatHandle, ""); super.inputText = ""; super.enteredText = ""; sleepEquation = DataOperations.getImage(data, 1, length); // sleepMessage = null; return; } if (command == 182) { int offset = 1; questPoints = DataOperations.getUnsigned2Bytes(data, offset); offset += 2; for (int i = 0; i < questName.length; i++) questStage[i] = data[offset + i]; return; } if (command == 224) { sleeping = false; sleepMessage = null; return; } if (command == 225) { sleepMessage = "Incorrect - please try again..."; return; } if (command == 174) { DataOperations.getUnsigned2Bytes(data, 1); return; } if (command == 181) { if (autoScreenshot) { takeScreenshot(false); } return; } if (command == 172) { systemUpdate = DataOperations.getUnsigned2Bytes(data, 1) * 32; return; } // System.out.println("Bad ID: " + command + " Length: " + length); } catch (Exception e) { // e.printStackTrace(); /* * if (handlePacketErrorCount < 3) { * super.streamClass.createPacket(156); * super.streamClass.addString(runtimeexception.toString()); * super.streamClass.formatPacket(); handlePacketErrorCount++; } */ } } private String sleepMessage = ""; protected final void lostConnection() { systemUpdate = 0; if (logoutTimeout != 0) { resetIntVars(); return; } super.lostConnection(); } private final void playSound(String s) { if (audioReader == null) { return; } if (configSoundEffects) { return; } audioReader.loadData(sounds, DataOperations.method358(s + ".pcm", sounds), DataOperations.method359(s + ".pcm", sounds)); } private final boolean sendWalkCommand(int walkSectionX, int walkSectionY, int x1, int y1, int x2, int y2, boolean stepBoolean, boolean coordsEqual) { // todo: needs checking int stepCount = engineHandle.getStepCount(walkSectionX, walkSectionY, x1, y1, x2, y2, sectionXArray, sectionYArray, stepBoolean); if (stepCount == -1) if (coordsEqual) { stepCount = 1; sectionXArray[0] = x1; sectionYArray[0] = y1; } else { return false; } stepCount--; walkSectionX = sectionXArray[stepCount]; walkSectionY = sectionYArray[stepCount]; stepCount--; if (coordsEqual) super.streamClass.createPacket(246); else super.streamClass.createPacket(132); super.streamClass.add2ByteInt(walkSectionX + getAreaX()); super.streamClass.add2ByteInt(walkSectionY + getAreaY()); if (coordsEqual && stepCount == -1 && (walkSectionX + getAreaX()) % 5 == 0) stepCount = 0; for (int currentStep = stepCount; currentStep >= 0 && currentStep > stepCount - 25; currentStep--) { super.streamClass .addByte(sectionXArray[currentStep] - walkSectionX); super.streamClass .addByte(sectionYArray[currentStep] - walkSectionY); } super.streamClass.formatPacket(); actionPictureType = -24; actionPictureX = super.mouseX; // guessing the little red/yellow x that // appears when you click actionPictureY = super.mouseY; return true; } private final boolean sendWalkCommandIgnoreCoordsEqual(int walkSectionX, int walkSectionY, int x1, int y1, int x2, int y2, boolean stepBoolean, boolean coordsEqual) { int stepCount = engineHandle.getStepCount(walkSectionX, walkSectionY, x1, y1, x2, y2, sectionXArray, sectionYArray, stepBoolean); if (stepCount == -1) return false; stepCount--; walkSectionX = sectionXArray[stepCount]; walkSectionY = sectionYArray[stepCount]; stepCount--; if (coordsEqual) super.streamClass.createPacket(246); else super.streamClass.createPacket(132); super.streamClass.add2ByteInt(walkSectionX + getAreaX()); super.streamClass.add2ByteInt(walkSectionY + getAreaY()); if (coordsEqual && stepCount == -1 && (walkSectionX + getAreaX()) % 5 == 0) stepCount = 0; for (int currentStep = stepCount; currentStep >= 0 && currentStep > stepCount - 25; currentStep--) { super.streamClass .addByte(sectionXArray[currentStep] - walkSectionX); super.streamClass .addByte(sectionYArray[currentStep] - walkSectionY); } super.streamClass.formatPacket(); actionPictureType = -24; actionPictureX = super.mouseX; actionPictureY = super.mouseY; return true; } public final Image createImage(int i, int j) { if (GameWindow.gameFrame != null) { return GameWindow.gameFrame.createImage(i, j); } return super.createImage(i, j); } private final void drawTradeConfirmWindow() { int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 16, 192); int i = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 16, 468, 246, i, 160); gameGraphics.drawText("Please confirm your trade with @yel@" + DataOperations.longToString(tradeConfirmOtherNameLong), byte0 + 234, byte1 + 12, 1, 0xffffff); gameGraphics.drawText("You are about to give:", byte0 + 117, byte1 + 30, 1, 0xffff00); for (int j = 0; j < tradeConfirmItemCount; j++) { String s = EntityHandler.getItemDef(tradeConfirmItems[j]).getName(); if (EntityHandler.getItemDef(tradeConfirmItems[j]).isStackable()) s = s + " x " + method74(tradeConfirmItemsCount[j]); gameGraphics.drawText(s, byte0 + 117, byte1 + 42 + j * 12, 1, 0xffffff); } if (tradeConfirmItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 117, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("In return you will receive:", byte0 + 351, byte1 + 30, 1, 0xffff00); for (int k = 0; k < tradeConfirmOtherItemCount; k++) { String s1 = EntityHandler.getItemDef(tradeConfirmOtherItems[k]) .getName(); if (EntityHandler.getItemDef(tradeConfirmOtherItems[k]) .isStackable()) s1 = s1 + " x " + method74(tradeConfirmOtherItemsCount[k]); gameGraphics.drawText(s1, byte0 + 351, byte1 + 42 + k * 12, 1, 0xffffff); } if (tradeConfirmOtherItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 351, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("Are you sure you want to do this?", byte0 + 234, byte1 + 200, 4, 65535); gameGraphics.drawText( "There is NO WAY to reverse a trade if you change your mind.", byte0 + 234, byte1 + 215, 1, 0xffffff); gameGraphics.drawText("Remember that not all players are trustworthy", byte0 + 234, byte1 + 230, 1, 0xffffff); if (!tradeConfirmAccepted) { gameGraphics.drawPicture((byte0 + 118) - 35, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture((byte0 + 352) - 35, byte1 + 238, SPRITE_MEDIA_START + 26); } else { gameGraphics.drawText("Waiting for other player...", byte0 + 234, byte1 + 250, 1, 0xffff00); } if (mouseButtonClick == 1) { if (super.mouseX < byte0 || super.mouseY < byte1 || super.mouseX > byte0 + 468 || super.mouseY > byte1 + 262) { showTradeConfirmWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 118) - 35 && super.mouseX <= byte0 + 118 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { tradeConfirmAccepted = true; super.streamClass.createPacket(53); // createPacket(73 super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 352) - 35 && super.mouseX <= byte0 + 353 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { showTradeConfirmWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } mouseButtonClick = 0; } } private final void walkToGroundItem(int walkSectionX, int walkSectionY, int x, int y, boolean coordsEqual) { if (sendWalkCommandIgnoreCoordsEqual(walkSectionX, walkSectionY, x, y, x, y, false, coordsEqual)) { return; } else { sendWalkCommand(walkSectionX, walkSectionY, x, y, x, y, true, coordsEqual); return; } } private final Mob addNPC(int serverIndex, int x, int y, int nextSprite, int type) { if (npcRecordArray[serverIndex] == null) { npcRecordArray[serverIndex] = new Mob(); npcRecordArray[serverIndex].serverIndex = serverIndex; } Mob mob = npcRecordArray[serverIndex]; boolean npcAlreadyExists = false; for (int lastNpcIndex = 0; lastNpcIndex < lastNpcCount; lastNpcIndex++) { if (lastNpcArray[lastNpcIndex].serverIndex != serverIndex) continue; npcAlreadyExists = true; break; } if (npcAlreadyExists) { mob.type = type; mob.nextSprite = nextSprite; int waypointCurrent = mob.waypointCurrent; if (x != mob.waypointsX[waypointCurrent] || y != mob.waypointsY[waypointCurrent]) { mob.waypointCurrent = waypointCurrent = (waypointCurrent + 1) % 10; mob.waypointsX[waypointCurrent] = x; mob.waypointsY[waypointCurrent] = y; } } else { mob.serverIndex = serverIndex; mob.waypointEndSprite = 0; mob.waypointCurrent = 0; mob.waypointsX[0] = mob.currentX = x; mob.waypointsY[0] = mob.currentY = y; mob.type = type; mob.nextSprite = mob.currentSprite = nextSprite; mob.stepCount = 0; } npcArray[npcCount++] = mob; return mob; } private final void drawDuelWindow() { if (mouseButtonClick != 0 && itemIncrement == 0) itemIncrement = 1; if (itemIncrement > 0) { int i = super.mouseX - 22 - xAddition; int j = super.mouseY - 36 - yAddition; if (i >= 0 && j >= 0 && i < 468 && j < 262) { if (i > 216 && j > 30 && i < 462 && j < 235) { int k = (i - 217) / 49 + ((j - 31) / 34) * 5; if (k >= 0 && k < inventoryCount) { boolean flag1 = false; int l1 = 0; int k2 = getInventoryItems()[k]; for (int k3 = 0; k3 < duelMyItemCount; k3++) if (duelMyItems[k3] == k2) if (EntityHandler.getItemDef(k2).isStackable()) { for (int i4 = 0; i4 < itemIncrement; i4++) { if (duelMyItemsCount[k3] < inventoryItemsCount[k]) duelMyItemsCount[k3]++; flag1 = true; } } else { l1++; } if (inventoryCount(k2) <= l1) flag1 = true; if (!flag1 && duelMyItemCount < 8) { duelMyItems[duelMyItemCount] = k2; duelMyItemsCount[duelMyItemCount] = 1; duelMyItemCount++; flag1 = true; } if (flag1) { super.streamClass.createPacket(123); super.streamClass.addByte(duelMyItemCount); for (int duelItem = 0; duelItem < duelMyItemCount; duelItem++) { super.streamClass .add2ByteInt(duelMyItems[duelItem]); super.streamClass .add4ByteInt(duelMyItemsCount[duelItem]); } super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } } } if (i > 8 && j > 30 && i < 205 && j < 129) { int l = (i - 9) / 49 + ((j - 31) / 34) * 4; if (l >= 0 && l < duelMyItemCount) { int j1 = duelMyItems[l]; for (int i2 = 0; i2 < itemIncrement; i2++) { if (EntityHandler.getItemDef(j1).isStackable() && duelMyItemsCount[l] > 1) { duelMyItemsCount[l]--; continue; } duelMyItemCount--; mouseDownTime = 0; for (int l2 = l; l2 < duelMyItemCount; l2++) { duelMyItems[l2] = duelMyItems[l2 + 1]; duelMyItemsCount[l2] = duelMyItemsCount[l2 + 1]; } break; } super.streamClass.createPacket(123); super.streamClass.addByte(duelMyItemCount); for (int i3 = 0; i3 < duelMyItemCount; i3++) { super.streamClass.add2ByteInt(duelMyItems[i3]); super.streamClass.add4ByteInt(duelMyItemsCount[i3]); } super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } } boolean flag = false; if (i >= 93 && j >= 221 && i <= 104 && j <= 232) { duelNoRetreating = !duelNoRetreating; flag = true; } if (i >= 93 && j >= 240 && i <= 104 && j <= 251) { duelNoMagic = !duelNoMagic; flag = true; } if (i >= 191 && j >= 221 && i <= 202 && j <= 232) { duelNoPrayer = !duelNoPrayer; flag = true; } if (i >= 191 && j >= 240 && i <= 202 && j <= 251) { duelNoWeapons = !duelNoWeapons; flag = true; } if (flag) { super.streamClass.createPacket(225); super.streamClass.addByte(duelNoRetreating ? 1 : 0); super.streamClass.addByte(duelNoMagic ? 1 : 0); super.streamClass.addByte(duelNoPrayer ? 1 : 0); super.streamClass.addByte(duelNoWeapons ? 1 : 0); super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } if (i >= 217 && j >= 238 && i <= 286 && j <= 259) { duelMyAccepted = true; super.streamClass.createPacket(252); super.streamClass.formatPacket(); } if (i >= 394 && j >= 238 && i < 463 && j < 259) { showDuelWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } } else if (mouseButtonClick != 0) { showDuelWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } mouseButtonClick = 0; itemIncrement = 0; } if (!showDuelWindow) return; int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 12, 0xc90b1d); int i1 = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 468, 18, i1, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 30, 8, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 205, byte1 + 30, 11, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 462, byte1 + 30, 6, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 99, 197, 24, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 192, 197, 23, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 258, 197, 20, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 235, 246, 43, i1, 160); int k1 = 0xd0d0d0; gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 30, 197, 69, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 123, 197, 69, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 215, 197, 43, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 30, 246, 205, k1, 160); for (int j2 = 0; j2 < 3; j2++) gameGraphics.drawLineX(byte0 + 8, byte1 + 30 + j2 * 34, 197, 0); for (int j3 = 0; j3 < 3; j3++) gameGraphics.drawLineX(byte0 + 8, byte1 + 123 + j3 * 34, 197, 0); for (int l3 = 0; l3 < 7; l3++) gameGraphics.drawLineX(byte0 + 216, byte1 + 30 + l3 * 34, 246, 0); for (int k4 = 0; k4 < 6; k4++) { if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 30, 69, 0); if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 123, 69, 0); gameGraphics.drawLineY(byte0 + 216 + k4 * 49, byte1 + 30, 205, 0); } gameGraphics.drawLineX(byte0 + 8, byte1 + 215, 197, 0); gameGraphics.drawLineX(byte0 + 8, byte1 + 257, 197, 0); gameGraphics.drawLineY(byte0 + 8, byte1 + 215, 43, 0); gameGraphics.drawLineY(byte0 + 204, byte1 + 215, 43, 0); gameGraphics.drawString("Preparing to duel with: " + duelOpponentName, byte0 + 1, byte1 + 10, 1, 0xffffff); gameGraphics.drawString("Your Stake", byte0 + 9, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("Opponent's Stake", byte0 + 9, byte1 + 120, 4, 0xffffff); gameGraphics.drawString("Duel Options", byte0 + 9, byte1 + 212, 4, 0xffffff); gameGraphics.drawString("Your Inventory", byte0 + 216, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("No retreating", byte0 + 8 + 1, byte1 + 215 + 16, 3, 0xffff00); gameGraphics.drawString("No magic", byte0 + 8 + 1, byte1 + 215 + 35, 3, 0xffff00); gameGraphics.drawString("No prayer", byte0 + 8 + 102, byte1 + 215 + 16, 3, 0xffff00); gameGraphics.drawString("No weapons", byte0 + 8 + 102, byte1 + 215 + 35, 3, 0xffff00); gameGraphics.drawBoxEdge(byte0 + 93, byte1 + 215 + 6, 11, 11, 0xffff00); if (duelNoRetreating) gameGraphics.drawBox(byte0 + 95, byte1 + 215 + 8, 7, 7, 0xffff00); gameGraphics .drawBoxEdge(byte0 + 93, byte1 + 215 + 25, 11, 11, 0xffff00); if (duelNoMagic) gameGraphics.drawBox(byte0 + 95, byte1 + 215 + 27, 7, 7, 0xffff00); gameGraphics .drawBoxEdge(byte0 + 191, byte1 + 215 + 6, 11, 11, 0xffff00); if (duelNoPrayer) gameGraphics.drawBox(byte0 + 193, byte1 + 215 + 8, 7, 7, 0xffff00); gameGraphics.drawBoxEdge(byte0 + 191, byte1 + 215 + 25, 11, 11, 0xffff00); if (duelNoWeapons) gameGraphics.drawBox(byte0 + 193, byte1 + 215 + 27, 7, 7, 0xffff00); if (!duelMyAccepted) gameGraphics.drawPicture(byte0 + 217, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture(byte0 + 394, byte1 + 238, SPRITE_MEDIA_START + 26); if (duelOpponentAccepted) { gameGraphics.drawText("Other player", byte0 + 341, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("has accepted", byte0 + 341, byte1 + 256, 1, 0xffffff); } if (duelMyAccepted) { gameGraphics.drawText("Waiting for", byte0 + 217 + 35, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("other player", byte0 + 217 + 35, byte1 + 256, 1, 0xffffff); } for (int l4 = 0; l4 < inventoryCount; l4++) { int i5 = 217 + byte0 + (l4 % 5) * 49; int k5 = 31 + byte1 + (l4 / 5) * 34; gameGraphics.spriteClip4(i5, k5, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(getInventoryItems()[l4]) .getSprite(), EntityHandler.getItemDef(getInventoryItems()[l4]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(getInventoryItems()[l4]).isStackable()) gameGraphics.drawString( String.valueOf(inventoryItemsCount[l4]), i5 + 1, k5 + 10, 1, 0xffff00); } for (int j5 = 0; j5 < duelMyItemCount; j5++) { int l5 = 9 + byte0 + (j5 % 4) * 49; int j6 = 31 + byte1 + (j5 / 4) * 34; gameGraphics.spriteClip4(l5, j6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(duelMyItems[j5]).getSprite(), EntityHandler.getItemDef(duelMyItems[j5]).getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(duelMyItems[j5]).isStackable()) gameGraphics.drawString(String.valueOf(duelMyItemsCount[j5]), l5 + 1, j6 + 10, 1, 0xffff00); if (super.mouseX > l5 && super.mouseX < l5 + 48 && super.mouseY > j6 && super.mouseY < j6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(duelMyItems[j5]).getName() + ": @whi@" + EntityHandler.getItemDef(duelMyItems[j5]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } for (int i6 = 0; i6 < duelOpponentItemCount; i6++) { int k6 = 9 + byte0 + (i6 % 4) * 49; int l6 = 124 + byte1 + (i6 / 4) * 34; gameGraphics.spriteClip4(k6, l6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(duelOpponentItems[i6]) .getSprite(), EntityHandler.getItemDef(duelOpponentItems[i6]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(duelOpponentItems[i6]).isStackable()) gameGraphics.drawString( String.valueOf(duelOpponentItemsCount[i6]), k6 + 1, l6 + 10, 1, 0xffff00); if (super.mouseX > k6 && super.mouseX < k6 + 48 && super.mouseY > l6 && super.mouseY < l6 + 32) gameGraphics .drawString( EntityHandler.getItemDef(duelOpponentItems[i6]) .getName() + ": @whi@" + EntityHandler.getItemDef( duelOpponentItems[i6]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } } private final void drawServerMessageBox() { int c = '\u0190'; int c1 = 'd'; if (serverMessageBoxTop) { c1 = '\u01C2'; c1 = '\u012C'; } gameGraphics.drawBox(256 - c / 2 + xAddition, 167 - c1 / 2 + yAddition, c, c1, 0); gameGraphics.drawBoxEdge(256 - c / 2 + xAddition, 167 - c1 / 2 + yAddition, c, c1, 0xffffff); gameGraphics.drawBoxTextColour(serverMessage, 256 + xAddition, (167 - c1 / 2) + 20 + yAddition, 1, 0xffffff, c - 40); int i = 157 + c1 / 2 + yAddition; int j = 0xffffff; if (super.mouseY > i - 12 && super.mouseY <= i && super.mouseX > 106 + xAddition && super.mouseX < 406 + xAddition) j = 0xff0000; gameGraphics.drawText("Click here to close window", 256 + xAddition, i, 1, j); if (mouseButtonClick == 1) { if (j == 0xff0000) showServerMessageBox = false; if ((super.mouseX < 256 - c / 2 + xAddition || super.mouseX > 256 + c / 2 + xAddition) && (super.mouseY < 167 - c1 / 2 + yAddition || super.mouseY > 167 + c1 / 2 + yAddition)) showServerMessageBox = false; } mouseButtonClick = 0; } private final void makeLoginMenus() { menuWelcome = new Menu(gameGraphics, 50); int i = 40 + yAddition; menuWelcome.drawText(256 + xAddition, 200 + i, "Click on an option", 5, true); menuWelcome.drawBox(156 + xAddition, 240 + i, 120, 35); menuWelcome.drawBox(356 + xAddition, 240 + i, 120, 35); menuWelcome.drawText(156 + xAddition, 240 + i, "New User", 5, false); menuWelcome.drawText(356 + xAddition, 240 + i, "Existing User", 5, false); loginButtonNewUser = menuWelcome.makeButton(156 + xAddition, 240 + i, 120, 35); loginButtonExistingUser = menuWelcome.makeButton(356 + xAddition, 240 + i, 120, 35); menuNewUser = new Menu(gameGraphics, 50); i = 230 + yAddition; if (referId == 0) { menuNewUser.drawText(256 + xAddition, i + 8, "To create an account please go back to the", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "www.3hit.net", 4, true); } else if (referId == 1) { menuNewUser.drawText(256 + xAddition, i + 8, "then click account", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); } else { menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); } i += 30; menuNewUser.drawBox(256 + xAddition, i + 17, 150, 34); menuNewUser.drawText(256 + xAddition, i + 17, "Ok", 5, false); newUserOkButton = menuNewUser.makeButton(256 + xAddition, i + 17, 150, 34); menuLogin = new Menu(gameGraphics, 50); i = 230 + yAddition; loginStatusText = menuLogin.drawText(256 + xAddition, i - 10, "Please enter your username and password", 4, true); i += 28; menuLogin.drawBox(140 + xAddition, i, 200, 40); menuLogin.drawText(140 + xAddition, i - 10, "Username:", 4, false); loginUsernameTextBox = menuLogin.makeTextBox(140 + xAddition, i + 10, 200, 40, 4, 12, false, false); i += 47; menuLogin.drawBox(190 + xAddition, i, 200, 40); menuLogin.drawText(190 + xAddition, i - 10, "Password:", 4, false); loginPasswordTextBox = menuLogin.makeTextBox(190 + xAddition, i + 10, 200, 40, 4, 20, true, false); i -= 55; menuLogin.drawBox(410 + xAddition, i, 120, 25); menuLogin.drawText(410 + xAddition, i, "Play Now", 4, false); loginOkButton = menuLogin.makeButton(410 + xAddition, i, 120, 25); i += 30; menuLogin.drawBox(410 + xAddition, i, 120, 25); menuLogin.drawText(410 + xAddition, i, "Cancel", 4, false); loginCancelButton = menuLogin.makeButton(410 + xAddition, i, 120, 25); i += 30; menuLogin.setFocus(loginUsernameTextBox); } private final void drawGameWindowsMenus() { if (logoutTimeout != 0) drawLoggingOutBox(); else if (showWelcomeBox) drawWelcomeBox(); else if (showServerMessageBox) drawServerMessageBox(); else if (wildernessType == 1) // 0 = not wild, 1 = close to wild, 2 = // wild drawWildernessWarningBox(); else if (showBank && lastWalkTimeout == 0) drawBankBox(); else if (showShop && lastWalkTimeout == 0) drawShopBox(); else if (showTradeConfirmWindow) drawTradeConfirmWindow(); else if (showTradeWindow) drawTradeWindow(); else if (showDuelConfirmWindow) drawDuelConfirmWindow(); else if (showDuelWindow) drawDuelWindow(); else if (showAbuseWindow == 1) drawAbuseWindow1(); else if (showAbuseWindow == 2) drawAbuseWindow2(); else if (inputBoxType != 0) { drawInputBox(); } else { if (showQuestionMenu) drawQuestionMenu(); if ((ourPlayer.currentSprite == 8 || ourPlayer.currentSprite == 9) || combatWindow) drawCombatStyleWindow(); checkMouseOverMenus(); boolean noMenusShown = !showQuestionMenu && !showRightClickMenu; if (noMenusShown) menuLength = 0; if (mouseOverMenu == 0 && noMenusShown) drawInventoryRightClickMenu(); if (mouseOverMenu == 1) drawInventoryMenu(noMenusShown); if (mouseOverMenu == 2) drawMapMenu(noMenusShown); if (mouseOverMenu == 3) drawPlayerInfoMenu(noMenusShown); if (mouseOverMenu == 4) drawMagicWindow(noMenusShown); if (mouseOverMenu == 5) drawFriendsWindow(noMenusShown); if (mouseOverMenu == 6) drawOptionsMenu(noMenusShown); if (mouseOverMenu == 7) drawOurOptionsMenu(noMenusShown); if (!showRightClickMenu && !showQuestionMenu) checkMouseStatus(); if (showRightClickMenu && !showQuestionMenu) drawRightClickMenu(); } mouseButtonClick = 0; } public final void method112(int i, int j, int k, int l, boolean flag) { sendWalkCommand(i, j, k, l, k, l, false, flag); } private final void drawInputBox() { if (mouseButtonClick != 0) { mouseButtonClick = 0; if (inputBoxType == 1 && (super.mouseX < 106 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 406 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (inputBoxType == 2 && (super.mouseX < 6 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 506 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (inputBoxType == 3 && (super.mouseX < 106 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 406 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (super.mouseX > 236 + xAddition && super.mouseX < 276 + xAddition && super.mouseY > 193 + yAddition && super.mouseY < 213 + yAddition) { inputBoxType = 0; return; } } int i = 145 + yAddition; if (inputBoxType == 1) { gameGraphics.drawBox(106 + xAddition, i, 300, 70, 0); gameGraphics.drawBoxEdge(106 + xAddition, i, 300, 70, 0xffffff); i += 20; gameGraphics.drawText("Enter name to add to friends list", 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredText.length() > 0) { String s = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; inputBoxType = 0; if (s.length() > 0 && DataOperations.stringLength12ToLong(s) != ourPlayer.nameLong) addToFriendsList(s); } } if (inputBoxType == 2) { gameGraphics.drawBox(6 + xAddition, i, 500, 70, 0); gameGraphics.drawBoxEdge(6 + xAddition, i, 500, 70, 0xffffff); i += 20; gameGraphics .drawText( "Enter message to send to " + DataOperations .longToString(privateMessageTarget), 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputMessage + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredMessage.length() > 0) { String s1 = super.enteredMessage; super.inputMessage = ""; super.enteredMessage = ""; inputBoxType = 0; byte[] message = DataConversions.stringToByteArray(s1); sendPrivateMessage(privateMessageTarget, message, message.length); s1 = DataConversions.byteToString(message, 0, message.length); handleServerMessage("@pri@You tell " + DataOperations.longToString(privateMessageTarget) + ": " + s1); } } if (inputBoxType == 3) { gameGraphics.drawBox(106 + xAddition, i, 300, 70, 0); gameGraphics.drawBoxEdge(106 + xAddition, i, 300, 70, 0xffffff); i += 20; gameGraphics.drawText("Enter name to add to ignore list", 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredText.length() > 0) { String s2 = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; inputBoxType = 0; if (s2.length() > 0 && DataOperations.stringLength12ToLong(s2) != ourPlayer.nameLong) addToIgnoreList(s2); } } int j = 0xffffff; if (super.mouseX > 236 + xAddition && super.mouseX < 276 + xAddition && super.mouseY > 193 + yAddition && super.mouseY < 213 + yAddition) j = 0xffff00; gameGraphics.drawText("Cancel", 256 + xAddition, 208 + yAddition, 1, j); } private final boolean hasRequiredRunes(int i, int j) { if (i == 31 && (method117(197) || method117(615) || method117(682))) { return true; } if (i == 32 && (method117(102) || method117(616) || method117(683))) { return true; } if (i == 33 && (method117(101) || method117(617) || method117(684))) { return true; } if (i == 34 && (method117(103) || method117(618) || method117(685))) { return true; } return inventoryCount(i) >= j; } private final void resetPrivateMessageStrings() { super.inputMessage = ""; super.enteredMessage = ""; } private final boolean method117(int i) { for (int j = 0; j < inventoryCount; j++) if (getInventoryItems()[j] == i && wearing[j] == 1) return true; return false; } private final void setPixelsAndAroundColour(int x, int y, int colour) { gameGraphics.setPixelColour(x, y, colour); gameGraphics.setPixelColour(x - 1, y, colour); gameGraphics.setPixelColour(x + 1, y, colour); gameGraphics.setPixelColour(x, y - 1, colour); gameGraphics.setPixelColour(x, y + 1, colour); } private final void method119() { for (int i = 0; i < mobMessageCount; i++) { int j = gameGraphics.messageFontHeight(1); int l = mobMessagesX[i]; int k1 = mobMessagesY[i]; int j2 = mobMessagesWidth[i]; int i3 = mobMessagesHeight[i]; boolean flag = true; while (flag) { flag = false; for (int i4 = 0; i4 < i; i4++) if (k1 + i3 > mobMessagesY[i4] - j && k1 - j < mobMessagesY[i4] + mobMessagesHeight[i4] && l - j2 < mobMessagesX[i4] + mobMessagesWidth[i4] && l + j2 > mobMessagesX[i4] - mobMessagesWidth[i4] && mobMessagesY[i4] - j - i3 < k1) { k1 = mobMessagesY[i4] - j - i3; flag = true; } } mobMessagesY[i] = k1; gameGraphics.drawBoxTextColour(mobMessages[i], l, k1, 1, 0xffff00, 300); } for (int k = 0; k < anInt699; k++) { int i1 = anIntArray858[k]; int l1 = anIntArray859[k]; int k2 = anIntArray705[k]; int j3 = anIntArray706[k]; int l3 = (39 * k2) / 100; int j4 = (27 * k2) / 100; int k4 = l1 - j4; gameGraphics.spriteClip2(i1 - l3 / 2, k4, l3, j4, SPRITE_MEDIA_START + 9, 85); int l4 = (36 * k2) / 100; int i5 = (24 * k2) / 100; gameGraphics.spriteClip4(i1 - l4 / 2, (k4 + j4 / 2) - i5 / 2, l4, i5, EntityHandler.getItemDef(j3).getSprite() + SPRITE_ITEM_START, EntityHandler.getItemDef(j3) .getPictureMask(), 0, 0, false); } for (int j1 = 0; j1 < anInt718; j1++) { int i2 = anIntArray786[j1]; int l2 = anIntArray787[j1]; int k3 = anIntArray788[j1]; gameGraphics.drawBoxAlpha(i2 - 15, l2 - 3, k3, 5, 65280, 192); gameGraphics.drawBoxAlpha((i2 - 15) + k3, l2 - 3, 30 - k3, 5, 0xff0000, 192); } } private final void drawMapMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; char c = '\234'; char c2 = '\230'; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 2); i += 40; gameGraphics.drawBox(i, 36, c, c2, 0); gameGraphics.setDimensions(i, 36, i + c, 36 + c2); int k = 192 + anInt986; int i1 = cameraRotation + anInt985 & 0xff; int k1 = ((ourPlayer.currentX - 6040) * 3 * k) / 2048; int i3 = ((ourPlayer.currentY - 6040) * 3 * k) / 2048; int k4 = Camera.anIntArray384[1024 - i1 * 4 & 0x3ff]; int i5 = Camera.anIntArray384[(1024 - i1 * 4 & 0x3ff) + 1024]; int k5 = i3 * k4 + k1 * i5 >> 18; i3 = i3 * i5 - k1 * k4 >> 18; k1 = k5; gameGraphics.method242((i + c / 2) - k1, 36 + c2 / 2 + i3, SPRITE_MEDIA_START - 1, i1 + 64 & 0xff, k); for (int i7 = 0; i7 < objectCount; i7++) { int l1 = (((objectX[i7] * magicLoc + 64) - ourPlayer.currentX) * 3 * k) / 2048; int j3 = (((objectY[i7] * magicLoc + 64) - ourPlayer.currentY) * 3 * k) / 2048; int l5 = j3 * k4 + l1 * i5 >> 18; j3 = j3 * i5 - l1 * k4 >> 18; l1 = l5; setPixelsAndAroundColour(i + c / 2 + l1, (36 + c2 / 2) - j3, 65535); } for (int j7 = 0; j7 < groundItemCount; j7++) { int i2 = (((groundItemX[j7] * magicLoc + 64) - ourPlayer.currentX) * 3 * k) / 2048; int k3 = (((groundItemY[j7] * magicLoc + 64) - ourPlayer.currentY) * 3 * k) / 2048; int i6 = k3 * k4 + i2 * i5 >> 18; k3 = k3 * i5 - i2 * k4 >> 18; i2 = i6; setPixelsAndAroundColour(i + c / 2 + i2, (36 + c2 / 2) - k3, 0xff0000); } for (int k7 = 0; k7 < npcCount; k7++) { Mob mob = npcArray[k7]; int j2 = ((mob.currentX - ourPlayer.currentX) * 3 * k) / 2048; int l3 = ((mob.currentY - ourPlayer.currentY) * 3 * k) / 2048; int j6 = l3 * k4 + j2 * i5 >> 18; l3 = l3 * i5 - j2 * k4 >> 18; j2 = j6; setPixelsAndAroundColour(i + c / 2 + j2, (36 + c2 / 2) - l3, 0xffff00); } for (int l7 = 0; l7 < playerCount; l7++) { Mob mob_1 = playerArray[l7]; int k2 = ((mob_1.currentX - ourPlayer.currentX) * 3 * k) / 2048; int i4 = ((mob_1.currentY - ourPlayer.currentY) * 3 * k) / 2048; int k6 = i4 * k4 + k2 * i5 >> 18; i4 = i4 * i5 - k2 * k4 >> 18; k2 = k6; int j8 = 0xffffff; for (int k8 = 0; k8 < super.friendsCount; k8++) { if (mob_1.nameLong != super.friendsListLongs[k8] || super.friendsListOnlineStatus[k8] != 99) continue; j8 = 65280; break; } setPixelsAndAroundColour(i + c / 2 + k2, (36 + c2 / 2) - i4, j8); } gameGraphics.method212(i + c / 2, 36 + c2 / 2, 2, 0xffffff, 255); gameGraphics.method242(i + 19, 55, SPRITE_MEDIA_START + 24, cameraRotation + 128 & 0xff, 128); gameGraphics.setDimensions(0, 0, windowWidth, windowHeight + 12); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); int i8 = super.mouseY - 36; if (i >= 40 && i8 >= 0 && i < 196 && i8 < 152) { char c1 = '\234'; char c3 = '\230'; int l = 192 + anInt986; int j1 = cameraRotation + anInt985 & 0xff; int j = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; j += 40; int l2 = ((super.mouseX - (j + c1 / 2)) * 16384) / (3 * l); int j4 = ((super.mouseY - (36 + c3 / 2)) * 16384) / (3 * l); int l4 = Camera.anIntArray384[1024 - j1 * 4 & 0x3ff]; int j5 = Camera.anIntArray384[(1024 - j1 * 4 & 0x3ff) + 1024]; int l6 = j4 * l4 + l2 * j5 >> 15; j4 = j4 * j5 - l2 * l4 >> 15; l2 = l6; l2 += ourPlayer.currentX; j4 = ourPlayer.currentY - j4; if (mouseButtonClick == 1) method112(getSectionX(), getSectionY(), l2 / 128, j4 / 128, false); mouseButtonClick = 0; } } public mudclient() { for (int i = 0; i < questStage.length; i++) questStage[i] = (byte) 0; combatWindow = false; threadSleepTime = 10; try { localhost = InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { e.printStackTrace(); localhost = "unknown"; } if (config.getProperty("width") == null) { Config.storeConfig("width", "502"); } if (config.getProperty("height") == null) { Config.storeConfig("height", "382"); } if (config.getProperty("refreshRate") == null) { Config.storeConfig("refreshRate", "" + Resolutions.oldDisplayMode.getRefreshRate()); } if (config.getProperty("bitDepth") == null) { Config.storeConfig("bitDepth", "" + Resolutions.oldDisplayMode.getBitDepth()); } windowWidth = Integer.valueOf(config.getProperty("width")); windowHeight = Integer.valueOf(config.getProperty("height")) - 40; screenDepth = Integer.valueOf(config.getProperty("bitDepth")); screenRefreshRate = Integer.valueOf(config.getProperty("refreshRate")); if (windowWidth < defaultWidth || windowHeight < defaultHeight) { windowWidth = defaultWidth; Config.storeConfig("width", "502"); windowHeight = defaultHeight; Config.storeConfig("height", "382"); } if (windowWidth > 532) { xAddition = (windowWidth - defaultWidth) / 2; yAddition = (windowHeight - defaultHeight) / 2; } else { xAddition = 0; yAddition = 0; } startTime = System.currentTimeMillis(); duelMyItems = new int[8]; duelMyItemsCount = new int[8]; configAutoCameraAngle = true; questionMenuAnswer = new String[10]; lastNpcArray = new Mob[500]; currentUser = ""; currentPass = ""; menuText1 = new String[250]; duelOpponentAccepted = false; duelMyAccepted = false; tradeConfirmItems = new int[14]; tradeConfirmItemsCount = new int[14]; tradeConfirmOtherItems = new int[14]; tradeConfirmOtherItemsCount = new int[14]; serverMessage = ""; duelOpponentName = ""; setInventoryItems(new int[35]); inventoryItemsCount = new int[35]; wearing = new int[35]; mobMessages = new String[50]; showBank = false; doorModel = new Model[500]; mobMessagesX = new int[50]; mobMessagesY = new int[50]; mobMessagesWidth = new int[50]; mobMessagesHeight = new int[50]; npcArray = new Mob[500]; equipmentStatus = new int[6]; prayerOn = new boolean[50]; tradeOtherAccepted = false; tradeWeAccepted = false; mobArray = new Mob[8000]; anIntArray705 = new int[50]; anIntArray706 = new int[50]; lastWildYSubtract = -1; memoryError = false; bankItemsMax = 48; showQuestionMenu = false; magicLoc = 128; cameraAutoAngle = 1; anInt727 = 2; showServerMessageBox = false; hasReceivedWelcomeBoxDetails = false; playerStatCurrent = new int[18]; wildYSubtract = -1; anInt742 = -1; anInt743 = -1; anInt744 = -1; sectionXArray = new int[8000]; sectionYArray = new int[8000]; selectedItem = -1; selectedItemName = ""; duelOpponentItems = new int[8]; duelOpponentItemsCount = new int[8]; anIntArray757 = new int[50]; menuID = new int[250]; showCharacterLookScreen = false; showDrawPointsScreen = false; lastPlayerArray = new Mob[500]; appletMode = true; gameDataModels = new Model[1000]; configMouseButtons = false; duelNoRetreating = false; duelNoMagic = false; duelNoPrayer = false; duelNoWeapons = false; anIntArray782 = new int[50]; duelConfirmOpponentItems = new int[8]; duelConfirmOpponentItemsCount = new int[8]; anIntArray786 = new int[50]; anIntArray787 = new int[50]; anIntArray788 = new int[50]; objectModelArray = new Model[1500]; cameraRotation = 128; showWelcomeBox = false; characterBodyGender = 1; character2Colour = 2; characterHairColour = 2; characterTopColour = 8; characterBottomColour = 14; characterHeadGender = 1; selectedBankItem = -1; selectedBankItemType = -2; menuText2 = new String[250]; aBooleanArray827 = new boolean[1500]; playerStatBase = new int[18]; menuActionType = new int[250]; menuActionVariable = new int[250]; menuActionVariable2 = new int[250]; shopItems = new int[256]; shopItemCount = new int[256]; shopItemsSellPrice = new int[256]; shopItemsBuyPrice = new int[256]; anIntArray858 = new int[50]; anIntArray859 = new int[50]; newBankItems = new int[256]; newBankItemsCount = new int[256]; duelConfirmMyItems = new int[8]; duelConfirmMyItemsCount = new int[8]; mobArrayIndexes = new int[500]; messagesTimeout = new int[5]; objectX = new int[1500]; objectY = new int[1500]; objectType = new int[1500]; objectID = new int[1500]; menuActionX = new int[250]; menuActionY = new int[250]; ourPlayer = new Mob(); serverIndex = -1; anInt882 = 30; showTradeConfirmWindow = false; tradeConfirmAccepted = false; playerArray = new Mob[500]; serverMessageBoxTop = false; cameraHeight = 750; bankItems = new int[256]; bankItemsCount = new int[256]; notInWilderness = false; selectedSpell = -1; anInt911 = 2; tradeOtherItems = new int[14]; tradeOtherItemsCount = new int[14]; menuIndexes = new int[250]; zoomCamera = false; playerStatExperience = new int[18]; cameraAutoAngleDebug = false; npcRecordArray = new Mob[8000]; showDuelWindow = false; anIntArray923 = new int[50]; lastLoadedNull = false; experienceArray = new int[99]; showShop = false; mouseClickXArray = new int[8192]; mouseClickYArray = new int[8192]; showDuelConfirmWindow = false; duelWeAccept = false; doorX = new int[500]; doorY = new int[500]; configSoundEffects = false; showRightClickMenu = false; attackingInt40 = 40; anIntArray944 = new int[50]; doorDirection = new int[500]; doorType = new int[500]; groundItemX = new int[8000]; groundItemY = new int[8000]; groundItemType = new int[8000]; groundItemObjectVar = new int[8000]; selectedShopItemIndex = -1; selectedShopItemType = -2; messagesArray = new String[5]; showTradeWindow = false; aBooleanArray970 = new boolean[500]; tradeMyItems = new int[14]; tradeMyItemsCount = new int[14]; cameraSizeInt = 9; tradeOtherPlayerName = ""; mc = this; } private boolean combatWindow; private int lastLoggedInDays; private int subscriptionLeftDays; private int duelMyItemCount; private int duelMyItems[]; private int duelMyItemsCount[]; private boolean configAutoCameraAngle; private String questionMenuAnswer[]; private int anInt658; private Mob lastNpcArray[]; private int loginButtonNewUser; private int loginButtonExistingUser; private String currentUser; private String currentPass; private int lastWalkTimeout; private String menuText1[]; private boolean duelOpponentAccepted; private boolean duelMyAccepted; private int tradeConfirmItemCount; private int tradeConfirmItems[]; private int tradeConfirmItemsCount[]; private int tradeConfirmOtherItemCount; private int tradeConfirmOtherItems[]; private int tradeConfirmOtherItemsCount[]; static String serverMessage; private String duelOpponentName; private int mouseOverBankPageText; public int playerCount; private int lastPlayerCount; private int fightCount; private int inventoryCount; private int inventoryItems[]; private int inventoryItemsCount[]; private int wearing[]; private int mobMessageCount; String mobMessages[]; private boolean showBank; private Model doorModel[]; private int mobMessagesX[]; private int mobMessagesY[]; private int mobMessagesWidth[]; private int mobMessagesHeight[]; public Mob npcArray[]; private int equipmentStatus[]; private final int characterTopBottomColours[] = { 0xff0000, 0xff8000, 0xffe000, 0xa0e000, 57344, 32768, 41088, 45311, 33023, 12528, 0xe000e0, 0x303030, 0x604000, 0x805000, 0xffffff }; private int loginScreenNumber; private int anInt699; private boolean prayerOn[]; private boolean tradeOtherAccepted; private boolean tradeWeAccepted; private Mob mobArray[]; private int npcCombatModelArray1[] = { 0, 1, 2, 1, 0, 0, 0, 0 }; private int anIntArray705[]; private int anIntArray706[]; public int npcCount; private int lastNpcCount; private int wildX; private int wildY; private int wildYMultiplier; private int lastWildYSubtract; private boolean memoryError; private int bankItemsMax; private int mouseOverMenu; private int walkModel[] = { 0, 1, 2, 1 }; private boolean showQuestionMenu; private int anInt718; public int magicLoc; public int loggedIn; private int cameraAutoAngle; private int cameraRotationBaseAddition; private Menu spellMenu; int spellMenuHandle; int menuMagicPrayersSelected; private int screenRotationX; private int anInt727; private int showAbuseWindow; private int duelCantRetreat; private int duelUseMagic; private int duelUsePrayer; private int duelUseWeapons; static boolean showServerMessageBox; private boolean hasReceivedWelcomeBoxDetails; private String lastLoggedInAddress; private int loginTimer; private int playerStatCurrent[]; private int areaX; private int areaY; private int wildYSubtract; private int anInt742; private int anInt743; private int anInt744; public int sectionXArray[]; public int sectionYArray[]; private int selectedItem; String selectedItemName; private int menuX; private int menuY; private int menuWidth; private int menuHeight; private int menuLength; private int duelOpponentItemCount; private int duelOpponentItems[]; private int duelOpponentItemsCount[]; private int anIntArray757[]; private int menuID[]; private boolean showCharacterLookScreen; private boolean showDrawPointsScreen; private int newBankItemCount; private int npcCombatModelArray2[] = { 0, 0, 0, 0, 0, 1, 2, 1 }; private Mob lastPlayerArray[]; private int inputBoxType; private boolean appletMode; private int combatStyle; private Model gameDataModels[]; private boolean configMouseButtons; private boolean duelNoRetreating; private boolean duelNoMagic; private boolean duelNoPrayer; private boolean duelNoWeapons; private int anIntArray782[]; private int duelConfirmOpponentItemCount; private int duelConfirmOpponentItems[]; private int duelConfirmOpponentItemsCount[]; private int anIntArray786[]; private int anIntArray787[]; private int anIntArray788[]; private int anInt789; private int anInt790; private int anInt791; private int anInt792; private Menu menuLogin; private final int characterHairColours[] = { 0xffc030, 0xffa040, 0x805030, 0x604020, 0x303030, 0xff6020, 0xff4000, 0xffffff, 65280, 65535 }; private Model objectModelArray[]; private Menu menuWelcome; private int systemUpdate; private int cameraRotation; private int logoutTimeout; private Menu gameMenu; // Wilderness int messagesHandleType2; int chatHandle; int messagesHandleType5; int messagesHandleType6; int messagesTab; private boolean showWelcomeBox; private int characterHeadType; private int characterBodyGender; private int character2Colour; private int characterHairColour; private int characterTopColour; private int characterBottomColour; private int characterSkinColour; private int characterHeadGender; // shopItems private int loginStatusText; private int loginUsernameTextBox; private int loginPasswordTextBox; private int loginOkButton; private int loginCancelButton; private int selectedBankItem; private int selectedBankItemType; private String menuText2[]; int anInt826; private boolean aBooleanArray827[]; private int playerStatBase[]; private int abuseSelectedType; public int actionPictureType; int actionPictureX; int actionPictureY; private int menuActionType[]; private int menuActionVariable[]; private int menuActionVariable2[]; private int shopItems[]; private int shopItemCount[]; private int shopItemsBuyPrice[]; private int shopItemsSellPrice[]; private byte[] x = new byte[] { 111, 114, 103, 46, 114, 115, 99, 97, 110, 103, 101, 108, 46, 99, 108, 105, 101, 110, 116, 46, 109, 117, 100, 99, 108, 105, 101, 110, 116, 46, 99, 104, 101, 99, 107, 77, 111, 117, 115, 101, 83, 116, 97, 116, 117, 115, 40, 41 }; private byte[] y = new byte[] { 111, 114, 103, 46, 114, 115, 99, 97, 110, 103, 101, 108, 46, 99, 108, 105, 101, 110, 116, 46, 109, 117, 100, 99, 108, 105, 101, 110, 116, 46, 100, 114, 97, 119, 82, 105, 103, 104, 116, 67, 108, 105, 99, 107, 77, 101, 110, 117, 40, 41 }; private int npcAnimationArray[][] = { { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3, 4 }, { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3, 4 }, { 11, 3, 2, 9, 7, 1, 6, 10, 0, 5, 8, 4 }, { 3, 4, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 3, 4, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 4, 3, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 11, 4, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3 }, { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 4, 3 } }; private int bankItemCount; private int strDownButton; private int atkDownButton; private int defDownButton; private int magDownButton; private int rangeDownButton; private int strUpButton; private int atkUpButton; private int defUpButton; private int magUpButton; private int rangeUpButton; private int dPSAcceptButton; public static final int[] pkexperienceArray = { 83, 174, 276, 388, 512, 650, 801, 969, 1154, 1358, 1584, 1833, 2107, 2411, 2746, 3115, 3523, 3973, 4470, 5018, 5624, 6291, 7028, 7842, 8740, 9730, 10824, 12031, 13363, 14833, 16456, 18247, 20224, 22406, 24815, 27473, 30408, 33648, 37224, 41171, 45529, 50339, 55649, 61512, 67983, 75127, 83014, 91721, 101333, 111945, 123660, 136594, 150872, 166636, 184040, 203254, 224466, 247886, 273742, 302288, 333804, 368599, 407015, 449428, 496254, 547953, 605032, 668051, 737627, 814445, 899257, 992895, 1096278, 1210421, 1336443, 1475581, 1629200, 1798808, 1986068, 2192818, 2421087, 2673114, 2951373, 3258594, 3597792, 3972294, 4385776, 4842295, 5346332, 5902831, 6517253, 7195629, 7944614, 8771558, 9684577, 10692629, 11805606, 13034431, 14391160 }; private int pkmagic, pkrange, pkatk, pkdef, pkstr = 1; private long pkpoints = 0; private int pkmagictext, pkcombattext, pkpointstext, pkrangetext, pkatktext, pkdeftext, pkstrtext = 0; private boolean pkreset = true; private int characterDesignHeadButton1; private int characterDesignHeadButton2; private int characterDesignHairColourButton1; private int characterDesignHairColourButton2; private int characterDesignGenderButton1; private int characterDesignGenderButton2; private int characterDesignTopColourButton1; private int characterDesignTopColourButton2; private int characterDesignSkinColourButton1; private int characterDesignSkinColourButton2; private int characterDesignBottomColourButton1; private int characterDesignBottomColourButton2; private int characterDesignAcceptButton; private int anIntArray858[]; private int anIntArray859[]; private int newBankItems[]; private int newBankItemsCount[]; private int duelConfirmMyItemCount; private int duelConfirmMyItems[]; private int duelConfirmMyItemsCount[]; private int mobArrayIndexes[]; private Menu menuNewUser; private int messagesTimeout[]; private int lastAutoCameraRotatePlayerX; private int lastAutoCameraRotatePlayerY; private int questionMenuCount; public int objectX[]; public int objectY[]; public int objectType[]; private int objectID[]; private int menuActionX[]; private int menuActionY[]; public Mob ourPlayer; private int sectionX; private int sectionY; int serverIndex; private int anInt882; private int mouseDownTime; private int itemIncrement; public int groundItemCount; private int modelFireLightningSpellNumber; private int modelTorchNumber; private int modelClawSpellNumber; private boolean showTradeConfirmWindow; private boolean tradeConfirmAccepted; private int anInt892; public EngineHandle engineHandle; public Mob playerArray[];// Stats private boolean serverMessageBoxTop; private final String equipmentStatusName[] = { "Armour", "WeaponAim", "WeaponPower", "Magic", "Prayer", "Range" }; public int flagged = 0; private int referId; private int anInt900; private int newUserOkButton; private int mouseButtonClick; private int cameraHeight; private int bankItems[]; private int bankItemsCount[]; private boolean notInWilderness; private int selectedSpell; private int screenRotationY; private int anInt911; private int tradeOtherItemCount; private int tradeOtherItems[]; private int tradeOtherItemsCount[]; private int menuIndexes[]; private boolean zoomCamera; private AudioReader audioReader; private int playerStatExperience[]; private boolean cameraAutoAngleDebug; private Mob npcRecordArray[]; private final String skillArray[] = { "Attack", "Defense", "Strength", "Hits", "Ranged", "Prayer", "Magic", "Cooking", "Woodcut", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblaw", "Agility", "Thieving" }; private boolean showDuelWindow; private int anIntArray923[]; public GameImageMiddleMan gameGraphics; private final String skillArrayLong[] = { "Attack", "Defense", "Strength", "Hitpoints", "Ranged", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblaw", "Agility", "Thieving" }; private boolean lastLoadedNull; private int experienceArray[]; private Camera gameCamera; private boolean showShop; private int mouseClickArrayOffset; int mouseClickXArray[]; int mouseClickYArray[]; private boolean showDuelConfirmWindow; private boolean duelWeAccept; private Graphics aGraphics936; private int doorX[]; private int doorY[]; private int wildernessType; private boolean configSoundEffects; private boolean showRightClickMenu; private int screenRotationTimer; private int attackingInt40; private int anIntArray944[]; private Menu characterDesignMenu; private Menu drawPointsScreen; private int shopItemSellPriceModifier; private int shopItemBuyPriceModifier; private int modelUpdatingTimer; private int doorCount; private int doorDirection[]; private int doorType[]; private int anInt952; private int anInt953; private int anInt954; private int anInt955; public int groundItemX[]; public int groundItemY[]; public int groundItemType[]; private int groundItemObjectVar[]; private int selectedShopItemIndex; private int selectedShopItemType; private String messagesArray[]; private long tradeConfirmOtherNameLong; private boolean showTradeWindow; private int playerAliveTimeout; private final int characterSkinColours[] = { 0xecded0, 0xccb366, 0xb38c40, 0x997326, 0x906020 }; private byte sounds[]; // 3150 private boolean aBooleanArray970[]; public int objectCount; private int tradeMyItemCount; private int tradeMyItems[]; private int tradeMyItemsCount[]; public int windowWidth = 512; public int windowHeight = 334; public int screenDepth; public int screenRefreshRate; int defaultWidth = 512; int defaultHeight = 334; public int xAddition; public int yAddition; private int cameraSizeInt; private Menu friendsMenu; int friendsMenuHandle; int anInt981; long privateMessageTarget; private long duelOpponentNameLong; private String tradeOtherPlayerName; private int anInt985; private int anInt986; private boolean aBoolean767; // humuliat public final static void drawDownloadProgress(String s, int progress, boolean download) { try { int j = (appletWidth - 281) / 2; int k = (appletHeight - 148) / 2; j += 2 + 4; k += 122; // BAR_COLOUR int l = (281 * progress) / 100; getLoadingGraphics().setColor(BAR_COLOUR); getLoadingGraphics().fillRect(j, k, l, 20); getLoadingGraphics().setColor(Color.black); getLoadingGraphics().fillRect(j + l, k, 281 - l, 20); getLoadingGraphics().setColor(Color.WHITE); getLoadingGraphics().drawString( (download ? "Downloading: " : "") + s + " " + progress + "%", j + (download ? 54 : 54), k + 14); } catch (Exception _ex) { } } public static File getFile(String filename) { File file = new File(Config.CONF_DIR + File.separator + filename); if (file.isFile() && file.exists()) { return file; } else return null; } public void setSectionX(int sectionX) { this.sectionX = sectionX; } public int getSectionX() { return sectionX; } public void setSectionY(int sectionY) { this.sectionY = sectionY; } public int getSectionY() { return sectionY; } public void setAreaY(int areaY) { this.areaY = areaY; } public int getAreaY() { return areaY; } public void setAreaX(int areaX) { this.areaX = areaX; } public int getAreaX() { return areaX; } public static void drawPopup(String message) { serverMessage = message; showServerMessageBox = true; } public void sendSmithingItem(int spriteID) { streamClass.createPacket(201); streamClass.add4ByteInt(spriteID); streamClass.formatPacket(); } public void sendSmithingClose() { streamClass.createPacket(202); streamClass.formatPacket(); } public void setInventoryItems(int inventoryItems[]) { this.inventoryItems = inventoryItems; } public int[] getInventoryItems() { return inventoryItems; } }
private final void drawGame() throws Exception { cur_fps++; if (System.currentTimeMillis() - lastFps < 0) { lastFps = System.currentTimeMillis(); } if (System.currentTimeMillis() - lastFps >= 1000) { fps = cur_fps; cur_fps = 0; lastFps = System.currentTimeMillis(); } // sleepTime = (int) ((long) threadSleepModifier - (l1 - // currentTimeArray[i]) / 10L); /* * long now = System.currentTimeMillis(); if (now - lastFrame > (1000 / * Config.MOVIE_FPS) && recording) { try { lastFrame = now; * frames.add(getImage()); } catch (Exception e) { e.printStackTrace(); * } } */ if (playerAliveTimeout != 0) { gameGraphics.fadePixels(); gameGraphics.drawText("Oh dear! You are dead...", windowWidth / 2, windowHeight / 2, 7, 0xff0000); drawChatMessageTabs(); drawOurSpritesOnScreen(); gameGraphics.drawImage(aGraphics936, 0, 0); return; } if (sleeping) { boolean drawEquation = true; // gameGraphics.fadePixels(); // if(Math.random() < 0.14999999999999999D) // gameGraphics.drawText("ZZZ", (int)(Math.random() * 80D), // (int)(Math.random() * (double)windowHeight), 5, // (int)(Math.random() * 16777215D)); // if(Math.random() < 0.14999999999999999D) // gameGraphics.drawText("ZZZ", windowWidth - (int)(Math.random() * // 80D), (int)(Math.random() * (double)windowHeight), 5, // (int)(Math.random() * 16777215D)); // gameGraphics.drawBox(windowWidth / 2 - 100, 160, 200, 40, 0); // gameGraphics.drawText("You are sleeping", windowWidth / 2, 50, 7, // 0xffff00); // gameGraphics.drawText("Fatigue: " + (tfatigue * 100) / 750 + "%", // windowWidth / 2, 90, 7, 0xffff00); // gameGraphics.drawText("When you want to wake up just use your", // windowWidth / 2, 140, 5, 0xffffff); // gameGraphics.drawText("keyboard to type the solution in the box below", // windowWidth / 2, 160, 5, 0xffffff); // gameGraphics.drawText(super.inputText + "*", windowWidth / 2, // 180, 5, 65535); // if(sleepMessage != null) { // gameGraphics.drawText(sleepMessage, windowWidth / 2, 260, 5, // 0xff0000); // drawEquation = false; // } // gameGraphics.drawBoxEdge(windowWidth / 2 - 128, 229, 257, 42, // 0xffffff); // drawChatMessageTabs(); // gameGraphics.drawText("If you can't read the equation", // windowWidth / 2, 290, 1, 0xffffff); // gameGraphics.drawText("@yel@click here@whi@ to get a different one", // windowWidth / 2, 305, 1, 0xffffff); // gameGraphics.drawImage(aGraphics936, 0, 0); if (drawEquation && sleepEquation != null) { gameGraphics.drawImage(aGraphics936, 0, 0, fixSleeping(sleepEquation)); // gameGraphics.drawImage(aGraphics936, windowWidth / 2 - 127, // 230, fixSleeping(sleepEquation)); } return; } if (showDrawPointsScreen) { showDPS(); return; } if (showCharacterLookScreen) { method62(); return; }// fog if (!engineHandle.playerIsAlive) { return; } for (int i = 0; i < 64; i++) { gameCamera .removeModel(engineHandle.aModelArrayArray598[lastWildYSubtract][i]); if (lastWildYSubtract == 0) { gameCamera.removeModel(engineHandle.aModelArrayArray580[1][i]); gameCamera.removeModel(engineHandle.aModelArrayArray598[1][i]); gameCamera.removeModel(engineHandle.aModelArrayArray580[2][i]); gameCamera.removeModel(engineHandle.aModelArrayArray598[2][i]); } zoomCamera = true; if (lastWildYSubtract == 0 && (engineHandle.walkableValue[ourPlayer.currentX / 128][ourPlayer.currentY / 128] & 0x80) == 0) { if (showRoof) { gameCamera .addModel(engineHandle.aModelArrayArray598[lastWildYSubtract][i]); if (lastWildYSubtract == 0) { gameCamera .addModel(engineHandle.aModelArrayArray580[1][i]); gameCamera .addModel(engineHandle.aModelArrayArray598[1][i]); gameCamera .addModel(engineHandle.aModelArrayArray580[2][i]); gameCamera .addModel(engineHandle.aModelArrayArray598[2][i]); } } zoomCamera = false; } } if (modelFireLightningSpellNumber != anInt742) { anInt742 = modelFireLightningSpellNumber; for (int j = 0; j < objectCount; j++) { if (objectType[j] == 97) method98(j, "firea" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 274) method98(j, "fireplacea" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1031) method98(j, "lightning" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1036) method98(j, "firespell" + (modelFireLightningSpellNumber + 1)); if (objectType[j] == 1147) method98(j, "spellcharge" + (modelFireLightningSpellNumber + 1)); } } if (modelTorchNumber != anInt743) { anInt743 = modelTorchNumber; for (int k = 0; k < objectCount; k++) { if (objectType[k] == 51) method98(k, "torcha" + (modelTorchNumber + 1)); if (objectType[k] == 143) method98(k, "skulltorcha" + (modelTorchNumber + 1)); } } if (modelClawSpellNumber != anInt744) { anInt744 = modelClawSpellNumber; for (int l = 0; l < objectCount; l++) if (objectType[l] == 1142) method98(l, "clawspell" + (modelClawSpellNumber + 1)); } gameCamera.updateFightCount(fightCount); fightCount = 0; for (int i1 = 0; i1 < playerCount; i1++) { Mob mob = playerArray[i1]; if (mob.colourBottomType != 255) { int k1 = mob.currentX; int i2 = mob.currentY; int k2 = -engineHandle.getAveragedElevation(k1, i2); int l3 = gameCamera.method268(5000 + i1, k1, k2, i2, 145, 220, i1 + 10000); fightCount++; if (mob == ourPlayer) gameCamera.setOurPlayer(l3); if (mob.currentSprite == 8) gameCamera.setCombat(l3, -30); if (mob.currentSprite == 9) gameCamera.setCombat(l3, 30); } } for (int j1 = 0; j1 < playerCount; j1++) { Mob player = playerArray[j1]; if (player.anInt176 > 0) { Mob npc = null; if (player.attackingNpcIndex != -1) npc = npcRecordArray[player.attackingNpcIndex]; else if (player.attackingMobIndex != -1) npc = mobArray[player.attackingMobIndex]; if (npc != null) { int px = player.currentX; int py = player.currentY; int pi = -engineHandle.getAveragedElevation(px, py) - 110; int nx = npc.currentX; int ny = npc.currentY; int ni = -engineHandle.getAveragedElevation(nx, ny) - EntityHandler.getNpcDef(npc.type).getCamera2() / 2; int i10 = (px * player.anInt176 + nx * (attackingInt40 - player.anInt176)) / attackingInt40; int j10 = (pi * player.anInt176 + ni * (attackingInt40 - player.anInt176)) / attackingInt40; int k10 = (py * player.anInt176 + ny * (attackingInt40 - player.anInt176)) / attackingInt40; gameCamera.method268(SPRITE_PROJECTILE_START + player.attackingCameraInt, i10, j10, k10, 32, 32, 0); fightCount++; } } } for (int l1 = 0; l1 < npcCount; l1++) { Mob npc = npcArray[l1]; int mobx = npc.currentX; int moby = npc.currentY; int i7 = -engineHandle.getAveragedElevation(mobx, moby); int i9 = gameCamera.method268(20000 + l1, mobx, i7, moby, EntityHandler.getNpcDef(npc.type).getCamera1(), EntityHandler.getNpcDef(npc.type).getCamera2(), l1 + 30000); fightCount++; if (npc.currentSprite == 8) gameCamera.setCombat(i9, -30); if (npc.currentSprite == 9) gameCamera.setCombat(i9, 30); } if (LOOT_ENABLED) { for (int j2 = 0; j2 < groundItemCount; j2++) { int j3 = groundItemX[j2] * magicLoc + 64; int k4 = groundItemY[j2] * magicLoc + 64; gameCamera.method268(40000 + groundItemType[j2], j3, -engineHandle.getAveragedElevation(j3, k4) - groundItemObjectVar[j2], k4, 96, 64, j2 + 20000); fightCount++; } }// if (systemUpdate != 0) { for (int k3 = 0; k3 < anInt892; k3++) { int l4 = anIntArray944[k3] * magicLoc + 64; int j7 = anIntArray757[k3] * magicLoc + 64; int j9 = anIntArray782[k3]; if (j9 == 0) { gameCamera.method268(50000 + k3, l4, -engineHandle.getAveragedElevation(l4, j7), j7, 128, 256, k3 + 50000); fightCount++; } if (j9 == 1) { gameCamera.method268(50000 + k3, l4, -engineHandle.getAveragedElevation(l4, j7), j7, 128, 64, k3 + 50000); fightCount++; } } gameGraphics.f1Toggle = false; gameGraphics.method211(); gameGraphics.f1Toggle = super.keyF1Toggle; if (lastWildYSubtract == 3) { int i5 = 40 + (int) (Math.random() * 3D); int k7 = 40 + (int) (Math.random() * 7D); gameCamera.method304(i5, k7, -50, -10, -50); } anInt699 = 0; mobMessageCount = 0; anInt718 = 0; if (cameraAutoAngleDebug) { if (configAutoCameraAngle && !zoomCamera) { int lastCameraAutoAngle = cameraAutoAngle; autoRotateCamera(); if (cameraAutoAngle != lastCameraAutoAngle) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } } if (fog) { gameCamera.zoom1 = 3000 + fogVar; gameCamera.zoom2 = 3000 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2800 + fogVar; } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } cameraRotation = cameraAutoAngle * 32; int k5 = lastAutoCameraRotatePlayerX + screenRotationX; int l7 = lastAutoCameraRotatePlayerY + screenRotationY; gameCamera.setCamera(k5, -engineHandle.getAveragedElevation(k5, l7), l7, cameraVertical, cameraRotation * 4, 0, 2000); } else { if (configAutoCameraAngle && !zoomCamera) autoRotateCamera(); if (fog) { if (!super.keyF1Toggle) { gameCamera.zoom1 = 2400 + fogVar; gameCamera.zoom2 = 2400 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2300 + fogVar; } else { gameCamera.zoom1 = 2200; gameCamera.zoom2 = 2200; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2100; } } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } int l5 = lastAutoCameraRotatePlayerX + screenRotationX; int i8 = lastAutoCameraRotatePlayerY + screenRotationY; gameCamera.setCamera(l5, -engineHandle.getAveragedElevation(l5, i8), i8, cameraVertical, cameraRotation * 4, 0, cameraHeight * 2); } gameCamera.finishCamera(); /* * e.printStackTrace(); System.out.println("Camera error: " + e); * cameraHeight = 750; cameraVertical = 920; fogVar = 0; */ method119(); if (actionPictureType > 0) gameGraphics.drawPicture(actionPictureX - 8, actionPictureY - 8, SPRITE_MEDIA_START + 14 + (24 - actionPictureType) / 6); if (actionPictureType < 0) gameGraphics.drawPicture(actionPictureX - 8, actionPictureY - 8, SPRITE_MEDIA_START + 18 + (24 + actionPictureType) / 6); try { MessageQueue.getQueue().checkProcessMessages(); int height = 55; if (MessageQueue.getQueue().hasMessages()) { for (Message m : MessageQueue.getQueue().getList()) { if (m.isBIG) continue; gameGraphics.drawString(m.message, 8, height, 1, 0xffff00); height += 12; } for (Message m : MessageQueue.getQueue().getList()) { if (m.isBIG) { gameGraphics.drawString(m.message, 120, 100, 7, 0xffff00); } } } } catch (Exception e) { e.printStackTrace(); } if (systemUpdate != 0) { int i6 = systemUpdate / 50; int j8 = i6 / 60; i6 %= 60; if (i6 < 10)// redflag gameGraphics.drawText("System update in: " + j8 + ":0" + i6, 256 + xAddition, windowHeight - 7, 1, 0xffff00); else gameGraphics.drawText("System update in: " + j8 + ":" + i6, 256 + xAddition, windowHeight - 7, 1, 0xffff00); } // #pmd# if (!notInWilderness) { int j6 = 2203 - (getSectionY() + wildY + getAreaY()); if (getSectionX() + wildX + getAreaX() >= 2640) j6 = -50; if (j6 > 0) { int k8 = 1 + j6 / 6; gameGraphics.drawPicture(windowWidth - 50, windowHeight - 56, SPRITE_MEDIA_START + 13); int minx = 12; int maxx = 91; int miny = 4; int maxy = 33; // command == 1 int ourX = (getSectionX() + getAreaX()); int ourY = (getSectionY() + getAreaY()); if (ourX > minx && ourX < maxx && ourY > miny && ourY < maxy) { gameGraphics.drawText("@whi@CTF", windowWidth - 40, windowHeight - 20, 1, 0xffff00); gameGraphics.drawText("@red@Red: @whi@" + GameWindowMiddleMan.redPoints + " @blu@Blue: @whi@" + GameWindowMiddleMan.bluePoints, windowWidth - 40, windowHeight - 7, 1, 0xffff00); } else { // Coords: gameGraphics.drawText("Wilderness", windowWidth - 40, windowHeight - 20, 1, 0xffff00); gameGraphics.drawText("Level: " + k8, windowWidth - 40, windowHeight - 7, 1, 0xffff00); } if (wildernessType == 0) wildernessType = 2; } if (wildernessType == 0 && j6 > -10 && j6 <= 0) wildernessType = 1; } if (messagesTab == 0) { for (int k6 = 0; k6 < messagesArray.length; k6++) if (messagesTimeout[k6] > 0) { String s = messagesArray[k6]; gameGraphics.drawString(s, 7, windowHeight - 18 - k6 * 12, 1, 0xffff00); } } gameMenu.method171(messagesHandleType2); gameMenu.method171(messagesHandleType5); gameMenu.method171(messagesHandleType6); if (messagesTab == 1) gameMenu.method170(messagesHandleType2); else if (messagesTab == 2) gameMenu.method170(messagesHandleType5); else if (messagesTab == 3) gameMenu.method170(messagesHandleType6); Menu.anInt225 = 2; gameMenu.drawMenu(); Menu.anInt225 = 0; gameGraphics.method232( ((GameImage) (gameGraphics)).menuDefaultWidth - 3 - 197, 3, SPRITE_MEDIA_START, 128); drawGameWindowsMenus(); gameGraphics.drawStringShadows = false; drawChatMessageTabs(); drawOurSpritesOnScreen(); InterfaceHandler.tick(); gameGraphics.drawImage(aGraphics936, 0, 0); } /** * Draws our sprites on screen when needed */ private void drawOurSpritesOnScreen() { if (mouseOverMenu != 7) gameGraphics.drawBoxAlpha( ((GameImage) (gameGraphics)).menuDefaultWidth - 232, 3, 31, 32, GameImage.convertRGBToLong(181, 181, 181), 128); gameGraphics.drawPicture(windowWidth - 240, 2, SPRITE_ITEM_START + EntityHandler.getItemDef(167).getSprite()); } private final void drawRightClickMenu() { if (mouseButtonClick != 0) { for (int i = 0; i < menuLength; i++) { int k = menuX + 2; int i1 = menuY + 27 + i * 15; if (super.mouseX <= k - 2 || super.mouseY <= i1 - 12 || super.mouseY >= i1 + 4 || super.mouseX >= (k - 3) + menuWidth) continue; menuClick(menuIndexes[i]); break; } mouseButtonClick = 0; showRightClickMenu = false; return; } if (super.mouseX < menuX - 10 || super.mouseY < menuY - 10 || super.mouseX > menuX + menuWidth + 10 || super.mouseY > menuY + menuHeight + 10) { showRightClickMenu = false; return; } gameGraphics.drawBoxAlpha(menuX, menuY, menuWidth, menuHeight, 0xd0d0d0, 160); gameGraphics.drawString("Choose option", menuX + 2, menuY + 12, 1, 65535); for (int j = 0; j < menuLength; j++) { int l = menuX + 2; int j1 = menuY + 27 + j * 15; int k1 = 0xffffff; if (super.mouseX > l - 2 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && super.mouseX < (l - 3) + menuWidth) k1 = 0xffff00; gameGraphics.drawString(menuText1[menuIndexes[j]] + " " + menuText2[menuIndexes[j]], l, j1, 1, k1); } } protected final void resetIntVars() { systemUpdate = 0; loginScreenNumber = 0; loggedIn = 0; logoutTimeout = 0; for (int i = 0; i < questStage.length; i++) questStage[i] = 0; questPoints = 0; } private final void drawQuestionMenu() { if (mouseButtonClick != 0) { for (int i = 0; i < questionMenuCount; i++) { if (super.mouseX >= gameGraphics.textWidth( questionMenuAnswer[i], 1) || super.mouseY <= i * 12 || super.mouseY >= 12 + i * 12) continue; super.streamClass.createPacket(154); super.streamClass.addByte(i); super.streamClass.formatPacket(); break; } mouseButtonClick = 0; showQuestionMenu = false; return; } for (int j = 0; j < questionMenuCount; j++) { int k = 65535; if (super.mouseX < gameGraphics.textWidth(questionMenuAnswer[j], 1) && super.mouseY > j * 12 && super.mouseY < 12 + j * 12) k = 0xff0000; gameGraphics .drawString(questionMenuAnswer[j], 6, 12 + j * 12, 1, k); // KO9 breaking! // questionmenu.Questions[j] = questionMenuAnswer[j]; } // questionmenu.isVisible = true; } private final void walkToAction(int actionX, int actionY, int actionType) { if (actionType == 0) { sendWalkCommand(getSectionX(), getSectionY(), actionX, actionY - 1, actionX, actionY, false, true); return; } if (actionType == 1) { sendWalkCommand(getSectionX(), getSectionY(), actionX - 1, actionY, actionX, actionY, false, true); return; } else { sendWalkCommand(getSectionX(), getSectionY(), actionX, actionY, actionX, actionY, true, true); return; } } private final void garbageCollect() { try { if (gameGraphics != null) { gameGraphics.cleanupSprites(); gameGraphics.imagePixelArray = null; gameGraphics = null; } if (gameCamera != null) { gameCamera.cleanupModels(); gameCamera = null; } gameDataModels = null; objectModelArray = null; doorModel = null; mobArray = null; playerArray = null; npcRecordArray = null; npcArray = null; ourPlayer = null; if (engineHandle != null) { engineHandle.aModelArray596 = null; engineHandle.aModelArrayArray580 = null; engineHandle.aModelArrayArray598 = null; engineHandle.aModel = null; engineHandle = null; } System.gc(); return; } catch (Exception _ex) { return; } } protected final void loginScreenPrint(String s, String s1) { if (loginScreenNumber == 1) menuNewUser.updateText(anInt900, s + " " + s1); if (loginScreenNumber == 2) menuLogin.updateText(loginStatusText, s + " " + s1); drawLoginScreen(); resetCurrentTimeArray(); } private final void drawInventoryRightClickMenu() { int i = 2203 - (getSectionY() + wildY + getAreaY()); if (getSectionX() + wildX + getAreaX() >= 2640) i = -50; int j = -1; for (int k = 0; k < objectCount; k++) aBooleanArray827[k] = false; for (int l = 0; l < doorCount; l++) aBooleanArray970[l] = false; int i1 = gameCamera.method272(); Model models[] = gameCamera.getVisibleModels(); int ai[] = gameCamera.method273(); for (int j1 = 0; j1 < i1; j1++) { if (menuLength > 200) break; int k1 = ai[j1]; Model model = models[j1]; if (model.anIntArray258[k1] <= 65535 || model.anIntArray258[k1] >= 0x30d40 && model.anIntArray258[k1] <= 0x493e0) if (model == gameCamera.aModel_423) { int i2 = model.anIntArray258[k1] % 10000; int l2 = model.anIntArray258[k1] / 10000; if (l2 == 1) { String s = ""; int k3 = 0; if (ourPlayer.level > 0 && playerArray[i2].level > 0) k3 = ourPlayer.level - playerArray[i2].level; if (k3 < 0) s = "@or1@"; if (k3 < -3) s = "@or2@"; if (k3 < -6) s = "@or3@"; if (k3 < -9) s = "@red@"; if (k3 > 0) s = "@gr1@"; if (k3 > 3) s = "@gr2@"; if (k3 > 6) s = "@gr3@"; if (k3 > 9) s = "@gre@"; s = " " + s + "(level-" + playerArray[i2].level + ")"; if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 1 || EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 2) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 800; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 810; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { // Max hit if (i > 0 && (playerArray[i2].currentY - 64) / magicLoc + wildY + getAreaY() < 2203) { menuText1[menuLength] = "Attack"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; if (k3 >= 0 && k3 < 5) menuID[menuLength] = 805; else menuID[menuLength] = 2805; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } else { menuText1[menuLength] = "Duel with"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + "@whi@" + playerArray[i2].name + s; menuActionX[menuLength] = playerArray[i2].currentX; menuActionY[menuLength] = playerArray[i2].currentY; menuID[menuLength] = 2806; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Trade with"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 2810; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; menuText1[menuLength] = "Follow"; menuText2[menuLength] = (playerArray[i2].admin == 1 ? "#pmd#" : "") + (playerArray[i2].admin == 2 ? "#mod#" : "") + (playerArray[i2].admin == 3 ? "#adm#" : "") + "@whi@" + playerArray[i2].name + s; menuID[menuLength] = 2820; menuActionType[menuLength] = playerArray[i2].serverIndex; menuLength++; } } else if (l2 == 2) { ItemDef itemDef = EntityHandler .getItemDef(groundItemType[i2]); if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 3) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 200; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 210; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { menuText1[menuLength] = "Take"; menuText2[menuLength] = "@lre@" + itemDef.getName(); menuID[menuLength] = 220; menuActionX[menuLength] = groundItemX[i2]; menuActionY[menuLength] = groundItemY[i2]; menuActionType[menuLength] = groundItemType[i2]; menuLength++; menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@lre@" + itemDef.getName() + (ourPlayer.admin >= 1 ? " @or1@(" + groundItemType[i2] + ":" + (groundItemX[i2] + getAreaX()) + "," + (groundItemY[i2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3200; menuActionType[menuLength] = groundItemType[i2]; menuLength++; } } else if (l2 == 3) { String s1 = ""; int l3 = -1; NPCDef npcDef = EntityHandler .getNpcDef(npcArray[i2].type); if (npcDef.isAttackable()) { int j4 = (npcDef.getAtt() + npcDef.getDef() + npcDef.getStr() + npcDef.getHits()) / 4; int k4 = (playerStatBase[0] + playerStatBase[1] + playerStatBase[2] + playerStatBase[3] + 27) / 4; l3 = k4 - j4; s1 = "@yel@"; if (l3 < 0) s1 = "@or1@"; if (l3 < -3) s1 = "@or2@"; if (l3 < -6) s1 = "@or3@"; if (l3 < -9) s1 = "@red@"; if (l3 > 0) s1 = "@gr1@"; if (l3 > 3) s1 = "@gr2@"; if (l3 > 6) s1 = "@gr3@"; if (l3 > 9) s1 = "@gre@"; s1 = " " + s1 + "(level-" + j4 + ")"; } if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 2) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 700; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 710; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { if (npcDef.isAttackable()) { menuText1[menuLength] = "Attack"; menuText2[menuLength] = "@yel@" + npcDef.getName() + s1; if (l3 >= 0) menuID[menuLength] = 715; else menuID[menuLength] = 2715; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Talk-to"; menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 720; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; if (!npcDef.getCommand().equals("")) { menuText1[menuLength] = npcDef.getCommand(); menuText2[menuLength] = "@yel@" + npcDef.getName(); menuID[menuLength] = 725; menuActionX[menuLength] = npcArray[i2].currentX; menuActionY[menuLength] = npcArray[i2].currentY; menuActionType[menuLength] = npcArray[i2].serverIndex; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@yel@" + npcDef.getName() + (ourPlayer.admin >= 1 ? " @or1@(" + npcArray[i2].type + ")" : ""); menuID[menuLength] = 3700; menuActionType[menuLength] = npcArray[i2].type; menuLength++; } }// "Skills } else if (model != null && model.anInt257 >= 10000) { int j2 = model.anInt257 - 10000; int i3 = doorType[j2]; if (!aBooleanArray970[j2]) { if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 4) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 300; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuActionVariable[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3).getName(); menuID[menuLength] = 310; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuActionVariable[menuLength] = selectedItem; menuLength++; } else { if (!EntityHandler.getDoorDef(i3).getCommand1() .equalsIgnoreCase("WalkTo")) { menuText1[menuLength] = EntityHandler .getDoorDef(i3).getCommand1(); menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 320; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuLength++; } if (!EntityHandler.getDoorDef(i3).getCommand2() .equalsIgnoreCase("Examine")) { menuText1[menuLength] = EntityHandler .getDoorDef(i3).getCommand2(); menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3) .getName(); menuID[menuLength] = 2300; menuActionX[menuLength] = doorX[j2]; menuActionY[menuLength] = doorY[j2]; menuActionType[menuLength] = doorDirection[j2]; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@cya@" + EntityHandler.getDoorDef(i3).getName() + (ourPlayer.admin >= 1 ? " @or1@(" + i3 + ":" + (doorX[j2] + getAreaX()) + "," + (doorY[j2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3300; menuActionType[menuLength] = i3; menuLength++; } aBooleanArray970[j2] = true; } } else if (model != null && model.anInt257 >= 0) { int k2 = model.anInt257; int j3 = objectType[k2]; if (!aBooleanArray827[k2]) { if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell) .getSpellType() == 5) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef( selectedSpell).getName() + " on"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 400; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuActionVariable2[menuLength] = selectedSpell; menuLength++; } } else if (selectedItem >= 0) { menuText1[menuLength] = "Use " + selectedItemName + " with"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3).getName(); menuID[menuLength] = 410; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuActionVariable2[menuLength] = selectedItem; menuLength++; } else { if (!EntityHandler.getObjectDef(j3).getCommand1() .equalsIgnoreCase("WalkTo")) { menuText1[menuLength] = EntityHandler .getObjectDef(j3).getCommand1(); menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 420; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuLength++; } if (!EntityHandler.getObjectDef(j3).getCommand2() .equalsIgnoreCase("Examine")) { menuText1[menuLength] = EntityHandler .getObjectDef(j3).getCommand2(); menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3) .getName(); menuID[menuLength] = 2400; menuActionX[menuLength] = objectX[k2]; menuActionY[menuLength] = objectY[k2]; menuActionType[menuLength] = objectID[k2]; menuActionVariable[menuLength] = objectType[k2]; menuLength++; } menuText1[menuLength] = "Examine"; menuText2[menuLength] = "@cya@" + EntityHandler.getObjectDef(j3).getName() + (ourPlayer.admin >= 1 ? " @or1@(" + j3 + ":" + (objectX[k2] + getAreaX()) + "," + (objectY[k2] + getAreaY()) + ")" : ""); menuID[menuLength] = 3400; menuActionType[menuLength] = j3; menuLength++; } aBooleanArray827[k2] = true; } } else { if (k1 >= 0) k1 = model.anIntArray258[k1] - 0x30d40; if (k1 >= 0) j = k1; } } if (selectedSpell >= 0 && EntityHandler.getSpellDef(selectedSpell).getSpellType() <= 1) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef(selectedSpell).getName() + " on self"; menuText2[menuLength] = ""; menuID[menuLength] = 1000; menuActionType[menuLength] = selectedSpell; menuLength++; } if (j != -1) { int l1 = j; if (selectedSpell >= 0) { if (EntityHandler.getSpellDef(selectedSpell).getSpellType() == 6) { menuText1[menuLength] = "Cast " + EntityHandler.getSpellDef(selectedSpell) .getName() + " on ground"; menuText2[menuLength] = ""; menuID[menuLength] = 900; menuActionX[menuLength] = engineHandle.selectedX[l1]; menuActionY[menuLength] = engineHandle.selectedY[l1]; menuActionType[menuLength] = selectedSpell; menuLength++; return; } } else if (selectedItem < 0) { menuText1[menuLength] = "Walk here"; menuText2[menuLength] = ""; menuID[menuLength] = 920; menuActionX[menuLength] = engineHandle.selectedX[l1]; menuActionY[menuLength] = engineHandle.selectedY[l1]; menuLength++; } } } protected final void startGame() { int i = 0; for (int j = 0; j < 99; j++) { int k = j + 1; int i1 = (int) ((double) k + 300D * Math.pow(2D, (double) k / 7D)); i += i1; experienceArray[j] = (i & 0xffffffc) / 4; } super.yOffset = 0; GameWindowMiddleMan.maxPacketReadCount = 500; if (appletMode) { CacheManager.load("Loading.rscd"); setLogo(Toolkit.getDefaultToolkit().getImage( Config.CONF_DIR + File.separator + "Loading.rscd")); } loadConfigFilter(); // 15% if (lastLoadedNull) { return; } aGraphics936 = getGraphics(); changeThreadSleepModifier(50); gameGraphics = new GameImageMiddleMan(windowWidth, windowHeight + 12, 4000, this); gameGraphics._mudclient = this; GameFrame.setClient(mc); GameWindow.setClient(this); gameGraphics.setDimensions(0, 0, windowWidth, windowHeight + 12); Menu.aBoolean220 = false; /* Menu.anInt221 = anInt902; */ spellMenu = new Menu(gameGraphics, 5); int l = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; spellMenuHandle = spellMenu.method162(l, byte0 + 24, 196, 90, 1, 500, true); friendsMenu = new Menu(gameGraphics, 5); friendsMenuHandle = friendsMenu.method162(l, byte0 + 40, 196, 126, 1, 500, true); questMenu = new Menu(gameGraphics, 5); questMenuHandle = questMenu.method162(l, byte0 + 40, 196, 235, 1, 500, true); loadMedia(); // 30% if (lastLoadedNull) return; loadEntity(); // 45% if (lastLoadedNull) return; gameCamera = new Camera(gameGraphics, 15000, 15000, 1000); gameCamera.setCameraSize(windowWidth / 2, windowHeight / 2, windowWidth / 2, windowHeight / 2, windowWidth, cameraSizeInt); if (fog) { gameCamera.zoom1 = 2400 + fogVar; gameCamera.zoom2 = 2400 + fogVar; gameCamera.zoom3 = 1; gameCamera.zoom4 = 2300 + fogVar; } else { gameCamera.zoom1 = 41000; gameCamera.zoom2 = 41000; gameCamera.zoom3 = 1; gameCamera.zoom4 = 41000; } gameCamera.method303(-50, -10, -50); engineHandle = new EngineHandle(gameCamera, gameGraphics); loadTextures(); // 60% if (lastLoadedNull) return; loadModels(); // 75% if (lastLoadedNull) return; loadSounds(); // 90% if (lastLoadedNull) return; CacheManager.doneLoading(); drawDownloadProgress("Starting game...", 100, false); drawGameMenu(); makeLoginMenus(); makeCharacterDesignMenu(); makeDPSMenu(); resetLoginVars(); menusLoaded = true; } private final void loadSprite(int id, String packageName, int amount) { for (int i = id; i < id + amount; i++) { if (!gameGraphics.loadSprite(i, packageName)) { lastLoadedNull = true; return; } } } private final void loadMedia() { drawDownloadProgress("Unpacking media", 30, false); loadSprite(SPRITE_MEDIA_START, "media", 1); loadSprite(SPRITE_MEDIA_START + 1, "media", 6); loadSprite(SPRITE_MEDIA_START + 9, "media", 1); loadSprite(SPRITE_MEDIA_START + 10, "media", 1); loadSprite(SPRITE_MEDIA_START + 11, "media", 3); loadSprite(SPRITE_MEDIA_START + 14, "media", 8); loadSprite(SPRITE_MEDIA_START + 22, "media", 1); loadSprite(SPRITE_MEDIA_START + 23, "media", 1); loadSprite(SPRITE_MEDIA_START + 24, "media", 1); loadSprite(SPRITE_MEDIA_START + 25, "media", 2); loadSprite(SPRITE_UTIL_START, "media", 2); loadSprite(SPRITE_UTIL_START + 2, "media", 4); loadSprite(SPRITE_UTIL_START + 6, "media", 2); loadSprite(SPRITE_PROJECTILE_START, "media", 7); loadSprite(SPRITE_LOGO_START, "media", 1); int i = EntityHandler.invPictureCount(); for (int j = 1; i > 0; j++) { int k = i; i -= 30; if (k > 30) { k = 30; } loadSprite(SPRITE_ITEM_START + (j - 1) * 30, "media.object", k); } } private final void loadEntity() { drawDownloadProgress("Unpacking entities", 45, false); int animationNumber = 0; label0: for (int animationIndex = 0; animationIndex < EntityHandler .animationCount(); animationIndex++) { String s = EntityHandler.getAnimationDef(animationIndex).getName(); for (int nextAnimationIndex = 0; nextAnimationIndex < animationIndex; nextAnimationIndex++) { if (!EntityHandler.getAnimationDef(nextAnimationIndex) .getName().equalsIgnoreCase(s)) { continue; } EntityHandler.getAnimationDef(animationIndex).number = EntityHandler .getAnimationDef(nextAnimationIndex).getNumber(); continue label0; } loadSprite(animationNumber, "entity", 15); if (EntityHandler.getAnimationDef(animationIndex).hasA()) { loadSprite(animationNumber + 15, "entity", 3); } if (EntityHandler.getAnimationDef(animationIndex).hasF()) { loadSprite(animationNumber + 18, "entity", 9); } EntityHandler.getAnimationDef(animationIndex).number = animationNumber; animationNumber += 27; } } private final void loadTextures() { drawDownloadProgress("Unpacking textures", 60, false); gameCamera.method297(EntityHandler.textureCount(), 7, 11); for (int i = 0; i < EntityHandler.textureCount(); i++) { loadSprite(SPRITE_TEXTURE_START + i, "texture", 1); Sprite sprite = ((GameImage) (gameGraphics)).sprites[SPRITE_TEXTURE_START + i]; int length = sprite.getWidth() * sprite.getHeight(); int[] pixels = sprite.getPixels(); int ai1[] = new int[32768]; for (int k = 0; k < length; k++) { ai1[((pixels[k] & 0xf80000) >> 9) + ((pixels[k] & 0xf800) >> 6) + ((pixels[k] & 0xf8) >> 3)]++; } int[] dictionary = new int[256]; dictionary[0] = 0xff00ff; int[] temp = new int[256]; for (int i1 = 0; i1 < ai1.length; i1++) { int j1 = ai1[i1]; if (j1 > temp[255]) { for (int k1 = 1; k1 < 256; k1++) { if (j1 <= temp[k1]) { continue; } for (int i2 = 255; i2 > k1; i2--) { dictionary[i2] = dictionary[i2 - 1]; temp[i2] = temp[i2 - 1]; } dictionary[k1] = ((i1 & 0x7c00) << 9) + ((i1 & 0x3e0) << 6) + ((i1 & 0x1f) << 3) + 0x40404; temp[k1] = j1; break; } } ai1[i1] = -1; } byte[] indices = new byte[length]; for (int l1 = 0; l1 < length; l1++) { int j2 = pixels[l1]; int k2 = ((j2 & 0xf80000) >> 9) + ((j2 & 0xf800) >> 6) + ((j2 & 0xf8) >> 3); int l2 = ai1[k2]; if (l2 == -1) { int i3 = 0x3b9ac9ff; int j3 = j2 >> 16 & 0xff; int k3 = j2 >> 8 & 0xff; int l3 = j2 & 0xff; for (int i4 = 0; i4 < 256; i4++) { int j4 = dictionary[i4]; int k4 = j4 >> 16 & 0xff; int l4 = j4 >> 8 & 0xff; int i5 = j4 & 0xff; int j5 = (j3 - k4) * (j3 - k4) + (k3 - l4) * (k3 - l4) + (l3 - i5) * (l3 - i5); if (j5 < i3) { i3 = j5; l2 = i4; } } ai1[k2] = l2; } indices[l1] = (byte) l2; } gameCamera.method298(i, indices, dictionary, sprite.getSomething1() / 64 - 1); } } /* * private int lastMouseButton = -1; private int lastMouseX = -1; private * int lastMouseY = -1; private double camVert = 0.0D; private double camRot * = 0.0D; private java.awt.Robot robot; protected final void * handleMouseDrag(MouseEvent mouse, int x, int y, int button) { * if(controlDown && button == 2) { int unitX = x - lastMouseX; * * if(unitX > 1) unitX = 1; else if(unitX < -1) unitX = -1; * * int unitY = lastMouseY - y; * * if(unitY > 1) unitY = 1; else if(unitY < -1) unitY = -1; * * cameraVertical += unitY; //cameraRotation += unitX; * * System.out.println("Y: " + y + ", LastY: " + lastMouseY + " dif: (" + (y * - lastMouseY) + ")"); * * lastMouseX = x; lastMouseY = y; //super.mouseX = lastMouseX; * //super.mouseY = lastMouseY; //robot.mouseMove(super.mouseX, * super.mouseY); } } */ private final void checkMouseStatus() { /* * lastMouseX = * (int)java.awt.MouseInfo.getPointerInfo().getLocation().getX(); * lastMouseY = * (int)java.awt.MouseInfo.getPointerInfo().getLocation().getY(); * lastMouseButton = mouseButtonClick; * * if(mouseButtonClick == 2 && controlDown) return; */ if (selectedSpell >= 0 || selectedItem >= 0) { menuText1[menuLength] = "Cancel"; menuText2[menuLength] = ""; menuID[menuLength] = 4000; menuLength++; } for (int i = 0; i < menuLength; i++) menuIndexes[i] = i; for (boolean flag = false; !flag;) { flag = true; for (int j = 0; j < menuLength - 1; j++) { int l = menuIndexes[j]; int j1 = menuIndexes[j + 1]; if (menuID[l] > menuID[j1]) { menuIndexes[j] = j1; menuIndexes[j + 1] = l; flag = false; } } } if (menuLength > 20) menuLength = 20; if (menuLength > 0) { int k = -1; for (int i1 = 0; i1 < menuLength; i1++) { if (menuText2[menuIndexes[i1]] == null || menuText2[menuIndexes[i1]].length() <= 0) continue; k = i1; break; } String s = null; if ((selectedItem >= 0 || selectedSpell >= 0) && menuLength == 1) s = "Choose a target"; else if ((selectedItem >= 0 || selectedSpell >= 0) && menuLength > 1) s = "@whi@" + menuText1[menuIndexes[0]] + " " + menuText2[menuIndexes[0]]; else if (k != -1) s = menuText2[menuIndexes[k]] + ": @whi@" + menuText1[menuIndexes[0]]; if (menuLength == 2 && s != null) s = s + "@whi@ / 1 more option"; if (menuLength > 2 && s != null) s = s + "@whi@ / " + (menuLength - 1) + " more options"; if (s != null) gameGraphics.drawString(s, 6, 14, 1, 0xffff00); if (!configMouseButtons && mouseButtonClick == 1 || configMouseButtons && mouseButtonClick == 1 && menuLength == 1) { menuClick(menuIndexes[0]); mouseButtonClick = 0; return; } if (!configMouseButtons && mouseButtonClick == 2 || configMouseButtons && mouseButtonClick == 1) { menuHeight = (menuLength + 1) * 15; menuWidth = gameGraphics.textWidth("Choose option", 1) + 5; for (int k1 = 0; k1 < menuLength; k1++) { int l1 = gameGraphics.textWidth(menuText1[k1] + " " + menuText2[k1], 1) + 5; if (l1 > menuWidth) menuWidth = l1; } menuX = super.mouseX - menuWidth / 2; menuY = super.mouseY - 7; showRightClickMenu = true; if (menuX < 0) menuX = 0; if (menuY < 0) menuY = 0; if (menuX + menuWidth > (windowWidth - 10)) menuX = (windowWidth - 10) - menuWidth; if (menuY + menuHeight > (windowHeight)) menuY = (windowHeight - 10) - menuHeight; mouseButtonClick = 0; } } } protected final void cantLogout() { logoutTimeout = 0; displayMessage("@cya@Sorry, you can't logout at the moment", 3, 0); } private final void drawFriendsWindow(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 5); char c = '\304'; char c1 = '\266'; int l; int k = l = GameImage.convertRGBToLong(160, 160, 160); if (anInt981 == 0) k = GameImage.convertRGBToLong(220, 220, 220); else l = GameImage.convertRGBToLong(220, 220, 220); int maxWidth = windowWidth - 23; int minWidth = windowWidth - 83; gameGraphics.drawBoxAlpha(i, j, c / 2, 24, k, 128); gameGraphics.drawBoxAlpha(i + c / 2, j, c / 2, 24, l, 128); gameGraphics.drawBoxAlpha(i, j + 24, c, c1 - 24, GameImage.convertRGBToLong(220, 220, 220), 128); gameGraphics.drawLineX(i, j + 24, c, 0); gameGraphics.drawLineY(i + c / 2, j, 24, 0); gameGraphics.drawLineX(i, (j + c1) - 16, c, 0); gameGraphics.drawText("Friends", i + c / 4, j + 16, 4, 0); gameGraphics.drawText("Ignore", i + c / 4 + c / 2, j + 16, 4, 0); friendsMenu.resetListTextCount(friendsMenuHandle); if (anInt981 == 0) { for (int i1 = 0; i1 < super.friendsCount; i1++) { String s; if (super.friendsListOnlineStatus[i1] == 99) s = "@gre@"; else if (super.friendsListOnlineStatus[i1] > 0) s = "@yel@"; else s = "@red@"; friendsMenu .drawMenuListText( friendsMenuHandle, i1, s + DataOperations .longToString(super.friendsListLongs[i1]) + "~" + (windowWidth - 73) + "~" + "@whi@Remove WWWWWWWWWW"); } } if (anInt981 == 1) { for (int j1 = 0; j1 < super.ignoreListCount; j1++) friendsMenu .drawMenuListText( friendsMenuHandle, j1, "@yel@" + DataOperations .longToString(super.ignoreListLongs[j1]) + "~" + (windowWidth - 73) + "~" + "@whi@Remove WWWWWWWWWW"); } friendsMenu.drawMenu(); if (anInt981 == 0) { int k1 = friendsMenu.selectedListIndex(friendsMenuHandle); if (k1 >= 0 && super.mouseX < maxWidth) { if (super.mouseX > minWidth) gameGraphics .drawText( "Click to remove " + DataOperations .longToString(super.friendsListLongs[k1]), i + c / 2, j + 35, 1, 0xffffff); else if (super.friendsListOnlineStatus[k1] == 99) gameGraphics .drawText( "Click to message " + DataOperations .longToString(super.friendsListLongs[k1]), i + c / 2, j + 35, 1, 0xffffff); else if (super.friendsListOnlineStatus[k1] > 0) gameGraphics.drawText( DataOperations .longToString(super.friendsListLongs[k1]) + " is on world " + super.friendsListOnlineStatus[k1], i + c / 2, j + 35, 1, 0xffffff); else gameGraphics.drawText( DataOperations .longToString(super.friendsListLongs[k1]) + " is offline", i + c / 2, j + 35, 1, 0xffffff); } else gameGraphics.drawText("Click a name to send a message", i + c / 2, j + 35, 1, 0xffffff); int k2; if (super.mouseX > i && super.mouseX < i + c && super.mouseY > (j + c1) - 16 && super.mouseY < j + c1) k2 = 0xffff00; else k2 = 0xffffff; gameGraphics.drawText("Click here to add a friend", i + c / 2, (j + c1) - 3, 1, k2); } if (anInt981 == 1) { int l1 = friendsMenu.selectedListIndex(friendsMenuHandle); if (l1 >= 0 && super.mouseX < maxWidth && super.mouseX > minWidth) { if (super.mouseX > minWidth) gameGraphics .drawText( "Click to remove " + DataOperations .longToString(super.ignoreListLongs[l1]), i + c / 2, j + 35, 1, 0xffffff); } else { gameGraphics.drawText("Blocking messages from:", i + c / 2, j + 35, 1, 0xffffff); } int l2; if (super.mouseX > i && super.mouseX < i + c && super.mouseY > (j + c1) - 16 && super.mouseY < j + c1) l2 = 0xffff00; else l2 = 0xffffff; gameGraphics.drawText("Click here to add a name", i + c / 2, (j + c1) - 3, 1, l2); } if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 182) { friendsMenu.updateActions(i + (((GameImage) (gameGraphics)).menuDefaultWidth - 199), j + 36, super.lastMouseDownButton, super.mouseDownButton); if (j <= 24 && mouseButtonClick == 1) if (i < 98 && anInt981 == 1) { anInt981 = 0; friendsMenu.method165(friendsMenuHandle, 0); } else if (i > 98 && anInt981 == 0) { anInt981 = 1; friendsMenu.method165(friendsMenuHandle, 0); } if (mouseButtonClick == 1 && anInt981 == 0) { int i2 = friendsMenu.selectedListIndex(friendsMenuHandle); if (i2 >= 0 && super.mouseX < maxWidth) if (super.mouseX > minWidth) removeFromFriends(super.friendsListLongs[i2]); else if (super.friendsListOnlineStatus[i2] != 0) { inputBoxType = 2; privateMessageTarget = super.friendsListLongs[i2]; super.inputMessage = ""; super.enteredMessage = ""; } } if (mouseButtonClick == 1 && anInt981 == 1) { int j2 = friendsMenu.selectedListIndex(friendsMenuHandle); if (j2 >= 0 && super.mouseX < maxWidth && super.mouseX > minWidth) removeFromIgnoreList(super.ignoreListLongs[j2]); } if (j > 166 && mouseButtonClick == 1 && anInt981 == 0) { inputBoxType = 1; super.inputText = ""; super.enteredText = ""; } if (j > 166 && mouseButtonClick == 1 && anInt981 == 1) { inputBoxType = 3; super.inputText = ""; super.enteredText = ""; } mouseButtonClick = 0; } } private final boolean loadSection(int i, int j) { if (playerAliveTimeout != 0) { engineHandle.playerIsAlive = false; return false; } notInWilderness = false; i += wildX; j += wildY; if (lastWildYSubtract == wildYSubtract && i > anInt789 && i < anInt791 && j > anInt790 && j < anInt792) { engineHandle.playerIsAlive = true; return false; } gameGraphics.drawText("Loading... Please wait", 256 + xAddition, 192 + yAddition, 1, 0xffffff); drawChatMessageTabs(); drawOurSpritesOnScreen(); gameGraphics.drawImage(aGraphics936, 0, 0); int k = getAreaX(); int l = getAreaY(); int i1 = (i + 24) / 48; int j1 = (j + 24) / 48; lastWildYSubtract = wildYSubtract; setAreaX(i1 * 48 - 48); setAreaY(j1 * 48 - 48); anInt789 = i1 * 48 - 32; anInt790 = j1 * 48 - 32; anInt791 = i1 * 48 + 32; anInt792 = j1 * 48 + 32; engineHandle.method401(i, j, lastWildYSubtract); setAreaX(getAreaX() - wildX); setAreaY(getAreaY() - wildY); int k1 = getAreaX() - k; int l1 = getAreaY() - l; for (int i2 = 0; i2 < objectCount; i2++) { objectX[i2] -= k1; objectY[i2] -= l1; int j2 = objectX[i2]; int l2 = objectY[i2]; int k3 = objectType[i2]; int m4 = objectID[i2]; Model model = objectModelArray[i2]; try { int l4 = objectID[i2]; int k5; int i6; if (l4 == 0 || l4 == 4) { k5 = EntityHandler.getObjectDef(k3).getWidth(); i6 = EntityHandler.getObjectDef(k3).getHeight(); } else { i6 = EntityHandler.getObjectDef(k3).getWidth(); k5 = EntityHandler.getObjectDef(k3).getHeight(); } int j6 = ((j2 + j2 + k5) * magicLoc) / 2; int k6 = ((l2 + l2 + i6) * magicLoc) / 2; if (j2 >= 0 && l2 >= 0 && j2 < 96 && l2 < 96) { gameCamera.addModel(model); model.method191(j6, -engineHandle.getAveragedElevation(j6, k6), k6); engineHandle.method412(j2, l2, k3, m4); if (k3 == 74) model.method190(0, -480, 0); } } catch (RuntimeException runtimeexception) { System.out.println("Loc Error: " + runtimeexception.getMessage()); System.out.println("i:" + i2 + " obj:" + model); runtimeexception.printStackTrace(); } } for (int k2 = 0; k2 < doorCount; k2++) { doorX[k2] -= k1; doorY[k2] -= l1; int i3 = doorX[k2]; int l3 = doorY[k2]; int j4 = doorType[k2]; int i5 = doorDirection[k2]; try { engineHandle.method408(i3, l3, i5, j4); Model model_1 = makeModel(i3, l3, i5, j4, k2); doorModel[k2] = model_1; } catch (RuntimeException runtimeexception1) { System.out.println("Bound Error: " + runtimeexception1.getMessage()); runtimeexception1.printStackTrace(); } } for (int j3 = 0; j3 < groundItemCount; j3++) { groundItemX[j3] -= k1; groundItemY[j3] -= l1; } for (int i4 = 0; i4 < playerCount; i4++) { Mob mob = playerArray[i4]; mob.currentX -= k1 * magicLoc; mob.currentY -= l1 * magicLoc; for (int j5 = 0; j5 <= mob.waypointCurrent; j5++) { mob.waypointsX[j5] -= k1 * magicLoc; mob.waypointsY[j5] -= l1 * magicLoc; } } for (int k4 = 0; k4 < npcCount; k4++) { Mob mob_1 = npcArray[k4]; mob_1.currentX -= k1 * magicLoc; mob_1.currentY -= l1 * magicLoc; for (int l5 = 0; l5 <= mob_1.waypointCurrent; l5++) { mob_1.waypointsX[l5] -= k1 * magicLoc; mob_1.waypointsY[l5] -= l1 * magicLoc; } } engineHandle.playerIsAlive = true; return true; } private final void drawMagicWindow(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 4); char c = '\304'; char c1 = '\266'; int l; int k = l = GameImage.convertRGBToLong(160, 160, 160); if (menuMagicPrayersSelected == 0) k = GameImage.convertRGBToLong(220, 220, 220); else l = GameImage.convertRGBToLong(220, 220, 220); gameGraphics.drawBoxAlpha(i, j, c / 2, 24, k, 128); gameGraphics.drawBoxAlpha(i + c / 2, j, c / 2, 24, l, 128); gameGraphics.drawBoxAlpha(i, j + 24, c, 90, GameImage.convertRGBToLong(220, 220, 220), 128); gameGraphics.drawBoxAlpha(i, j + 24 + 90, c, c1 - 90 - 24, GameImage.convertRGBToLong(160, 160, 160), 128); gameGraphics.drawLineX(i, j + 24, c, 0); gameGraphics.drawLineY(i + c / 2, j, 24, 0); gameGraphics.drawLineX(i, j + 113, c, 0); gameGraphics.drawText("Magic", i + c / 4, j + 16, 4, 0); gameGraphics.drawText("Prayers", i + c / 4 + c / 2, j + 16, 4, 0); if (menuMagicPrayersSelected == 0) { spellMenu.resetListTextCount(spellMenuHandle); int i1 = 0; for (int spellIndex = 0; spellIndex < EntityHandler.spellCount(); spellIndex++) { String s = "@yel@"; for (Entry e : EntityHandler.getSpellDef(spellIndex) .getRunesRequired()) { if (hasRequiredRunes((Integer) e.getKey(), (Integer) e.getValue())) { continue; } s = "@whi@"; break; } int spellLevel = playerStatCurrent[6]; if (EntityHandler.getSpellDef(spellIndex).getReqLevel() > spellLevel) { s = "@bla@"; } spellMenu.drawMenuListText(spellMenuHandle, i1++, s + "Level " + EntityHandler.getSpellDef(spellIndex).getReqLevel() + ": " + EntityHandler.getSpellDef(spellIndex).getName()); } spellMenu.drawMenu(); int selectedSpellIndex = spellMenu .selectedListIndex(spellMenuHandle); if (selectedSpellIndex != -1) { gameGraphics .drawString( "Level " + EntityHandler.getSpellDef( selectedSpellIndex) .getReqLevel() + ": " + EntityHandler.getSpellDef( selectedSpellIndex).getName(), i + 2, j + 124, 1, 0xffff00); gameGraphics.drawString( EntityHandler.getSpellDef(selectedSpellIndex) .getDescription(), i + 2, j + 136, 0, 0xffffff); int i4 = 0; for (Entry<Integer, Integer> e : EntityHandler.getSpellDef( selectedSpellIndex).getRunesRequired()) { int runeID = e.getKey(); gameGraphics.drawPicture(i + 2 + i4 * 44, j + 150, SPRITE_ITEM_START + EntityHandler.getItemDef(runeID) .getSprite()); int runeInvCount = inventoryCount(runeID); int runeCount = e.getValue(); String s2 = "@red@"; if (hasRequiredRunes(runeID, runeCount)) { s2 = "@gre@"; } gameGraphics.drawString( s2 + runeInvCount + "/" + runeCount, i + 2 + i4 * 44, j + 150, 1, 0xffffff); i4++; } } else { gameGraphics.drawString("Point at a spell for a description", i + 2, j + 124, 1, 0); } } if (menuMagicPrayersSelected == 1) { spellMenu.resetListTextCount(spellMenuHandle); int j1 = 0; for (int j2 = 0; j2 < EntityHandler.prayerCount(); j2++) { String s1 = "@whi@"; if (EntityHandler.getPrayerDef(j2).getReqLevel() > playerStatBase[5]) s1 = "@bla@"; if (prayerOn[j2]) s1 = "@gre@"; spellMenu.drawMenuListText(spellMenuHandle, j1++, s1 + "Level " + EntityHandler.getPrayerDef(j2).getReqLevel() + ": " + EntityHandler.getPrayerDef(j2).getName()); } spellMenu.drawMenu(); int j3 = spellMenu.selectedListIndex(spellMenuHandle); if (j3 != -1) { gameGraphics.drawText("Level " + EntityHandler.getPrayerDef(j3).getReqLevel() + ": " + EntityHandler.getPrayerDef(j3).getName(), i + c / 2, j + 130, 1, 0xffff00); if (j3 == 13) { if (playerStatBase[5] > 39) { int percent = (int) ((playerStatBase[5] - 40) * 0.6); percent += 60; if (percent > 100) percent = 100; gameGraphics.drawText(percent + "% protection from ranged attack", i + c / 2, j + 145, 0, 0xffffff); } else gameGraphics.drawText( "60% protection from ranged attack", i + c / 2, j + 145, 0, 0xffffff); } else gameGraphics.drawText(EntityHandler.getPrayerDef(j3) .getDescription(), i + c / 2, j + 145, 0, 0xffffff); gameGraphics.drawText("Drain rate: " + EntityHandler.getPrayerDef(j3).getDrainRate(), i + c / 2, j + 160, 1, 0); } else { gameGraphics.drawString("Point at a prayer for a description", i + 2, j + 124, 1, 0); } } if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 182) { spellMenu.updateActions(i + (((GameImage) (gameGraphics)).menuDefaultWidth - 199), j + 36, super.lastMouseDownButton, super.mouseDownButton); if (j <= 24 && mouseButtonClick == 1) if (i < 98 && menuMagicPrayersSelected == 1) { menuMagicPrayersSelected = 0; prayerMenuIndex = spellMenu.getMenuIndex(spellMenuHandle); spellMenu.method165(spellMenuHandle, magicMenuIndex); } else if (i > 98 && menuMagicPrayersSelected == 0) { menuMagicPrayersSelected = 1; magicMenuIndex = spellMenu.getMenuIndex(spellMenuHandle); spellMenu.method165(spellMenuHandle, prayerMenuIndex); } if (mouseButtonClick == 1 && menuMagicPrayersSelected == 0) { int k1 = spellMenu.selectedListIndex(spellMenuHandle); if (k1 != -1) { int k2 = playerStatCurrent[6]; if (EntityHandler.getSpellDef(k1).getReqLevel() > k2) { displayMessage( "Your magic ability is not high enough for this spell", 3, 0); } else { int k3 = 0; for (Entry<Integer, Integer> e : EntityHandler .getSpellDef(k1).getRunesRequired()) { if (!hasRequiredRunes(e.getKey(), e.getValue())) { displayMessage( "You don't have all the reagents you need for this spell", 3, 0); k3 = -1; break; } k3++; } if (k3 == EntityHandler.getSpellDef(k1).getRuneCount()) { selectedSpell = k1; selectedItem = -1; } } } } if (mouseButtonClick == 1 && menuMagicPrayersSelected == 1) { int l1 = spellMenu.selectedListIndex(spellMenuHandle); if (l1 != -1) { int l2 = playerStatBase[5]; if (EntityHandler.getPrayerDef(l1).getReqLevel() > l2) displayMessage( "Your prayer ability is not high enough for this prayer", 3, 0); else if (playerStatCurrent[5] == 0) displayMessage( "You have run out of prayer points. Return to a church to recharge", 3, 0); else if (prayerOn[l1]) { super.streamClass.createPacket(248); super.streamClass.addByte(l1); super.streamClass.formatPacket(); prayerOn[l1] = false; playSound("prayeroff"); } else { super.streamClass.createPacket(56); super.streamClass.addByte(l1); super.streamClass.formatPacket(); prayerOn[l1] = true; playSound("prayeron"); } } } mouseButtonClick = 0; } } protected final void handleWheelRotate(int units) { if (super.controlDown) { if (units > -1) { if (cameraVertical >= 1000) return; } else { if (cameraVertical <= 850) return; } cameraVertical += units * 2; } } protected final void handleMenuKeyDown(int key, char keyChar) { if (!menusLoaded) return; switch (key) { case 123: // F12 takeScreenshot(true); break; case 33: { if (cameraHeight < 300) { cameraHeight += 25; } else { cameraHeight -= 25; } break; } case 34: { // Page Down { if (cameraHeight > 1500) { cameraHeight -= 25; } else { cameraHeight += 25; } break; } case 36: { cameraHeight = 750; break; } } if (loggedIn == 0) { if (loginScreenNumber == 0) menuWelcome.keyDown(key, keyChar); if (loginScreenNumber == 1) menuNewUser.keyDown(key, keyChar); if (loginScreenNumber == 2) menuLogin.keyDown(key, keyChar); } if (loggedIn == 1) { if (showCharacterLookScreen) { characterDesignMenu.keyDown(key, keyChar); return; } if (showDrawPointsScreen) { drawPointsScreen.keyDown(key, keyChar); return; } if (inputBoxType == 0 && showAbuseWindow == 0) gameMenu.keyDown(key, keyChar); } } private final void drawShopBox() { if (mouseButtonClick != 0) { mouseButtonClick = 0; int i = super.mouseX - 52 - xAddition; int j = super.mouseY - 44 - yAddition; if (i >= 0 && j >= 12 && i < 408 && j < 246) { int k = 0; for (int i1 = 0; i1 < 5; i1++) { for (int i2 = 0; i2 < 8; i2++) { int l2 = 7 + i2 * 49; int l3 = 28 + i1 * 34; if (i > l2 && i < l2 + 49 && j > l3 && j < l3 + 34 && shopItems[k] != -1) { selectedShopItemIndex = k; selectedShopItemType = shopItems[k]; } k++; } } if (selectedShopItemIndex >= 0) { int j2 = shopItems[selectedShopItemIndex]; if (j2 != -1) { if (shopItemCount[selectedShopItemIndex] > 0 && i > 298 && j >= 204 && i < 408 && j <= 215) { int i4 = shopItemsBuyPrice[selectedShopItemIndex];// (shopItemBuyPriceModifier // * // EntityHandler.getItemDef(j2).getBasePrice()) // / // 100; super.streamClass.createPacket(128); super.streamClass .add2ByteInt(shopItems[selectedShopItemIndex]); super.streamClass.add4ByteInt(i4); super.streamClass.formatPacket(); } if (inventoryCount(j2) > 0 && i > 2 && j >= 229 && i < 112 && j <= 240) { int j4 = shopItemsSellPrice[selectedShopItemIndex];// (shopItemSellPriceModifier // * // EntityHandler.getItemDef(j2).getBasePrice()) // / // 100; super.streamClass.createPacket(255); super.streamClass .add2ByteInt(shopItems[selectedShopItemIndex]); super.streamClass.add4ByteInt(j4); super.streamClass.formatPacket(); } } } } else { super.streamClass.createPacket(253); super.streamClass.formatPacket(); showShop = false; return; } } int byte0 = 52 + xAddition; int byte1 = 44 + yAddition; gameGraphics.drawBox(byte0, byte1, 408, 12, 192); int l = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 408, 17, l, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 29, 8, 170, l, 160); gameGraphics.drawBoxAlpha(byte0 + 399, byte1 + 29, 9, 170, l, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 199, 408, 47, l, 160); gameGraphics.drawString("Buying and selling items", byte0 + 1, byte1 + 10, 1, 0xffffff); int j1 = 0xffffff; if (super.mouseX > byte0 + 320 && super.mouseY >= byte1 && super.mouseX < byte0 + 408 && super.mouseY < byte1 + 12) j1 = 0xff0000; gameGraphics.drawBoxTextRight("Close window", byte0 + 406, byte1 + 10, 1, j1); gameGraphics.drawString("Shops stock in green", byte0 + 2, byte1 + 24, 1, 65280); gameGraphics.drawString("Number you own in blue", byte0 + 135, byte1 + 24, 1, 65535); gameGraphics.drawString("Your money: " + inventoryCount(10) + "gp", byte0 + 280, byte1 + 24, 1, 0xffff00); int k2 = 0xd0d0d0; int k3 = 0; for (int k4 = 0; k4 < 5; k4++) { for (int l4 = 0; l4 < 8; l4++) { int j5 = byte0 + 7 + l4 * 49; int i6 = byte1 + 28 + k4 * 34; if (selectedShopItemIndex == k3) gameGraphics.drawBoxAlpha(j5, i6, 49, 34, 0xff0000, 160); else gameGraphics.drawBoxAlpha(j5, i6, 49, 34, k2, 160); gameGraphics.drawBoxEdge(j5, i6, 50, 35, 0); if (shopItems[k3] != -1) { gameGraphics.spriteClip4(j5, i6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(shopItems[k3]) .getSprite(), EntityHandler.getItemDef(shopItems[k3]) .getPictureMask(), 0, 0, false); gameGraphics.drawString(String.valueOf(shopItemCount[k3]), j5 + 1, i6 + 10, 1, 65280); gameGraphics.drawBoxTextRight( String.valueOf(inventoryCount(shopItems[k3])), j5 + 47, i6 + 10, 1, 65535); } k3++; } } gameGraphics.drawLineX(byte0 + 5, byte1 + 222, 398, 0); if (selectedShopItemIndex == -1) { gameGraphics.drawText("Select an object to buy or sell", byte0 + 204, byte1 + 214, 3, 0xffff00); return; } int i5 = shopItems[selectedShopItemIndex]; if (i5 != -1) { if (shopItemCount[selectedShopItemIndex] > 0) { int j6 = shopItemsBuyPrice[selectedShopItemIndex];// (shopItemBuyPriceModifier // * // EntityHandler.getItemDef( // i5).getBasePrice()) / 100; gameGraphics.drawString("Buy a new " + EntityHandler.getItemDef(i5).getName() + " for " + j6 + "gp", byte0 + 2, byte1 + 214, 1, 0xffff00); int k1 = 0xffffff; if (super.mouseX > byte0 + 298 && super.mouseY >= byte1 + 204 && super.mouseX < byte0 + 408 && super.mouseY <= byte1 + 215) k1 = 0xff0000; gameGraphics.drawBoxTextRight("Click here to buy", byte0 + 405, byte1 + 214, 3, k1); } else { gameGraphics.drawText( "This item is not currently available to buy", byte0 + 204, byte1 + 214, 3, 0xffff00); } if (inventoryCount(i5) > 0) { int k6 = shopItemsSellPrice[selectedShopItemIndex];// (shopItemSellPriceModifier // * // EntityHandler.getItemDef( // i5).getBasePrice()) / 100; gameGraphics.drawBoxTextRight("Sell your " + EntityHandler.getItemDef(i5).getName() + " for " + k6 + "gp", byte0 + 405, byte1 + 239, 1, 0xffff00); int l1 = 0xffffff; if (super.mouseX > byte0 + 2 && super.mouseY >= byte1 + 229 && super.mouseX < byte0 + 112 && super.mouseY <= byte1 + 240) l1 = 0xff0000; gameGraphics.drawString("Click here to sell", byte0 + 2, byte1 + 239, 3, l1); return; } gameGraphics.drawText("You do not have any of this item to sell", byte0 + 204, byte1 + 239, 3, 0xffff00); } } private final void drawGameMenu() { gameMenu = new Menu(gameGraphics, 10); messagesHandleType2 = gameMenu.method159(5, windowHeight - 85, windowWidth - 10, 56, 1, 20, true); chatHandle = gameMenu.method160(7, windowHeight - 10, windowWidth - 14, 14, 1, 80, false, true); messagesHandleType5 = gameMenu.method159(5, windowHeight - 65, windowWidth - 10, 56, 1, 20, true); messagesHandleType6 = gameMenu.method159(5, windowHeight - 65, windowWidth - 10, 56, 1, 20, true); gameMenu.setFocus(chatHandle); } protected final byte[] load(String filename) { CacheManager.load(filename); return super.load(Config.CONF_DIR + File.separator + filename); } /** * Draws our options menu (client size etc) * * @param flag */ private final void drawOurOptionsMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 232; int j = 36; int c = 360; gameGraphics.drawBoxAlpha(i, 36, c, 176, GameImage.convertRGBToLong(181, 181, 181), 160); /** * Draws the gray box behind the icon */ gameGraphics.drawBox(i, 3, 31, 32, GameImage.convertRGBToLong(0, 0, 131)); int temp = 10; gameGraphics.drawBox(i, 26, 274, temp, GameImage.convertRGBToLong(0, 0, 131)); gameGraphics.drawBox(i, 26 + temp, 274, 1, GameImage.convertRGBToLong(0, 0, 0)); gameGraphics.drawString("screen size", i + 147, 26 + temp, 4, 0xffffff); int k = i + 3; int i1 = j + 15; i1 += 15; if (Resolutions.fs) gameGraphics.drawString( " Fullscreen @gre@On", k, i1, 1, 0xffffff); else gameGraphics.drawString( " Fullscreen @red@Off", k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" Screen size @gre@" + reso.getResolution(), k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" Refresh rate @gre@" + reso.getRefreshRate(), k, i1, 1, 0xffffff); i1 += 30; gameGraphics.drawString(" Window size will change after you", k, i1, 1, 0xffffff); i1 += 15; gameGraphics .drawString(" restart the client.", k, i1, 1, 0xffffff); i1 += 30; gameGraphics.drawString(" Going to fullsreen and back does", k, i1, 1, 0xffffff); i1 += 15; gameGraphics.drawString(" not require a client restart.", k, i1, 1, 0xffffff); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 265) { int l1 = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; char c1 = '\304'; int l = l1 + 3; int j1 = byte0 + 30; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { if (gameFrame == null) { mudclient .drawPopup("You cannot switch to fullscreen from the webclient, sorry!"); return; } if (Resolutions.fs) { gameFrame.makeRegularScreen(); } else { gameFrame.makeFullScreen(); } } j1 += 15; // amera error if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { reso.findNextResolution(); Config.storeConfig( "width", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getWidth()); Config.storeConfig( "height", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getHeight()); Config.storeConfig( "refreshRate", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getRefreshRate()); Config.storeConfig( "bitDepth", "" + Display.displaymodes.get( Resolutions.resolutionSetting) .getBitDepth()); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; boolean flag1 = false; j1 += 35; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { } j1 += 15; j1 += 20; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) mouseButtonClick = 0; } } private final void drawOptionsMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; int j = 36; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 6); char c = '\304'; gameGraphics.drawBoxAlpha(i, 36, c, 65, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 101, c, 65, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 166, c, 95, GameImage.convertRGBToLong(181, 181, 181), 160); gameGraphics.drawBoxAlpha(i, 261, c, 52, GameImage.convertRGBToLong(181, 181, 181), 160); int k = i + 3; int i1 = j + 15; gameGraphics.drawString("Game options - click to toggle", k, i1, 1, 0); i1 += 15; if (configAutoCameraAngle) gameGraphics.drawString("Camera angle mode - @gre@Auto", k, i1, 1, 0xffffff); else gameGraphics.drawString("Camera angle mode - @red@Manual", k, i1, 1, 0xffffff); i1 += 15; if (configMouseButtons) gameGraphics.drawString("Mouse buttons - @red@One", k, i1, 1, 0xffffff); else gameGraphics.drawString("Mouse buttons - @gre@Two", k, i1, 1, 0xffffff); i1 += 15; if (configSoundEffects) gameGraphics.drawString("Sound effects - @red@off", k, i1, 1, 0xffffff); else gameGraphics.drawString("Sound effects - @gre@on", k, i1, 1, 0xffffff); i1 += 15; gameGraphics .drawString("Client assists - click to toggle", k, i1, 1, 0); i1 += 15; if (showRoof) gameGraphics .drawString("Hide Roofs - @red@off", k, i1, 1, 0xffffff); else gameGraphics.drawString("Hide Roofs - @gre@on", k, i1, 1, 0xffffff); i1 += 15; if (autoScreenshot) gameGraphics.drawString("Auto Screenshots - @gre@on", k, i1, 1, 0xffffff); else gameGraphics.drawString("Auto Screenshots - @red@off", k, i1, 1, 0xffffff); i1 += 15; if (combatWindow) gameGraphics.drawString("Fightmode Selector - @gre@on", k, i1, 1, 0xffffff); else gameGraphics.drawString("Fightmode Selector - @red@off", k, i1, 1, 0xffffff); i1 += 15; if (fog) gameGraphics.drawString("Fog of War - @gre@on", k, i1, 1, 0xffffff); else gameGraphics .drawString("Fog of War - @red@off", k, i1, 1, 0xffffff); i1 += 15; i1 += 5; gameGraphics.drawString("Privacy settings. Will be applied to", i + 3, i1, 1, 0); i1 += 15; gameGraphics.drawString("all people not on your friends list", i + 3, i1, 1, 0); i1 += 15; if (super.blockChatMessages == 0) gameGraphics.drawString("Block chat messages: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block chat messages: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockPrivateMessages == 0) gameGraphics.drawString("Block private messages: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block private messages: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockTradeRequests == 0) gameGraphics.drawString("Block trade requests: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block trade requests: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; if (super.blockDuelRequests == 0) gameGraphics.drawString("Block duel requests: @red@<off>", i + 3, i1, 1, 0xffffff); else gameGraphics.drawString("Block duel requests: @gre@<on>", i + 3, i1, 1, 0xffffff); i1 += 15; i1 += 5; gameGraphics.drawString("Always logout when you finish", k, i1, 1, 0); i1 += 15; int k1 = 0xffffff; if (super.mouseX > k && super.mouseX < k + c && super.mouseY > i1 - 12 && super.mouseY < i1 + 4) k1 = 0xffff00; gameGraphics.drawString("Click here to logout", i + 3, i1, 1, k1); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); j = super.mouseY - 36; if (i >= 0 && j >= 0 && i < 196 && j < 265) { int l1 = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; byte byte0 = 36; char c1 = '\304'; int l = l1 + 3; int j1 = byte0 + 30; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configAutoCameraAngle = !configAutoCameraAngle; super.streamClass.createPacket(157); super.streamClass.addByte(0); super.streamClass.addByte(configAutoCameraAngle ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; // amera error if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configMouseButtons = !configMouseButtons; super.streamClass.createPacket(157); super.streamClass.addByte(2); super.streamClass.addByte(configMouseButtons ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { configSoundEffects = !configSoundEffects; super.streamClass.createPacket(157); super.streamClass.addByte(3); super.streamClass.addByte(configSoundEffects ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { showRoof = !showRoof; super.streamClass.createPacket(157); super.streamClass.addByte(4); super.streamClass.addByte(showRoof ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { autoScreenshot = !autoScreenshot; super.streamClass.createPacket(157); super.streamClass.addByte(5); super.streamClass.addByte(autoScreenshot ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { combatWindow = !combatWindow; super.streamClass.createPacket(157); super.streamClass.addByte(6); super.streamClass.addByte(combatWindow ? 1 : 0); super.streamClass.formatPacket(); } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { fog = !fog; } j1 += 15; boolean flag1 = false; j1 += 35; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockChatMessages = 1 - super.blockChatMessages; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockPrivateMessages = 1 - super.blockPrivateMessages; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockTradeRequests = 1 - super.blockTradeRequests; flag1 = true; } j1 += 15; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) { super.blockDuelRequests = 1 - super.blockDuelRequests; flag1 = true; } j1 += 15; if (flag1) sendUpdatedPrivacyInfo(super.blockChatMessages, super.blockPrivateMessages, super.blockTradeRequests, super.blockDuelRequests); j1 += 20; if (super.mouseX > l && super.mouseX < l + c1 && super.mouseY > j1 - 12 && super.mouseY < j1 + 4 && mouseButtonClick == 1) logout(); mouseButtonClick = 0; } } private final void processGame() { try { if (super.keyDownDown) { currentChat++; if (currentChat >= messages.size()) { currentChat = messages.size() - 1; super.keyDownDown = false; return; } gameMenu.updateText(chatHandle, messages.get(currentChat)); super.keyDownDown = false; } if (super.keyUpDown) { currentChat--; if (currentChat < 0) { currentChat = 0; super.keyUpDown = false; return; } gameMenu.updateText(chatHandle, messages.get(currentChat)); super.keyUpDown = false; } } catch (Exception e) { e.printStackTrace(); } if (systemUpdate > 1) { systemUpdate--; } sendPingPacketReadPacketData(); if (logoutTimeout > 0) { logoutTimeout--; } if (ourPlayer.currentSprite == 8 || ourPlayer.currentSprite == 9) { lastWalkTimeout = 500; } if (lastWalkTimeout > 0) { lastWalkTimeout--; } if (showCharacterLookScreen) { drawCharacterLookScreen(); return; } if (showDrawPointsScreen) { drawPointsScreen(); return; } for (int i = 0; i < playerCount; i++) { Mob mob = playerArray[i]; int k = (mob.waypointCurrent + 1) % 10; if (mob.waypointEndSprite != k) { int i1 = -1; int l2 = mob.waypointEndSprite; int j4; if (l2 < k) j4 = k - l2; else j4 = (10 + k) - l2; int j5 = 4; if (j4 > 2) j5 = (j4 - 1) * 4; if (mob.waypointsX[l2] - mob.currentX > magicLoc * 3 || mob.waypointsY[l2] - mob.currentY > magicLoc * 3 || mob.waypointsX[l2] - mob.currentX < -magicLoc * 3 || mob.waypointsY[l2] - mob.currentY < -magicLoc * 3 || j4 > 8) { mob.currentX = mob.waypointsX[l2]; mob.currentY = mob.waypointsY[l2]; } else { if (mob.currentX < mob.waypointsX[l2]) { mob.currentX += j5; mob.stepCount++; i1 = 2; } else if (mob.currentX > mob.waypointsX[l2]) { mob.currentX -= j5; mob.stepCount++; i1 = 6; } if (mob.currentX - mob.waypointsX[l2] < j5 && mob.currentX - mob.waypointsX[l2] > -j5) mob.currentX = mob.waypointsX[l2]; if (mob.currentY < mob.waypointsY[l2]) { mob.currentY += j5; mob.stepCount++; if (i1 == -1) i1 = 4; else if (i1 == 2) i1 = 3; else i1 = 5; } else if (mob.currentY > mob.waypointsY[l2]) { mob.currentY -= j5; mob.stepCount++; if (i1 == -1) i1 = 0; else if (i1 == 2) i1 = 1; else i1 = 7; } if (mob.currentY - mob.waypointsY[l2] < j5 && mob.currentY - mob.waypointsY[l2] > -j5) mob.currentY = mob.waypointsY[l2]; } if (i1 != -1) mob.currentSprite = i1; if (mob.currentX == mob.waypointsX[l2] && mob.currentY == mob.waypointsY[l2]) mob.waypointEndSprite = (l2 + 1) % 10; } else { mob.currentSprite = mob.nextSprite; } if (mob.lastMessageTimeout > 0) mob.lastMessageTimeout--; if (mob.anInt163 > 0) mob.anInt163--; if (mob.combatTimer > 0) mob.combatTimer--; if (playerAliveTimeout > 0) { playerAliveTimeout--; if (playerAliveTimeout == 0) displayMessage( "You have been granted another life. Be more careful this time!", 3, 0); if (playerAliveTimeout == 0) displayMessage( "You retain your skills. Your objects land where you died", 3, 0); } } for (int j = 0; j < npcCount; j++) { Mob mob_1 = npcArray[j]; if (mob_1 == null) { System.out.println("MOB == NULL, npcCount: " + npcCount + ", j: " + j); System.exit(1); } int j1 = (mob_1.waypointCurrent + 1) % 10; if (mob_1.waypointEndSprite != j1) { int i3 = -1; int k4 = mob_1.waypointEndSprite; int k5; if (k4 < j1) k5 = j1 - k4; else k5 = (10 + j1) - k4; int l5 = 4; if (k5 > 2) l5 = (k5 - 1) * 4; if (mob_1.waypointsX[k4] - mob_1.currentX > magicLoc * 3 || mob_1.waypointsY[k4] - mob_1.currentY > magicLoc * 3 || mob_1.waypointsX[k4] - mob_1.currentX < -magicLoc * 3 || mob_1.waypointsY[k4] - mob_1.currentY < -magicLoc * 3 || k5 > 8) { mob_1.currentX = mob_1.waypointsX[k4]; mob_1.currentY = mob_1.waypointsY[k4]; } else { if (mob_1.currentX < mob_1.waypointsX[k4]) { mob_1.currentX += l5; mob_1.stepCount++; i3 = 2; } else if (mob_1.currentX > mob_1.waypointsX[k4]) { mob_1.currentX -= l5; mob_1.stepCount++; i3 = 6; } if (mob_1.currentX - mob_1.waypointsX[k4] < l5 && mob_1.currentX - mob_1.waypointsX[k4] > -l5) mob_1.currentX = mob_1.waypointsX[k4]; if (mob_1.currentY < mob_1.waypointsY[k4]) { mob_1.currentY += l5; mob_1.stepCount++; if (i3 == -1) i3 = 4; else if (i3 == 2) i3 = 3; else i3 = 5; } else if (mob_1.currentY > mob_1.waypointsY[k4]) { mob_1.currentY -= l5; mob_1.stepCount++; if (i3 == -1) i3 = 0; else if (i3 == 2) i3 = 1; else i3 = 7; } if (mob_1.currentY - mob_1.waypointsY[k4] < l5 && mob_1.currentY - mob_1.waypointsY[k4] > -l5) mob_1.currentY = mob_1.waypointsY[k4]; } if (i3 != -1) mob_1.currentSprite = i3; if (mob_1.currentX == mob_1.waypointsX[k4] && mob_1.currentY == mob_1.waypointsY[k4]) mob_1.waypointEndSprite = (k4 + 1) % 10; } else { mob_1.currentSprite = mob_1.nextSprite; if (mob_1.type == 43) mob_1.stepCount++; } if (mob_1.lastMessageTimeout > 0) mob_1.lastMessageTimeout--; if (mob_1.anInt163 > 0) mob_1.anInt163--; if (mob_1.combatTimer > 0) mob_1.combatTimer--; } if (mouseOverMenu != 2) { if (GameImage.anInt346 > 0) anInt658++; if (GameImage.anInt347 > 0) anInt658 = 0; GameImage.anInt346 = 0; GameImage.anInt347 = 0; } for (int l = 0; l < playerCount; l++) { Mob mob_2 = playerArray[l]; if (mob_2.anInt176 > 0) mob_2.anInt176--; } if (cameraAutoAngleDebug) { if (lastAutoCameraRotatePlayerX - ourPlayer.currentX < -500 || lastAutoCameraRotatePlayerX - ourPlayer.currentX > 500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY < -500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY > 500) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } } else { if (lastAutoCameraRotatePlayerX - ourPlayer.currentX < -500 || lastAutoCameraRotatePlayerX - ourPlayer.currentX > 500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY < -500 || lastAutoCameraRotatePlayerY - ourPlayer.currentY > 500) { lastAutoCameraRotatePlayerX = ourPlayer.currentX; lastAutoCameraRotatePlayerY = ourPlayer.currentY; } if (lastAutoCameraRotatePlayerX != ourPlayer.currentX) lastAutoCameraRotatePlayerX += (ourPlayer.currentX - lastAutoCameraRotatePlayerX) / (16 + (cameraHeight - 500) / 15); if (lastAutoCameraRotatePlayerY != ourPlayer.currentY) lastAutoCameraRotatePlayerY += (ourPlayer.currentY - lastAutoCameraRotatePlayerY) / (16 + (cameraHeight - 500) / 15); if (configAutoCameraAngle) { int k1 = cameraAutoAngle * 32; int j3 = k1 - cameraRotation; byte byte0 = 1; if (j3 != 0) { cameraRotationBaseAddition++; if (j3 > 128) { byte0 = -1; j3 = 256 - j3; } else if (j3 > 0) byte0 = 1; else if (j3 < -128) { byte0 = 1; j3 = 256 + j3; } else if (j3 < 0) { byte0 = -1; j3 = -j3; } cameraRotation += ((cameraRotationBaseAddition * j3 + 255) / 256) * byte0; cameraRotation &= 0xff; } else { cameraRotationBaseAddition = 0; } } } if (anInt658 > 20) { aBoolean767 = false; anInt658 = 0; } if (sleeping) { ignoreNext = true; if (super.enteredText.length() > 0) { super.streamClass.createPacket(200); super.streamClass.addString(super.enteredText); if (!aBoolean767) { super.streamClass.addByte(0); aBoolean767 = true; } super.streamClass.formatPacket(); super.inputText = ""; super.enteredText = ""; gameMenu.updateText(chatHandle, ""); sleepMessage = "Please wait..."; } // PLZ CAN I HAS NEW SLEEP EKWAZION? if (super.lastMouseDownButton != 0 && super.mouseX >= ((windowWidth / 2) - 100) && super.mouseX < ((windowWidth / 2) + 100) && super.mouseY > 280 && super.mouseY < 310) { super.streamClass.createPacket(200); super.streamClass.addString("-null-"); if (!aBoolean767) { super.streamClass.addByte(0); aBoolean767 = true; } super.streamClass.formatPacket(); super.inputText = ""; super.enteredText = ""; sleepMessage = " Please wait..."; } super.lastMouseDownButton = 0; return; } if (super.mouseY > windowHeight - 4) { if (super.mouseX > 15 + xAddition && super.mouseX < 96 + xAddition && super.lastMouseDownButton == 1) messagesTab = 0; if (super.mouseX > 110 + xAddition && super.mouseX < 194 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 1; gameMenu.anIntArray187[messagesHandleType2] = 0xf423f; } if (super.mouseX > 215 + xAddition && super.mouseX < 295 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 2; gameMenu.anIntArray187[messagesHandleType5] = 0xf423f; } if (super.mouseX > 315 + xAddition && super.mouseX < 395 + xAddition && super.lastMouseDownButton == 1) { messagesTab = 3; gameMenu.anIntArray187[messagesHandleType6] = 0xf423f; } if (super.mouseX > 417 + xAddition && super.mouseX < 497 + xAddition && super.lastMouseDownButton == 1) { showAbuseWindow = 1; abuseSelectedType = 0; super.inputText = ""; super.enteredText = ""; } super.lastMouseDownButton = 0; super.mouseDownButton = 0; } gameMenu.updateActions(super.mouseX, super.mouseY, super.lastMouseDownButton, super.mouseDownButton); if (messagesTab > 0 && super.mouseX >= 494 && super.mouseY >= windowHeight - 66) super.lastMouseDownButton = 0; if (gameMenu.hasActivated(chatHandle)) { String s = gameMenu.getText(chatHandle); gameMenu.updateText(chatHandle, ""); if (ignoreNext) { ignoreNext = false; return; } if (s.startsWith("::")) { s = s.substring(2); if (!handleCommand(s) && !sleeping && !ignoreNext) { sendChatString(s); if (messages.size() == 0 || !messages.get(messages.size() - 1) .equalsIgnoreCase("::" + s)) { messages.add("::" + s); currentChat = messages.size(); } else if (messages.get(messages.size() - 1) .equalsIgnoreCase("::" + s)) { currentChat = messages.size(); } } } else if (!sleeping && !ignoreNext) { byte[] chatMessage = DataConversions.stringToByteArray(s); sendChatMessage(chatMessage, chatMessage.length); s = DataConversions.byteToString(chatMessage, 0, chatMessage.length).trim(); if (s.toLowerCase().trim().startsWith(";;")) return; if (messages.size() == 0 || !messages.get(messages.size() - 1).equalsIgnoreCase( s)) { messages.add(s); currentChat = messages.size(); } else if (messages.get(messages.size() - 1) .equalsIgnoreCase(s)) { currentChat = messages.size(); } ourPlayer.lastMessageTimeout = 150; ourPlayer.lastMessage = s; displayMessage(ourPlayer.name + ": " + s, 2, ourPlayer.admin); } } if (messagesTab == 0) { for (int l1 = 0; l1 < messagesTimeout.length; l1++) if (messagesTimeout[l1] > 0) messagesTimeout[l1]--; } if (playerAliveTimeout != 0) super.lastMouseDownButton = 0; if (showTradeWindow || showDuelWindow) { if (super.mouseDownButton != 0) mouseDownTime++; else mouseDownTime = 0; if (mouseDownTime > 500) itemIncrement += 100000; else if (mouseDownTime > 350) itemIncrement += 10000; else if (mouseDownTime > 250) itemIncrement += 1000; else if (mouseDownTime > 150) itemIncrement += 100; else if (mouseDownTime > 100) itemIncrement += 10; else if (mouseDownTime > 50) itemIncrement++; else if (mouseDownTime > 20 && (mouseDownTime & 5) == 0) itemIncrement++; } else { mouseDownTime = 0; itemIncrement = 0; } if (super.lastMouseDownButton == 1) mouseButtonClick = 1; else if (super.lastMouseDownButton == 2) mouseButtonClick = 2; gameCamera.updateMouseCoords(super.mouseX, super.mouseY); super.lastMouseDownButton = 0; if (configAutoCameraAngle) { if (cameraRotationBaseAddition == 0 || cameraAutoAngleDebug) { if (super.keyLeftDown) { cameraAutoAngle = cameraAutoAngle + 1 & 7; super.keyLeftDown = false; if (!zoomCamera) { if ((cameraAutoAngle & 1) == 0) cameraAutoAngle = cameraAutoAngle + 1 & 7; for (int i2 = 0; i2 < 8; i2++) { if (enginePlayerVisible(cameraAutoAngle)) break; cameraAutoAngle = cameraAutoAngle + 1 & 7; } } } if (super.keyRightDown) { cameraAutoAngle = cameraAutoAngle + 7 & 7; super.keyRightDown = false; if (!zoomCamera) { if ((cameraAutoAngle & 1) == 0) cameraAutoAngle = cameraAutoAngle + 7 & 7; for (int j2 = 0; j2 < 8; j2++) { if (enginePlayerVisible(cameraAutoAngle)) break; cameraAutoAngle = cameraAutoAngle + 7 & 7; } } } } } else try { if (super.keyLeftDown) cameraRotation = cameraRotation + 2 & 0xff; else if (super.keyRightDown) cameraRotation = cameraRotation - 2 & 0xff; if (super.home) { cameraHeight = 750; cameraVertical = 920; fogVar = 0; } else if (super.pageUp) { if (cameraHeight > 400) cameraHeight -= 6; } else if (super.pageDown) { if (cameraHeight < 3000) cameraHeight += 6; } if (controlDown && fog) { if (minus) fogVar += 20; else if (plus) fogVar -= 20; } } catch (Exception e) { e.printStackTrace(); System.out.println("Camera error: " + e); cameraHeight = 750; cameraVertical = 920; fogVar = 0; } if (actionPictureType > 0) actionPictureType--; else if (actionPictureType < 0) actionPictureType++; gameCamera.method301(17); modelUpdatingTimer++; if (modelUpdatingTimer > 5) { modelUpdatingTimer = 0; modelFireLightningSpellNumber = (modelFireLightningSpellNumber + 1) % 3; modelTorchNumber = (modelTorchNumber + 1) % 4; modelClawSpellNumber = (modelClawSpellNumber + 1) % 5; } for (int k2 = 0; k2 < objectCount; k2++) { int l3 = objectX[k2]; int l4 = objectY[k2]; if (l3 >= 0 && l4 >= 0 && l3 < 96 && l4 < 96 && objectType[k2] == 74) objectModelArray[k2].method188(1, 0, 0); } for (int i4 = 0; i4 < anInt892; i4++) { anIntArray923[i4]++; if (anIntArray923[i4] > 50) { anInt892--; for (int i5 = i4; i5 < anInt892; i5++) { anIntArray944[i5] = anIntArray944[i5 + 1]; anIntArray757[i5] = anIntArray757[i5 + 1]; anIntArray923[i5] = anIntArray923[i5 + 1]; anIntArray782[i5] = anIntArray782[i5 + 1]; } } } }// command == 11 public static HashMap<String, File> ctfsounds = new HashMap<String, File>(); private final void loadSounds() { try { drawDownloadProgress("Unpacking Sound effects", 90, false); sounds = load("sounds1.mem"); audioReader = new AudioReader(); return; } catch (Throwable throwable) { System.out.println("Unable to init sounds:" + throwable); } } private final void drawCombatStyleWindow() { byte byte0 = 7; byte byte1 = 15; char c = '\257'; if (mouseButtonClick != 0) { for (int i = 0; i < 5; i++) { if (i <= 0 || super.mouseX <= byte0 || super.mouseX >= byte0 + c || super.mouseY <= byte1 + i * 20 || super.mouseY >= byte1 + i * 20 + 20) continue; combatStyle = i - 1; mouseButtonClick = 0; super.streamClass.createPacket(42); super.streamClass.addByte(combatStyle); super.streamClass.formatPacket(); break; } } for (int j = 0; j < 5; j++) { if (j == combatStyle + 1) gameGraphics.drawBoxAlpha(byte0, byte1 + j * 20, c, 20, GameImage.convertRGBToLong(255, 0, 0), 128); else gameGraphics.drawBoxAlpha(byte0, byte1 + j * 20, c, 20, GameImage.convertRGBToLong(190, 190, 190), 128); gameGraphics.drawLineX(byte0, byte1 + j * 20, c, 0); gameGraphics.drawLineX(byte0, byte1 + j * 20 + 20, c, 0); } gameGraphics.drawText("Select combat style", byte0 + c / 2, byte1 + 16, 3, 0xffffff); gameGraphics.drawText("Controlled (+1 of each)", byte0 + c / 2, byte1 + 36, 3, 0); gameGraphics.drawText("Aggressive (+3 strength)", byte0 + c / 2, byte1 + 56, 3, 0); gameGraphics.drawText("Accurate (+3 attack)", byte0 + c / 2, byte1 + 76, 3, 0); gameGraphics.drawText("Defensive (+3 defense)", byte0 + c / 2, byte1 + 96, 3, 0); } private final void drawDuelConfirmWindow() { int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 16, 192); int i = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 16, 468, 246, i, 160); gameGraphics.drawText("Please confirm your duel with @yel@" + DataOperations.longToString(duelOpponentNameLong), byte0 + 234, byte1 + 12, 1, 0xffffff); gameGraphics.drawText("Your stake:", byte0 + 117, byte1 + 30, 1, 0xffff00); for (int j = 0; j < duelConfirmMyItemCount; j++) { String s = EntityHandler.getItemDef(duelConfirmMyItems[j]) .getName(); if (EntityHandler.getItemDef(duelConfirmMyItems[j]).isStackable()) s = s + " x " + method74(duelConfirmMyItemsCount[j]); gameGraphics.drawText(s, byte0 + 117, byte1 + 42 + j * 12, 1, 0xffffff); } if (duelConfirmMyItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 117, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("Your opponent's stake:", byte0 + 351, byte1 + 30, 1, 0xffff00); for (int k = 0; k < duelConfirmOpponentItemCount; k++) { String s1 = EntityHandler.getItemDef(duelConfirmOpponentItems[k]) .getName(); if (EntityHandler.getItemDef(duelConfirmOpponentItems[k]) .isStackable()) s1 = s1 + " x " + method74(duelConfirmOpponentItemsCount[k]); gameGraphics.drawText(s1, byte0 + 351, byte1 + 42 + k * 12, 1, 0xffffff); } if (duelConfirmOpponentItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 351, byte1 + 42, 1, 0xffffff); if (duelCantRetreat == 0) gameGraphics.drawText("You can retreat from this duel", byte0 + 234, byte1 + 180, 1, 65280); else gameGraphics.drawText("No retreat is possible!", byte0 + 234, byte1 + 180, 1, 0xff0000); if (duelUseMagic == 0) gameGraphics.drawText("Magic may be used", byte0 + 234, byte1 + 192, 1, 65280); else gameGraphics.drawText("Magic cannot be used", byte0 + 234, byte1 + 192, 1, 0xff0000); if (duelUsePrayer == 0) gameGraphics.drawText("Prayer may be used", byte0 + 234, byte1 + 204, 1, 65280); else gameGraphics.drawText("Prayer cannot be used", byte0 + 234, byte1 + 204, 1, 0xff0000); if (duelUseWeapons == 0) gameGraphics.drawText("Weapons may be used", byte0 + 234, byte1 + 216, 1, 65280); else gameGraphics.drawText("Weapons cannot be used", byte0 + 234, byte1 + 216, 1, 0xff0000); gameGraphics.drawText( "If you are sure click 'Accept' to begin the duel", byte0 + 234, byte1 + 230, 1, 0xffffff); if (!duelWeAccept) { gameGraphics.drawPicture((byte0 + 118) - 35, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture((byte0 + 352) - 35, byte1 + 238, SPRITE_MEDIA_START + 26); } else { gameGraphics.drawText("Waiting for other player...", byte0 + 234, byte1 + 250, 1, 0xffff00); } if (mouseButtonClick == 1) { if (super.mouseX < byte0 || super.mouseY < byte1 || super.mouseX > byte0 + 468 || super.mouseY > byte1 + 262) { showDuelConfirmWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 118) - 35 && super.mouseX <= byte0 + 118 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { duelWeAccept = true; super.streamClass.createPacket(87); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 352) - 35 && super.mouseX <= byte0 + 353 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { showDuelConfirmWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } mouseButtonClick = 0; } } private final void updateBankItems() { bankItemCount = newBankItemCount; for (int i = 0; i < newBankItemCount; i++) { bankItems[i] = newBankItems[i]; bankItemsCount[i] = newBankItemsCount[i]; } for (int j = 0; j < inventoryCount; j++) { if (bankItemCount >= bankItemsMax) break; int k = getInventoryItems()[j]; boolean flag = false; for (int l = 0; l < bankItemCount; l++) { if (bankItems[l] != k) continue; flag = true; break; } if (!flag) { bankItems[bankItemCount] = k; bankItemsCount[bankItemCount] = 0; bankItemCount++; } } } private final void makeDPSMenu() { drawPointsScreen = new Menu(gameGraphics, 100); final Menu dPS = drawPointsScreen; dPS.drawText(256, 10, "Please select your points", 4, true); int i = 140; int j = 34; i += 116; j -= 10; byte byte0 = 54; j += 145; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Str", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); strDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); strUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); dPS.method157(i + byte0, j, 53, 41); dPS.drawText(i + byte0, j - 8, "Atk", 1, true); dPS.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); atkDownButton = dPS.makeButton((i + byte0) - 40, j, 20, 20); dPS.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); atkUpButton = dPS.makeButton(i + byte0 + 40, j, 20, 20); j += 50; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Def", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); defDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); defUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); dPS.method157(i + byte0, j, 53, 41); dPS.drawText(i + byte0, j - 8, "Range", 1, true); dPS.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); rangeDownButton = dPS.makeButton((i + byte0) - 40, j, 20, 20); dPS.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); rangeUpButton = dPS.makeButton(i + byte0 + 40, j, 20, 20); j += 50; dPS.method157(i - byte0, j, 53, 41); dPS.drawText(i - byte0, j - 8, "Magic", 1, true); dPS.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); magDownButton = dPS.makeButton(i - byte0 - 40, j, 20, 20); dPS.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); magUpButton = dPS.makeButton((i - byte0) + 40, j, 20, 20); j += 82; j -= 35; dPS.drawBox(i, j, 200, 30); dPS.drawText(i, j, "Accept", 4, false); dPSAcceptButton = dPS.makeButton(i, j, 200, 30); } private final void makeCharacterDesignMenu() { characterDesignMenu = new Menu(gameGraphics, 100); characterDesignMenu.drawText(256, 10, "Please design Your Character", 4, true); int i = 140; int j = 34; i += 116; j -= 10; characterDesignMenu.drawText(i - 55, j + 110, "Front", 3, true); characterDesignMenu.drawText(i, j + 110, "Side", 3, true); characterDesignMenu.drawText(i + 55, j + 110, "Back", 3, true); byte byte0 = 54; j += 145; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j - 8, "Head", 1, true); characterDesignMenu.drawText(i - byte0, j + 8, "Type", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignHeadButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignHeadButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Hair", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignHairColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignHairColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 50; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j, "Gender", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignGenderButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignGenderButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Top", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignTopColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignTopColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 50; characterDesignMenu.method157(i - byte0, j, 53, 41); characterDesignMenu.drawText(i - byte0, j - 8, "Skin", 1, true); characterDesignMenu.drawText(i - byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158(i - byte0 - 40, j, SPRITE_UTIL_START + 7); characterDesignSkinColourButton1 = characterDesignMenu.makeButton(i - byte0 - 40, j, 20, 20); characterDesignMenu.method158((i - byte0) + 40, j, SPRITE_UTIL_START + 6); characterDesignSkinColourButton2 = characterDesignMenu.makeButton( (i - byte0) + 40, j, 20, 20); characterDesignMenu.method157(i + byte0, j, 53, 41); characterDesignMenu.drawText(i + byte0, j - 8, "Bottom", 1, true); characterDesignMenu.drawText(i + byte0, j + 8, "Colour", 1, true); characterDesignMenu.method158((i + byte0) - 40, j, SPRITE_UTIL_START + 7); characterDesignBottomColourButton1 = characterDesignMenu.makeButton( (i + byte0) - 40, j, 20, 20); characterDesignMenu.method158(i + byte0 + 40, j, SPRITE_UTIL_START + 6); characterDesignBottomColourButton2 = characterDesignMenu.makeButton(i + byte0 + 40, j, 20, 20); j += 82; j -= 35; characterDesignMenu.drawBox(i, j, 200, 30); characterDesignMenu.drawText(i, j, "Accept", 4, false); characterDesignAcceptButton = characterDesignMenu.makeButton(i, j, 200, 30); } private final void drawAbuseWindow2() { if (super.enteredText.length() > 0) { String s = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; if (s.length() > 0) { long l = DataOperations.stringLength12ToLong(s); super.streamClass.createPacket(7); super.streamClass.addTwo4ByteInts(l); super.streamClass.addByte(abuseSelectedType); super.streamClass.formatPacket(); } showAbuseWindow = 0; return; } gameGraphics.drawBox(56 + xAddition, 130 + yAddition, 400, 100, 0); gameGraphics.drawBoxEdge(56 + xAddition, 130 + yAddition, 400, 100, 0xffffff); int i = 160 + yAddition; gameGraphics.drawText( "Now type the name of the offending player, and press enter", 256 + xAddition, i, 1, 0xffff00); i += 18; gameGraphics.drawText("Name: " + super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); i = 222 + yAddition; int j = 0xffffff; if (super.mouseX > 196 + xAddition && super.mouseX < 316 + xAddition && super.mouseY > i - 13 && super.mouseY < i + 2) { j = 0xffff00; if (mouseButtonClick == 1) { mouseButtonClick = 0; showAbuseWindow = 0; } } gameGraphics.drawText("Click here to cancel", 256 + xAddition, i, 1, j); if (mouseButtonClick == 1 && (super.mouseX < 56 + xAddition || super.mouseX > 456 + xAddition || super.mouseY < 130 + yAddition || super.mouseY > 230 + yAddition)) { mouseButtonClick = 0; showAbuseWindow = 0; } } public final void displayMessage(String message, int type, int status) { if (type == 2 || type == 4 || type == 6) { for (; message.length() > 5 && message.charAt(0) == '@' && message.charAt(4) == '@'; message = message.substring(5)) ; } if (message.startsWith("%", 0)) { message = message.substring(1); status = 4; } if (message.startsWith("&", 0)) { message = message.substring(1); status = 33; } // if (command == 131) { message = message.replaceAll("\\#pmd\\#", ""); message = message.replaceAll("\\#mod\\#", ""); message = message.replaceAll("\\#adm\\#", ""); if (type == 2) message = "@yel@" + message; if (type == 3 || type == 4) message = "@whi@" + message; if (type == 6) message = "@cya@" + message; if (status == 1) message = "#pmd#" + message; if (status == 2) message = "#mod#" + message; if (status == 3) message = "#adm#" + message; if (status == 4) { message = "#pmd#" + message; MessageQueue.getQueue(); MessageQueue.addMessage(new Message(message)); gameMenu.addString(messagesHandleType6, message, false); return; } // MessageQueue if (status == 33) { MessageQueue.getQueue(); MessageQueue.addMessage(new Message(message, true)); gameMenu.addString(messagesHandleType6, message, false); return; } if (messagesTab != 0) { if (type == 4 || type == 3) anInt952 = 200; if (type == 2 && messagesTab != 1) anInt953 = 200; if (type == 5 && messagesTab != 2) anInt954 = 200; if (type == 6 && messagesTab != 3) anInt955 = 200; if (type == 3 && messagesTab != 0) messagesTab = 0; if (type == 6 && messagesTab != 3 && messagesTab != 0) messagesTab = 0; } for (int k = messagesArray.length - 1; k > 0; k--) { messagesArray[k] = messagesArray[k - 1]; messagesTimeout[k] = messagesTimeout[k - 1]; } messagesArray[0] = message; /** * Change this to add longer chat msg time */ messagesTimeout[0] = 300; if (type == 2) if (gameMenu.anIntArray187[messagesHandleType2] == gameMenu.menuListTextCount[messagesHandleType2] - 4) gameMenu.addString(messagesHandleType2, message, true); else gameMenu.addString(messagesHandleType2, message, false); if (type == 5) if (gameMenu.anIntArray187[messagesHandleType5] == gameMenu.menuListTextCount[messagesHandleType5] - 4) gameMenu.addString(messagesHandleType5, message, true); else gameMenu.addString(messagesHandleType5, message, false); if (type == 6) { if (gameMenu.anIntArray187[messagesHandleType6] == gameMenu.menuListTextCount[messagesHandleType6] - 4) { gameMenu.addString(messagesHandleType6, message, true); return; } gameMenu.addString(messagesHandleType6, message, false); } } protected final void logoutAndStop() { sendLogoutPacket(); garbageCollect(); if (audioReader != null) { audioReader.stopAudio(); } } private final void method98(int i, String s) { int j = objectX[i]; int k = objectY[i]; int l = j - ourPlayer.currentX / 128; int i1 = k - ourPlayer.currentY / 128; byte byte0 = 7; if (j >= 0 && k >= 0 && j < 96 && k < 96 && l > -byte0 && l < byte0 && i1 > -byte0 && i1 < byte0) { try { gameCamera.removeModel(objectModelArray[i]); int j1 = EntityHandler.storeModel(s); Model model = gameDataModels[j1].method203(); gameCamera.addModel(model); model.method184(true, 48, 48, -50, -10, -50); model.method205(objectModelArray[i]); model.anInt257 = i; objectModelArray[i] = model; } catch (Exception e) { // e.printStackTrace(); } } } protected final void resetVars() { systemUpdate = 0; combatStyle = 0; logoutTimeout = 0; loginScreenNumber = 0; loggedIn = 1; flagged = 0; resetPrivateMessageStrings(); gameGraphics.method211(); gameGraphics.drawImage(aGraphics936, 0, 0); for (int i = 0; i < objectCount; i++) { gameCamera.removeModel(objectModelArray[i]); engineHandle.updateObject(objectX[i], objectY[i], objectType[i], objectID[i]); } for (int j = 0; j < doorCount; j++) { gameCamera.removeModel(doorModel[j]); engineHandle.updateDoor(doorX[j], doorY[j], doorDirection[j], doorType[j]); } objectCount = 0; doorCount = 0; groundItemCount = 0; playerCount = 0; for (int k = 0; k < mobArray.length; k++) mobArray[k] = null; for (int l = 0; l < playerArray.length; l++) playerArray[l] = null; npcCount = 0; for (int i1 = 0; i1 < npcRecordArray.length; i1++) npcRecordArray[i1] = null; for (int j1 = 0; j1 < npcArray.length; j1++) npcArray[j1] = null; for (int k1 = 0; k1 < prayerOn.length; k1++) prayerOn[k1] = false; mouseButtonClick = 0; super.lastMouseDownButton = 0; super.mouseDownButton = 0; showShop = false; showBank = false; super.friendsCount = 0; } private final void drawTradeWindow() { if (mouseButtonClick != 0 && itemIncrement == 0) itemIncrement = 1; if (itemIncrement > 0) { int i = super.mouseX - 22 - xAddition; int j = super.mouseY - 36 - yAddition; if (i >= 0 && j >= 0 && i < 468 && j < 262) { if (i > 216 && j > 30 && i < 462 && j < 235) { int k = (i - 217) / 49 + ((j - 31) / 34) * 5; if (k >= 0 && k < inventoryCount) { boolean flag = false; int l1 = 0; int k2 = getInventoryItems()[k]; for (int k3 = 0; k3 < tradeMyItemCount; k3++) if (tradeMyItems[k3] == k2) if (EntityHandler.getItemDef(k2).isStackable()) { for (int i4 = 0; i4 < itemIncrement; i4++) { if (tradeMyItemsCount[k3] < inventoryItemsCount[k]) tradeMyItemsCount[k3]++; flag = true; } } else { l1++; } if (inventoryCount(k2) <= l1) flag = true; if (!flag && tradeMyItemCount < 12) { tradeMyItems[tradeMyItemCount] = k2; tradeMyItemsCount[tradeMyItemCount] = 1; tradeMyItemCount++; flag = true; } if (flag) { super.streamClass.createPacket(70); super.streamClass.addByte(tradeMyItemCount); for (int j4 = 0; j4 < tradeMyItemCount; j4++) { super.streamClass.add2ByteInt(tradeMyItems[j4]); super.streamClass .add4ByteInt(tradeMyItemsCount[j4]); } super.streamClass.formatPacket(); tradeOtherAccepted = false; tradeWeAccepted = false; } } } if (i > 8 && j > 30 && i < 205 && j < 133) { int l = (i - 9) / 49 + ((j - 31) / 34) * 4; if (l >= 0 && l < tradeMyItemCount) { int j1 = tradeMyItems[l]; for (int i2 = 0; i2 < itemIncrement; i2++) { if (EntityHandler.getItemDef(j1).isStackable() && tradeMyItemsCount[l] > 1) { tradeMyItemsCount[l]--; continue; }// shopItem tradeMyItemCount--; mouseDownTime = 0; for (int l2 = l; l2 < tradeMyItemCount; l2++) { tradeMyItems[l2] = tradeMyItems[l2 + 1]; tradeMyItemsCount[l2] = tradeMyItemsCount[l2 + 1]; } break; } super.streamClass.createPacket(70); super.streamClass.addByte(tradeMyItemCount); for (int i3 = 0; i3 < tradeMyItemCount; i3++) { super.streamClass.add2ByteInt(tradeMyItems[i3]); super.streamClass .add4ByteInt(tradeMyItemsCount[i3]); } super.streamClass.formatPacket(); tradeOtherAccepted = false; tradeWeAccepted = false; } } if (i >= 217 && j >= 238 && i <= 286 && j <= 259) { tradeWeAccepted = true; super.streamClass.createPacket(211); super.streamClass.formatPacket(); } if (i >= 394 && j >= 238 && i < 463 && j < 259) { showTradeWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } } else if (mouseButtonClick != 0) { showTradeWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } mouseButtonClick = 0; itemIncrement = 0; } if (!showTradeWindow) return; int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 12, 192); int i1 = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 468, 18, i1, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 30, 8, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 205, byte1 + 30, 11, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 462, byte1 + 30, 6, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 133, 197, 22, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 258, 197, 20, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 235, 246, 43, i1, 160); int k1 = 0xd0d0d0; gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 30, 197, 103, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 155, 197, 103, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 30, 246, 205, k1, 160); for (int j2 = 0; j2 < 4; j2++) gameGraphics.drawLineX(byte0 + 8, byte1 + 30 + j2 * 34, 197, 0); for (int j3 = 0; j3 < 4; j3++) gameGraphics.drawLineX(byte0 + 8, byte1 + 155 + j3 * 34, 197, 0); for (int l3 = 0; l3 < 7; l3++) gameGraphics.drawLineX(byte0 + 216, byte1 + 30 + l3 * 34, 246, 0); for (int k4 = 0; k4 < 6; k4++) { if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 30, 103, 0); if (k4 < 5) gameGraphics .drawLineY(byte0 + 8 + k4 * 49, byte1 + 155, 103, 0); gameGraphics.drawLineY(byte0 + 216 + k4 * 49, byte1 + 30, 205, 0); } gameGraphics.drawString("Trading with: " + tradeOtherPlayerName, byte0 + 1, byte1 + 10, 1, 0xffffff); gameGraphics.drawString("Your Offer", byte0 + 9, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("Opponent's Offer", byte0 + 9, byte1 + 152, 4, 0xffffff); gameGraphics.drawString("Your Inventory", byte0 + 216, byte1 + 27, 4, 0xffffff); if (!tradeWeAccepted) gameGraphics.drawPicture(byte0 + 217, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture(byte0 + 394, byte1 + 238, SPRITE_MEDIA_START + 26); if (tradeOtherAccepted) { gameGraphics.drawText("Other player", byte0 + 341, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("has accepted", byte0 + 341, byte1 + 256, 1, 0xffffff); } if (tradeWeAccepted) { gameGraphics.drawText("Waiting for", byte0 + 217 + 35, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("other player", byte0 + 217 + 35, byte1 + 256, 1, 0xffffff); } for (int l4 = 0; l4 < inventoryCount; l4++) { int i5 = 217 + byte0 + (l4 % 5) * 49; int k5 = 31 + byte1 + (l4 / 5) * 34; gameGraphics.spriteClip4(i5, k5, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(getInventoryItems()[l4]) .getSprite(), EntityHandler.getItemDef(getInventoryItems()[l4]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(getInventoryItems()[l4]).isStackable()) gameGraphics.drawString( String.valueOf(inventoryItemsCount[l4]), i5 + 1, k5 + 10, 1, 0xffff00); } for (int j5 = 0; j5 < tradeMyItemCount; j5++) { int l5 = 9 + byte0 + (j5 % 4) * 49; int j6 = 31 + byte1 + (j5 / 4) * 34; gameGraphics .spriteClip4(l5, j6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(tradeMyItems[j5]) .getSprite(), EntityHandler.getItemDef(tradeMyItems[j5]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(tradeMyItems[j5]).isStackable()) gameGraphics.drawString(String.valueOf(tradeMyItemsCount[j5]), l5 + 1, j6 + 10, 1, 0xffff00); if (super.mouseX > l5 && super.mouseX < l5 + 48 && super.mouseY > j6 && super.mouseY < j6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(tradeMyItems[j5]).getName() + ": @whi@" + EntityHandler.getItemDef(tradeMyItems[j5]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } for (int i6 = 0; i6 < tradeOtherItemCount; i6++) { int k6 = 9 + byte0 + (i6 % 4) * 49; int l6 = 156 + byte1 + (i6 / 4) * 34; gameGraphics.spriteClip4( k6, l6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(tradeOtherItems[i6]) .getSprite(), EntityHandler.getItemDef(tradeOtherItems[i6]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(tradeOtherItems[i6]).isStackable()) gameGraphics.drawString( String.valueOf(tradeOtherItemsCount[i6]), k6 + 1, l6 + 10, 1, 0xffff00); if (super.mouseX > k6 && super.mouseX < k6 + 48 && super.mouseY > l6 && super.mouseY < l6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(tradeOtherItems[i6]).getName() + ": @whi@" + EntityHandler.getItemDef(tradeOtherItems[i6]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } } private final boolean enginePlayerVisible(int i) { int j = ourPlayer.currentX / 128; int k = ourPlayer.currentY / 128; for (int l = 2; l >= 1; l--) { if (i == 1 && ((engineHandle.walkableValue[j][k - l] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k - l] & 0x80) == 128)) return false; if (i == 3 && ((engineHandle.walkableValue[j][k + l] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k] & 0x80) == 128 || (engineHandle.walkableValue[j - l][k + l] & 0x80) == 128)) return false; if (i == 5 && ((engineHandle.walkableValue[j][k + l] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k + l] & 0x80) == 128)) return false; if (i == 7 && ((engineHandle.walkableValue[j][k - l] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k] & 0x80) == 128 || (engineHandle.walkableValue[j + l][k - l] & 0x80) == 128)) return false; if (i == 0 && (engineHandle.walkableValue[j][k - l] & 0x80) == 128) return false; if (i == 2 && (engineHandle.walkableValue[j - l][k] & 0x80) == 128) return false; if (i == 4 && (engineHandle.walkableValue[j][k + l] & 0x80) == 128) return false; if (i == 6 && (engineHandle.walkableValue[j + l][k] & 0x80) == 128) return false; } return true; } private Mob getLastPlayer(int serverIndex) { for (int i1 = 0; i1 < lastPlayerCount; i1++) { if (lastPlayerArray[i1].serverIndex == serverIndex) { return lastPlayerArray[i1]; } } return null; } private Mob getLastNpc(int serverIndex) { for (int i1 = 0; i1 < lastNpcCount; i1++) { if (lastNpcArray[i1].serverIndex == serverIndex) { return lastNpcArray[i1]; } } return null; } protected final void handleIncomingPacket(int command, int length, byte data[]) { try { if (command == 254) { int bar = DataOperations.getUnsigned4Bytes(data, 1); // System.out.println(bar); if (bar == -1) { smithingscreen.isVisible = false; } else { SmithingScreen.changeItems(smithingscreen, bar); smithingscreen.isVisible = true; } } if (command == 231) { // PS = DataOperations.getUnsigned4Bytes(data, 1); return; } if (command == 233) { questPoints = DataOperations.getUnsignedByte(data[1]); int k = DataOperations.getUnsignedByte(data[2]); int r = 3; newQuestNames = new String[k]; questStage = new byte[k]; for (int i = 0; i < k; i++) { int uid = DataOperations.getUnsignedByte(data[r]); r++; newQuestNames[i] = questName[uid]; questStage[i] = (byte) DataOperations .getUnsignedByte(data[r]); // System.out.println(newQuestNames[i] + " " + // questStage[i]); r++; } }// command == 177 if (command == 110) { int i = 1; serverStartTime = DataOperations.getUnsigned8Bytes(data, i); i += 8; serverLocation = new String(data, i, length - i); return; } if (command == 145) { if (!hasWorldInfo) { return; } loading = true; lastPlayerCount = playerCount; for (int k = 0; k < lastPlayerCount; k++) lastPlayerArray[k] = playerArray[k]; int currentOffset = 8; setSectionX(DataOperations.getIntFromByteArray(data, currentOffset, 11)); currentOffset += 11; setSectionY(DataOperations.getIntFromByteArray(data, currentOffset, 13)); currentOffset += 13; int mobSprite = DataOperations.getIntFromByteArray(data, currentOffset, 4); currentOffset += 4; boolean sectionLoaded = loadSection(getSectionX(), getSectionY()); setSectionX(getSectionX() - getAreaX()); setSectionY(getSectionY() - getAreaY()); int mapEnterX = getSectionX() * magicLoc + 64; int mapEnterY = getSectionY() * magicLoc + 64; if (sectionLoaded) { ourPlayer.waypointCurrent = 0; ourPlayer.waypointEndSprite = 0; ourPlayer.currentX = ourPlayer.waypointsX[0] = mapEnterX; ourPlayer.currentY = ourPlayer.waypointsY[0] = mapEnterY; } playerCount = 0; ourPlayer = makePlayer(serverIndex, mapEnterX, mapEnterY, mobSprite); int newPlayerCount = DataOperations.getIntFromByteArray(data, currentOffset, 8); currentOffset += 8; for (int currentNewPlayer = 0; currentNewPlayer < newPlayerCount; currentNewPlayer++) { Mob lastMob = getLastPlayer(DataOperations .getIntFromByteArray(data, currentOffset, 16)); currentOffset += 16; int nextPlayer = DataOperations.getIntFromByteArray(data, currentOffset, 1); // 1 currentOffset++; if (nextPlayer != 0) { int waypointsLeft = DataOperations.getIntFromByteArray( data, currentOffset, 1); // 2 currentOffset++; if (waypointsLeft == 0) { int currentNextSprite = DataOperations .getIntFromByteArray(data, currentOffset, 3); // 3 currentOffset += 3; int currentWaypoint = lastMob.waypointCurrent; int newWaypointX = lastMob.waypointsX[currentWaypoint]; int newWaypointY = lastMob.waypointsY[currentWaypoint]; if (currentNextSprite == 2 || currentNextSprite == 1 || currentNextSprite == 3) newWaypointX += magicLoc; if (currentNextSprite == 6 || currentNextSprite == 5 || currentNextSprite == 7) newWaypointX -= magicLoc; if (currentNextSprite == 4 || currentNextSprite == 3 || currentNextSprite == 5) newWaypointY += magicLoc; if (currentNextSprite == 0 || currentNextSprite == 1 || currentNextSprite == 7) newWaypointY -= magicLoc; lastMob.nextSprite = currentNextSprite; lastMob.waypointCurrent = currentWaypoint = (currentWaypoint + 1) % 10; lastMob.waypointsX[currentWaypoint] = newWaypointX; lastMob.waypointsY[currentWaypoint] = newWaypointY; } else { int needsNextSprite = DataOperations .getIntFromByteArray(data, currentOffset, 4); currentOffset += 4; if ((needsNextSprite & 0xc) == 12) { continue; } lastMob.nextSprite = needsNextSprite; } } playerArray[playerCount++] = lastMob; } int mobCount = 0; while (currentOffset + 24 < length * 8) { int mobIndex = DataOperations.getIntFromByteArray(data, currentOffset, 16); currentOffset += 16; int areaMobX = DataOperations.getIntFromByteArray(data, currentOffset, 5); currentOffset += 5; if (areaMobX > 15) areaMobX -= 32; int areaMobY = DataOperations.getIntFromByteArray(data, currentOffset, 5); currentOffset += 5; if (areaMobY > 15) areaMobY -= 32; int mobArrayMobID = DataOperations.getIntFromByteArray( data, currentOffset, 4); currentOffset += 4; int addIndex = DataOperations.getIntFromByteArray(data, currentOffset, 1); currentOffset++; int mobX = (getSectionX() + areaMobX) * magicLoc + 64; int mobY = (getSectionY() + areaMobY) * magicLoc + 64; makePlayer(mobIndex, mobX, mobY, mobArrayMobID); if (addIndex == 0) mobArrayIndexes[mobCount++] = mobIndex; } if (mobCount > 0) { super.streamClass.createPacket(83); super.streamClass.add2ByteInt(mobCount); for (int currentMob = 0; currentMob < mobCount; currentMob++) { Mob dummyMob = mobArray[mobArrayIndexes[currentMob]]; super.streamClass.add2ByteInt(dummyMob.serverIndex); super.streamClass.add2ByteInt(dummyMob.mobIntUnknown); } super.streamClass.formatPacket(); mobCount = 0; } loading = false; return; } if (command == 109) { /*if (needsClear) { for (int i = 0; i < groundItemType.length; i++) { groundItemType[i] = -1; groundItemX[i] = -1; groundItemY[i] = -1; } needsClear = false; }*/ for (int l = 1; l < length;) if (DataOperations.getUnsignedByte(data[l]) == 255) { // ??? int newCount = 0; int newSectionX = getSectionX() + data[l + 1] >> 3; int newSectionY = getSectionY() + data[l + 2] >> 3; l += 3; for (int groundItem = 0; groundItem < groundItemCount; groundItem++) { int newX = (groundItemX[groundItem] >> 3) - newSectionX; int newY = (groundItemY[groundItem] >> 3) - newSectionY; if (newX != 0 || newY != 0) { if (groundItem != newCount) { groundItemX[newCount] = groundItemX[groundItem]; groundItemY[newCount] = groundItemY[groundItem]; groundItemType[newCount] = groundItemType[groundItem]; groundItemObjectVar[newCount] = groundItemObjectVar[groundItem]; } newCount++; } } groundItemCount = newCount; } else { int i8 = DataOperations.getUnsigned2Bytes(data, l); l += 2; int k14 = getSectionX() + data[l++]; int j19 = getSectionY() + data[l++]; if ((i8 & 0x8000) == 0) { // New Item groundItemX[groundItemCount] = k14; groundItemY[groundItemCount] = j19; groundItemType[groundItemCount] = i8; groundItemObjectVar[groundItemCount] = 0; for (int k23 = 0; k23 < objectCount; k23++) { if (objectX[k23] != k14 || objectY[k23] != j19) continue; groundItemObjectVar[groundItemCount] = EntityHandler .getObjectDef(objectType[k23]) .getGroundItemVar(); break; } groundItemCount++; } else { // Known Item i8 &= 0x7fff; int l23 = 0; for (int k26 = 0; k26 < groundItemCount; k26++) { if (groundItemX[k26] != k14 || groundItemY[k26] != j19 || groundItemType[k26] != i8) { // Keep // how // it is if (k26 != l23) { groundItemX[l23] = groundItemX[k26]; groundItemY[l23] = groundItemY[k26]; groundItemType[l23] = groundItemType[k26]; groundItemObjectVar[l23] = groundItemObjectVar[k26]; } l23++; } else { // Remove i8 = -123; } } groundItemCount = l23; } } return; } if (command == 27) { for (int i1 = 1; i1 < length;) if (DataOperations.getUnsignedByte(data[i1]) == 255) { int j8 = 0; int l14 = getSectionX() + data[i1 + 1] >> 3; int k19 = getSectionY() + data[i1 + 2] >> 3; i1 += 3; for (int i24 = 0; i24 < objectCount; i24++) { int l26 = (objectX[i24] >> 3) - l14; int k29 = (objectY[i24] >> 3) - k19; if (l26 != 0 || k29 != 0) { if (i24 != j8) { objectModelArray[j8] = objectModelArray[i24]; objectModelArray[j8].anInt257 = j8; objectX[j8] = objectX[i24]; objectY[j8] = objectY[i24]; objectType[j8] = objectType[i24]; objectID[j8] = objectID[i24]; } j8++; } else { gameCamera.removeModel(objectModelArray[i24]); engineHandle.updateObject(objectX[i24], objectY[i24], objectType[i24], objectID[i24]); } } objectCount = j8; } else { int k8 = DataOperations.getUnsigned2Bytes(data, i1); i1 += 2; int i15 = getSectionX() + data[i1++]; int l19 = getSectionY() + data[i1++]; int l29 = data[i1++]; int j24 = 0; for (int i27 = 0; i27 < objectCount; i27++) if (objectX[i27] != i15 || objectY[i27] != l19 || objectID[i27] != l29) { if (i27 != j24) { objectModelArray[j24] = objectModelArray[i27]; objectModelArray[j24].anInt257 = j24; objectX[j24] = objectX[i27]; objectY[j24] = objectY[i27]; objectType[j24] = objectType[i27]; objectID[j24] = objectID[i27]; } j24++; } else { gameCamera.removeModel(objectModelArray[i27]); engineHandle.updateObject(objectX[i27], objectY[i27], objectType[i27], objectID[i27]); } objectCount = j24; if (k8 != 60000) { engineHandle.registerObjectDir(i15, l19, l29); int i34; int j37; if (l29 == 0 || l29 == 4) { i34 = EntityHandler.getObjectDef(k8).getWidth(); j37 = EntityHandler.getObjectDef(k8) .getHeight(); } else { j37 = EntityHandler.getObjectDef(k8).getWidth(); i34 = EntityHandler.getObjectDef(k8) .getHeight(); } int j40 = ((i15 + i15 + i34) * magicLoc) / 2; int i42 = ((l19 + l19 + j37) * magicLoc) / 2; int k43 = EntityHandler.getObjectDef(k8).modelID; Model model_1 = gameDataModels[k43].method203(); gameCamera.addModel(model_1); model_1.anInt257 = objectCount; model_1.method188(0, l29 * 32, 0); model_1.method190(j40, -engineHandle .getAveragedElevation(j40, i42), i42); model_1.method184(true, 48, 48, -50, -10, -50); engineHandle.method412(i15, l19, k8, l29); if (k8 == 74) model_1.method190(0, -480, 0); objectX[objectCount] = i15; objectY[objectCount] = l19; objectType[objectCount] = k8; objectID[objectCount] = l29; objectModelArray[objectCount++] = model_1; } } return; }// command == 48 if (command == 114) { int invOffset = 1; inventoryCount = data[invOffset++] & 0xff; for (int invItem = 0; invItem < inventoryCount; invItem++) { int j15 = DataOperations.getUnsigned2Bytes(data, invOffset); invOffset += 2; getInventoryItems()[invItem] = (j15 & 0x7fff); wearing[invItem] = j15 / 32768; if (EntityHandler.getItemDef(j15 & 0x7fff).isStackable()) { inventoryItemsCount[invItem] = DataOperations.readInt( data, invOffset); invOffset += 4; } else { inventoryItemsCount[invItem] = 1; } } return; } if (command == 53) { int mobCount = DataOperations.getUnsigned2Bytes(data, 1); int mobUpdateOffset = 3; for (int currentMob = 0; currentMob < mobCount; currentMob++) { int mobArrayIndex = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mobArrayIndex < 0 || mobArrayIndex > mobArray.length) { return; } Mob mob = mobArray[mobArrayIndex]; if (mob == null) { return; } byte mobUpdateType = data[mobUpdateOffset++]; if (mobUpdateType == 0) { int i30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.anInt163 = 150; mob.anInt162 = i30; } } else if (mobUpdateType == 1) { // Player talking byte byte7 = data[mobUpdateOffset++]; if (mob != null) { String s2 = DataConversions.byteToString(data, mobUpdateOffset, byte7); mob.lastMessageTimeout = 150; mob.lastMessage = s2; displayMessage(mob.name + ": " + mob.lastMessage, 2, mob.admin); } mobUpdateOffset += byte7; } else if (mobUpdateType == 2) { // Someone getting hit. int j30 = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); int hits = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); int hitsBase = DataOperations .getUnsignedByte(data[mobUpdateOffset++]); if (mob != null) { mob.anInt164 = j30; mob.hitPointsCurrent = hits; mob.hitPointsBase = hitsBase; mob.combatTimer = 200; if (mob == ourPlayer) { playerStatCurrent[3] = hits; playerStatBase[3] = hitsBase; showWelcomeBox = false; // showServerMessageBox = false; } } } else if (mobUpdateType == 3) { // Projectile an npc.. int k30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; int k34 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.attackingCameraInt = k30; mob.attackingNpcIndex = k34; mob.attackingMobIndex = -1; mob.anInt176 = attackingInt40; } } else if (mobUpdateType == 4) { // Projectile another // player. int l30 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; int l34 = DataOperations.getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; if (mob != null) { mob.attackingCameraInt = l30; mob.attackingMobIndex = l34; mob.attackingNpcIndex = -1; mob.anInt176 = attackingInt40; } } else if (mobUpdateType == 5) { // Apperance update if (mob != null) { mob.mobIntUnknown = DataOperations .getUnsigned2Bytes(data, mobUpdateOffset); mobUpdateOffset += 2; mob.nameLong = DataOperations.getUnsigned8Bytes( data, mobUpdateOffset); mobUpdateOffset += 8; mob.name = DataOperations .longToString(mob.nameLong); int i31 = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset++; for (int i35 = 0; i35 < i31; i35++) { mob.animationCount[i35] = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset++; } for (int l37 = i31; l37 < 12; l37++) mob.animationCount[l37] = 0; mob.colourHairType = data[mobUpdateOffset++] & 0xff; mob.colourTopType = data[mobUpdateOffset++] & 0xff; mob.colourBottomType = data[mobUpdateOffset++] & 0xff; mob.colourSkinType = data[mobUpdateOffset++] & 0xff; mob.level = data[mobUpdateOffset++] & 0xff; mob.anInt179 = data[mobUpdateOffset++] & 0xff; mob.admin = data[mobUpdateOffset++] & 0xff; } else { mobUpdateOffset += 14; int j31 = DataOperations .getUnsignedByte(data[mobUpdateOffset]); mobUpdateOffset += j31 + 1; } } else if (mobUpdateType == 6) { // private player talking byte byte8 = data[mobUpdateOffset]; mobUpdateOffset++; if (mob != null) { String s3 = DataConversions.byteToString(data, mobUpdateOffset, byte8); mob.lastMessageTimeout = 150; mob.lastMessage = s3; if (mob == ourPlayer) displayMessage(mob.name + ": " + mob.lastMessage, 5, mob.admin); } mobUpdateOffset += byte8; } } return; } if (command == 129) { combatStyle = DataOperations.getUnsignedByte(data[1]); return; } if (command == 95) { for (int l1 = 1; l1 < length;) if (DataOperations.getUnsignedByte(data[l1]) == 255) { int j9 = 0; int l15 = getSectionX() + data[l1 + 1] >> 3; int j20 = getSectionY() + data[l1 + 2] >> 3; l1 += 3; for (int currentDoor = 0; currentDoor < doorCount; currentDoor++) { int j27 = (doorX[currentDoor] >> 3) - l15; int k31 = (doorY[currentDoor] >> 3) - j20; if (j27 != 0 || k31 != 0) { if (currentDoor != j9) { doorModel[j9] = doorModel[currentDoor]; doorModel[j9].anInt257 = j9 + 10000; doorX[j9] = doorX[currentDoor]; doorY[j9] = doorY[currentDoor]; doorDirection[j9] = doorDirection[currentDoor]; doorType[j9] = doorType[currentDoor]; } j9++; } else { gameCamera.removeModel(doorModel[currentDoor]); engineHandle.updateDoor(doorX[currentDoor], doorY[currentDoor], doorDirection[currentDoor], doorType[currentDoor]); } } doorCount = j9; } else { int k9 = DataOperations.getUnsigned2Bytes(data, l1); l1 += 2; int i16 = getSectionX() + data[l1++]; int k20 = getSectionY() + data[l1++]; byte byte5 = data[l1++]; int k27 = 0; for (int l31 = 0; l31 < doorCount; l31++) if (doorX[l31] != i16 || doorY[l31] != k20 || doorDirection[l31] != byte5) { if (l31 != k27) { doorModel[k27] = doorModel[l31]; doorModel[k27].anInt257 = k27 + 10000; doorX[k27] = doorX[l31]; doorY[k27] = doorY[l31]; doorDirection[k27] = doorDirection[l31]; doorType[k27] = doorType[l31]; } k27++; } else { gameCamera.removeModel(doorModel[l31]); engineHandle.updateDoor(doorX[l31], doorY[l31], doorDirection[l31], doorType[l31]); } doorCount = k27; if (k9 != 60000) { // 65535) { engineHandle.method408(i16, k20, byte5, k9); Model model = makeModel(i16, k20, byte5, k9, doorCount); doorModel[doorCount] = model; doorX[doorCount] = i16; doorY[doorCount] = k20; doorType[doorCount] = k9; doorDirection[doorCount++] = byte5; } } return; } if (command == 77) { lastNpcCount = npcCount; npcCount = 0; for (int lastNpcIndex = 0; lastNpcIndex < lastNpcCount; lastNpcIndex++) lastNpcArray[lastNpcIndex] = npcArray[lastNpcIndex]; int newNpcOffset = 8; int newNpcCount = DataOperations.getIntFromByteArray(data, newNpcOffset, 8); newNpcOffset += 8; for (int newNpcIndex = 0; newNpcIndex < newNpcCount; newNpcIndex++) { Mob newNPC = getLastNpc(DataOperations.getIntFromByteArray( data, newNpcOffset, 16)); newNpcOffset += 16; int npcNeedsUpdate = DataOperations.getIntFromByteArray( data, newNpcOffset, 1); newNpcOffset++; if (npcNeedsUpdate != 0) { int i32 = DataOperations.getIntFromByteArray(data, newNpcOffset, 1); newNpcOffset++; if (i32 == 0) { int nextSprite = DataOperations .getIntFromByteArray(data, newNpcOffset, 3); newNpcOffset += 3; int waypointCurrent = newNPC.waypointCurrent; int waypointX = newNPC.waypointsX[waypointCurrent]; int waypointY = newNPC.waypointsY[waypointCurrent]; if (nextSprite == 2 || nextSprite == 1 || nextSprite == 3) waypointX += magicLoc; if (nextSprite == 6 || nextSprite == 5 || nextSprite == 7) waypointX -= magicLoc; if (nextSprite == 4 || nextSprite == 3 || nextSprite == 5) waypointY += magicLoc; if (nextSprite == 0 || nextSprite == 1 || nextSprite == 7) waypointY -= magicLoc; newNPC.nextSprite = nextSprite; newNPC.waypointCurrent = waypointCurrent = (waypointCurrent + 1) % 10; newNPC.waypointsX[waypointCurrent] = waypointX; newNPC.waypointsY[waypointCurrent] = waypointY; } else { int nextSpriteOffset = DataOperations .getIntFromByteArray(data, newNpcOffset, 4); newNpcOffset += 4; if ((nextSpriteOffset & 0xc) == 12) { continue; } newNPC.nextSprite = nextSpriteOffset; } } npcArray[npcCount++] = newNPC; } while (newNpcOffset + 34 < length * 8) { int serverIndex = DataOperations.getIntFromByteArray(data, newNpcOffset, 16); newNpcOffset += 16; int i28 = DataOperations.getIntFromByteArray(data, newNpcOffset, 5); newNpcOffset += 5; if (i28 > 15) i28 -= 32; int j32 = DataOperations.getIntFromByteArray(data, newNpcOffset, 5); newNpcOffset += 5; if (j32 > 15) j32 -= 32; int nextSprite = DataOperations.getIntFromByteArray(data, newNpcOffset, 4); newNpcOffset += 4; int x = (getSectionX() + i28) * magicLoc + 64; int y = (getSectionY() + j32) * magicLoc + 64; int type = DataOperations.getIntFromByteArray(data, newNpcOffset, 10); newNpcOffset += 10; if (type >= EntityHandler.npcCount()) type = 24; addNPC(serverIndex, x, y, nextSprite, type); } return; } if (command == 190) { int j2 = DataOperations.getUnsigned2Bytes(data, 1); int i10 = 3; for (int k16 = 0; k16 < j2; k16++) { int i21 = DataOperations.getUnsigned2Bytes(data, i10); i10 += 2; Mob mob_2 = npcRecordArray[i21]; int j28 = DataOperations.getUnsignedByte(data[i10]); i10++; if (j28 == 1) { int k32 = DataOperations.getUnsigned2Bytes(data, i10); i10 += 2; byte byte9 = data[i10]; i10++; if (mob_2 != null) { String s4 = DataConversions.byteToString(data, i10, byte9); mob_2.lastMessageTimeout = 150; mob_2.lastMessage = s4; if (k32 == ourPlayer.serverIndex) displayMessage("@yel@" + EntityHandler.getNpcDef(mob_2.type) .getName() + ": " + mob_2.lastMessage, 5, 0); } i10 += byte9; } else if (j28 == 2) { int l32 = DataOperations.getUnsignedByte(data[i10]); i10++; int i36 = DataOperations.getUnsignedByte(data[i10]); i10++; int k38 = DataOperations.getUnsignedByte(data[i10]); i10++; if (mob_2 != null) { mob_2.anInt164 = l32; mob_2.hitPointsCurrent = i36; mob_2.hitPointsBase = k38; mob_2.combatTimer = 200; } } } return; } if (command == 223) { showQuestionMenu = true; int newQuestionMenuCount = DataOperations .getUnsignedByte(data[1]); questionMenuCount = newQuestionMenuCount; int newQuestionMenuOffset = 2; for (int l16 = 0; l16 < newQuestionMenuCount; l16++) { int newQuestionMenuQuestionLength = DataOperations .getUnsignedByte(data[newQuestionMenuOffset]); newQuestionMenuOffset++; questionMenuAnswer[l16] = new String(data, newQuestionMenuOffset, newQuestionMenuQuestionLength); newQuestionMenuOffset += newQuestionMenuQuestionLength; } return; } if (command == 127) { showQuestionMenu = false; return; }// if (command == 109) { if (command == 131) { needsClear = true; notInWilderness = true; hasWorldInfo = true; serverIndex = DataOperations.getUnsigned2Bytes(data, 1); wildX = DataOperations.getUnsigned2Bytes(data, 3); wildY = DataOperations.getUnsigned2Bytes(data, 5); wildYSubtract = DataOperations.getUnsigned2Bytes(data, 7); wildYMultiplier = DataOperations.getUnsigned2Bytes(data, 9); wildY -= wildYSubtract * wildYMultiplier; return; } if (command == 180) { int l2 = 1; for (int k10 = 0; k10 < 18; k10++) { playerStatCurrent[k10] = DataOperations .getUnsignedByte(data[l2++]); } for (int i17 = 0; i17 < 18; i17++) { playerStatBase[i17] = DataOperations .getUnsignedByte(data[l2++]); } for (int k21 = 0; k21 < 18; k21++) { playerStatExperience[k21] = DataOperations .readInt(data, l2); l2 += 4; } expGained = 0; return; }// command == 114 if (command == 177) { int i3 = 1; for (int x = 0; x < 6; x++) { equipmentStatus[x] = DataOperations.getSigned2Bytes(data, i3); i3 += 2; } return; } if (command == 165) { playerAliveTimeout = 250; return; } if (command == 115) { int thingLength = (length - 1) / 4; for (int currentThing = 0; currentThing < thingLength; currentThing++) { int currentItemSectionX = getSectionX() + DataOperations.getSigned2Bytes(data, 1 + currentThing * 4) >> 3; int currentItemSectionY = getSectionY() + DataOperations.getSigned2Bytes(data, 3 + currentThing * 4) >> 3; int currentCount = 0; for (int currentItem = 0; currentItem < groundItemCount; currentItem++) { int currentItemOffsetX = (groundItemX[currentItem] >> 3) - currentItemSectionX; int currentItemOffsetY = (groundItemY[currentItem] >> 3) - currentItemSectionY; if (currentItemOffsetX != 0 || currentItemOffsetY != 0) { if (currentItem != currentCount) { groundItemX[currentCount] = groundItemX[currentItem]; groundItemY[currentCount] = groundItemY[currentItem]; groundItemType[currentCount] = groundItemType[currentItem]; groundItemObjectVar[currentCount] = groundItemObjectVar[currentItem]; } currentCount++; } } groundItemCount = currentCount; currentCount = 0; for (int j33 = 0; j33 < objectCount; j33++) { int k36 = (objectX[j33] >> 3) - currentItemSectionX; int l38 = (objectY[j33] >> 3) - currentItemSectionY; if (k36 != 0 || l38 != 0) { if (j33 != currentCount) { objectModelArray[currentCount] = objectModelArray[j33]; objectModelArray[currentCount].anInt257 = currentCount; objectX[currentCount] = objectX[j33]; objectY[currentCount] = objectY[j33]; objectType[currentCount] = objectType[j33]; objectID[currentCount] = objectID[j33]; } currentCount++; } else { gameCamera.removeModel(objectModelArray[j33]); engineHandle.updateObject(objectX[j33], objectY[j33], objectType[j33], objectID[j33]); } } objectCount = currentCount; currentCount = 0; for (int l36 = 0; l36 < doorCount; l36++) { int i39 = (doorX[l36] >> 3) - currentItemSectionX; int j41 = (doorY[l36] >> 3) - currentItemSectionY; if (i39 != 0 || j41 != 0) { if (l36 != currentCount) { doorModel[currentCount] = doorModel[l36]; doorModel[currentCount].anInt257 = currentCount + 10000; doorX[currentCount] = doorX[l36]; doorY[currentCount] = doorY[l36]; doorDirection[currentCount] = doorDirection[l36]; doorType[currentCount] = doorType[l36]; } currentCount++; } else { gameCamera.removeModel(doorModel[l36]); engineHandle.updateDoor(doorX[l36], doorY[l36], doorDirection[l36], doorType[l36]); } } doorCount = currentCount; } return; } if (command == 230) { showDrawPointsScreen = true; int pkbytes = 1; pkatk = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkdef = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkstr = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkrange = DataOperations.readInt(data, pkbytes); pkbytes += 4; pkmagic = DataOperations.readInt(data, pkbytes); } if (command == 207) { showCharacterLookScreen = true; return; } if (command == 4) { int currentMob = DataOperations.getUnsigned2Bytes(data, 1); if (mobArray[currentMob] != null) // todo: check what that // mobArray is tradeOtherPlayerName = mobArray[currentMob].name; showTradeWindow = true; tradeOtherAccepted = false; tradeWeAccepted = false; tradeMyItemCount = 0; tradeOtherItemCount = 0; return; } if (command == 187) { showTradeWindow = false; showTradeConfirmWindow = false; return; } if (command == 250) { tradeOtherItemCount = data[1] & 0xff; int l3 = 2; for (int i11 = 0; i11 < tradeOtherItemCount; i11++) { tradeOtherItems[i11] = DataOperations.getUnsigned2Bytes( data, l3); l3 += 2; tradeOtherItemsCount[i11] = DataOperations .readInt(data, l3); l3 += 4; } tradeOtherAccepted = false; tradeWeAccepted = false; return; } if (command == 92) { tradeOtherAccepted = data[1] == 1; } if (command == 253) { showShop = true; int i4 = 1; int j11 = data[i4++] & 0xff; byte byte4 = data[i4++]; shopItemSellPriceModifier = data[i4++] & 0xff; shopItemBuyPriceModifier = data[i4++] & 0xff; for (int i22 = 0; i22 < 40; i22++) shopItems[i22] = -1; for (int j25 = 0; j25 < j11; j25++) { shopItems[j25] = DataOperations.getUnsigned2Bytes(data, i4); i4 += 2; shopItemCount[j25] = DataOperations.getUnsigned2Bytes(data, i4); i4 += 2; shopItemsBuyPrice[j25] = DataOperations.getUnsigned4Bytes( data, i4); i4 += 4; shopItemsSellPrice[j25] = DataOperations.getUnsigned4Bytes( data, i4); i4 += 4; } if (byte4 == 1) { int l28 = 39; for (int k33 = 0; k33 < inventoryCount; k33++) { if (l28 < j11) break; boolean flag2 = false; for (int j39 = 0; j39 < 40; j39++) { if (shopItems[j39] != getInventoryItems()[k33]) continue; flag2 = true; break; } if (getInventoryItems()[k33] == 10) flag2 = true; if (!flag2) { // our own item that's not in stock. shopItems[l28] = getInventoryItems()[k33] & 0x7fff; shopItemsSellPrice[l28] = EntityHandler .getItemDef(shopItems[l28]).basePrice - (int) (EntityHandler .getItemDef(shopItems[l28]).basePrice / 2.5); shopItemsSellPrice[l28] = shopItemsSellPrice[l28] - (int) (shopItemsSellPrice[l28] * 0.10); shopItemCount[l28] = 0; l28--; } } } if (selectedShopItemIndex >= 0 && selectedShopItemIndex < 40 && shopItems[selectedShopItemIndex] != selectedShopItemType) { selectedShopItemIndex = -1; selectedShopItemType = -2; } return; } if (command == 220) { showShop = false; return; } if (command == 18) { tradeWeAccepted = data[1] == 1; } if (command == 152) { configAutoCameraAngle = DataOperations.getUnsignedByte(data[1]) == 1; configMouseButtons = DataOperations.getUnsignedByte(data[2]) == 1; configSoundEffects = DataOperations.getUnsignedByte(data[3]) == 1; showRoof = DataOperations.getUnsignedByte(data[4]) == 1; autoScreenshot = DataOperations.getUnsignedByte(data[5]) == 1; combatWindow = DataOperations.getUnsignedByte(data[6]) == 1; return; } if (command == 209) { for (int currentPrayer = 0; currentPrayer < length - 1; currentPrayer++) { boolean prayerOff = data[currentPrayer + 1] == 1; if (!prayerOn[currentPrayer] && prayerOff) playSound("prayeron"); if (prayerOn[currentPrayer] && !prayerOff) playSound("prayeroff"); prayerOn[currentPrayer] = prayerOff; } return; } if (command == 93) { showBank = true; int l4 = 1; newBankItemCount = data[l4++] & 0xff; bankItemsMax = data[l4++] & 0xff; for (int k11 = 0; k11 < newBankItemCount; k11++) { newBankItems[k11] = DataOperations.getUnsigned2Bytes(data, l4); l4 += 2; newBankItemsCount[k11] = DataOperations.getUnsigned4Bytes( data, l4); l4 += 4; } updateBankItems(); return; } if (command == 171) { showBank = false; return; } if (command == 211) { int idx = data[1] & 0xFF; int oldExp = playerStatExperience[idx]; playerStatExperience[idx] = DataOperations.readInt(data, 2); if (playerStatExperience[idx] > oldExp) { expGained += (playerStatExperience[idx] - oldExp); } return; } if (command == 229) { int j5 = DataOperations.getUnsigned2Bytes(data, 1); if (mobArray[j5] != null) { duelOpponentName = mobArray[j5].name; } showDuelWindow = true; duelMyItemCount = 0; duelOpponentItemCount = 0; duelOpponentAccepted = false; duelMyAccepted = false; duelNoRetreating = false; duelNoMagic = false; duelNoPrayer = false; duelNoWeapons = false; return; } if (command == 160) { showDuelWindow = false; showDuelConfirmWindow = false; return; } if (command == 251) { showTradeConfirmWindow = true; tradeConfirmAccepted = false; showTradeWindow = false; int k5 = 1; tradeConfirmOtherNameLong = DataOperations.getUnsigned8Bytes( data, k5); k5 += 8; tradeConfirmOtherItemCount = data[k5++] & 0xff; for (int l11 = 0; l11 < tradeConfirmOtherItemCount; l11++) { tradeConfirmOtherItems[l11] = DataOperations .getUnsigned2Bytes(data, k5); k5 += 2; tradeConfirmOtherItemsCount[l11] = DataOperations.readInt( data, k5); k5 += 4; } tradeConfirmItemCount = data[k5++] & 0xff; for (int k17 = 0; k17 < tradeConfirmItemCount; k17++) { tradeConfirmItems[k17] = DataOperations.getUnsigned2Bytes( data, k5); k5 += 2; tradeConfirmItemsCount[k17] = DataOperations.readInt(data, k5); k5 += 4; } return; } if (command == 63) { duelOpponentItemCount = data[1] & 0xff; int l5 = 2; for (int i12 = 0; i12 < duelOpponentItemCount; i12++) { duelOpponentItems[i12] = DataOperations.getUnsigned2Bytes( data, l5); l5 += 2; duelOpponentItemsCount[i12] = DataOperations.readInt(data, l5); l5 += 4; } duelOpponentAccepted = false; duelMyAccepted = false; return; } if (command == 198) { duelNoRetreating = data[1] == 1; duelNoMagic = data[2] == 1; duelNoPrayer = data[3] == 1; duelNoWeapons = data[4] == 1; duelOpponentAccepted = false; duelMyAccepted = false; return; } if (command == 139) { int bankDataOffset = 1; int bankSlot = data[bankDataOffset++] & 0xff; int bankItemId = DataOperations.getUnsigned2Bytes(data, bankDataOffset); bankDataOffset += 2; int bankItemCount = DataOperations.getUnsigned4Bytes(data, bankDataOffset); bankDataOffset += 4; if (bankItemCount == 0) { newBankItemCount--; for (int currentBankSlot = bankSlot; currentBankSlot < newBankItemCount; currentBankSlot++) { newBankItems[currentBankSlot] = newBankItems[currentBankSlot + 1]; newBankItemsCount[currentBankSlot] = newBankItemsCount[currentBankSlot + 1]; } } else { newBankItems[bankSlot] = bankItemId; newBankItemsCount[bankSlot] = bankItemCount; if (bankSlot >= newBankItemCount) newBankItemCount = bankSlot + 1; } updateBankItems(); return; } if (command == 228) { int j6 = 1; int k12 = 1; int i18 = data[j6++] & 0xff; int k22 = DataOperations.getUnsigned2Bytes(data, j6); j6 += 2; if (EntityHandler.getItemDef(k22 & 0x7fff).isStackable()) { k12 = DataOperations.readInt(data, j6); j6 += 4; } getInventoryItems()[i18] = k22 & 0x7fff; wearing[i18] = k22 / 32768; inventoryItemsCount[i18] = k12; if (i18 >= inventoryCount) inventoryCount = i18 + 1; return; } if (command == 191) { int k6 = data[1] & 0xff; inventoryCount--; for (int l12 = k6; l12 < inventoryCount; l12++) { getInventoryItems()[l12] = getInventoryItems()[l12 + 1]; inventoryItemsCount[l12] = inventoryItemsCount[l12 + 1]; wearing[l12] = wearing[l12 + 1]; } return; } if (command == 208) { int pointer = 1; int idx = data[pointer++] & 0xff; int oldExp = playerStatExperience[idx]; playerStatCurrent[idx] = DataOperations .getUnsignedByte(data[pointer++]); playerStatBase[idx] = DataOperations .getUnsignedByte(data[pointer++]); playerStatExperience[idx] = DataOperations.readInt(data, pointer); pointer += 4; if (playerStatExperience[idx] > oldExp) { expGained += (playerStatExperience[idx] - oldExp); } return; } if (command == 65) { duelOpponentAccepted = data[1] == 1; } if (command == 197) { duelMyAccepted = data[1] == 1; } if (command == 147) { showDuelConfirmWindow = true; duelWeAccept = false; showDuelWindow = false; int i7 = 1; duelOpponentNameLong = DataOperations.getUnsigned8Bytes(data, i7); i7 += 8; duelConfirmOpponentItemCount = data[i7++] & 0xff; for (int j13 = 0; j13 < duelConfirmOpponentItemCount; j13++) { duelConfirmOpponentItems[j13] = DataOperations .getUnsigned2Bytes(data, i7); i7 += 2; duelConfirmOpponentItemsCount[j13] = DataOperations .readInt(data, i7); i7 += 4; } duelConfirmMyItemCount = data[i7++] & 0xff; for (int j18 = 0; j18 < duelConfirmMyItemCount; j18++) { duelConfirmMyItems[j18] = DataOperations.getUnsigned2Bytes( data, i7); i7 += 2; duelConfirmMyItemsCount[j18] = DataOperations.readInt(data, i7); i7 += 4; } duelCantRetreat = data[i7++] & 0xff; duelUseMagic = data[i7++] & 0xff; duelUsePrayer = data[i7++] & 0xff; duelUseWeapons = data[i7++] & 0xff; return; } if (command == 11) { String s = new String(data, 1, length - 1); playSound(s); return; } if (command == 23) { if (anInt892 < 50) { int j7 = data[1] & 0xff; int k13 = data[2] + getSectionX(); int k18 = data[3] + getSectionY(); anIntArray782[anInt892] = j7; anIntArray923[anInt892] = 0; anIntArray944[anInt892] = k13; anIntArray757[anInt892] = k18; anInt892++; } return; } if (command == 248) { if (!hasReceivedWelcomeBoxDetails) { lastLoggedInDays = DataOperations .getUnsigned2Bytes(data, 1); subscriptionLeftDays = DataOperations.getUnsigned2Bytes( data, 3); lastLoggedInAddress = new String(data, 5, length - 5); showWelcomeBox = true; hasReceivedWelcomeBoxDetails = true; } return; } if (command == 148) { serverMessage = new String(data, 1, length - 1); showServerMessageBox = true; serverMessageBoxTop = false; return; } if (command == 64) { serverMessage = new String(data, 1, length - 1); showServerMessageBox = true; serverMessageBoxTop = true; return; } if (command == 126) { fatigue = DataOperations.getUnsigned2Bytes(data, 1); return; } if (command == 206) { if (!sleeping) { } sleeping = true; gameMenu.updateText(chatHandle, ""); super.inputText = ""; super.enteredText = ""; sleepEquation = DataOperations.getImage(data, 1, length); // sleepMessage = null; return; } if (command == 182) { int offset = 1; questPoints = DataOperations.getUnsigned2Bytes(data, offset); offset += 2; for (int i = 0; i < questName.length; i++) questStage[i] = data[offset + i]; return; } if (command == 224) { sleeping = false; sleepMessage = null; return; } if (command == 225) { sleepMessage = "Incorrect - please try again..."; return; } if (command == 174) { DataOperations.getUnsigned2Bytes(data, 1); return; } if (command == 181) { if (autoScreenshot) { takeScreenshot(false); } return; } if (command == 172) { systemUpdate = DataOperations.getUnsigned2Bytes(data, 1) * 32; return; } // System.out.println("Bad ID: " + command + " Length: " + length); } catch (Exception e) { // e.printStackTrace(); /* * if (handlePacketErrorCount < 3) { * super.streamClass.createPacket(156); * super.streamClass.addString(runtimeexception.toString()); * super.streamClass.formatPacket(); handlePacketErrorCount++; } */ } } private String sleepMessage = ""; protected final void lostConnection() { systemUpdate = 0; if (logoutTimeout != 0) { resetIntVars(); return; } super.lostConnection(); } private final void playSound(String s) { if (audioReader == null) { return; } if (configSoundEffects) { return; } audioReader.loadData(sounds, DataOperations.method358(s + ".pcm", sounds), DataOperations.method359(s + ".pcm", sounds)); } private final boolean sendWalkCommand(int walkSectionX, int walkSectionY, int x1, int y1, int x2, int y2, boolean stepBoolean, boolean coordsEqual) { // todo: needs checking int stepCount = engineHandle.getStepCount(walkSectionX, walkSectionY, x1, y1, x2, y2, sectionXArray, sectionYArray, stepBoolean); if (stepCount == -1) if (coordsEqual) { stepCount = 1; sectionXArray[0] = x1; sectionYArray[0] = y1; } else { return false; } stepCount--; walkSectionX = sectionXArray[stepCount]; walkSectionY = sectionYArray[stepCount]; stepCount--; if (coordsEqual) super.streamClass.createPacket(246); else super.streamClass.createPacket(132); super.streamClass.add2ByteInt(walkSectionX + getAreaX()); super.streamClass.add2ByteInt(walkSectionY + getAreaY()); if (coordsEqual && stepCount == -1 && (walkSectionX + getAreaX()) % 5 == 0) stepCount = 0; for (int currentStep = stepCount; currentStep >= 0 && currentStep > stepCount - 25; currentStep--) { super.streamClass .addByte(sectionXArray[currentStep] - walkSectionX); super.streamClass .addByte(sectionYArray[currentStep] - walkSectionY); } super.streamClass.formatPacket(); actionPictureType = -24; actionPictureX = super.mouseX; // guessing the little red/yellow x that // appears when you click actionPictureY = super.mouseY; return true; } private final boolean sendWalkCommandIgnoreCoordsEqual(int walkSectionX, int walkSectionY, int x1, int y1, int x2, int y2, boolean stepBoolean, boolean coordsEqual) { int stepCount = engineHandle.getStepCount(walkSectionX, walkSectionY, x1, y1, x2, y2, sectionXArray, sectionYArray, stepBoolean); if (stepCount == -1) return false; stepCount--; walkSectionX = sectionXArray[stepCount]; walkSectionY = sectionYArray[stepCount]; stepCount--; if (coordsEqual) super.streamClass.createPacket(246); else super.streamClass.createPacket(132); super.streamClass.add2ByteInt(walkSectionX + getAreaX()); super.streamClass.add2ByteInt(walkSectionY + getAreaY()); if (coordsEqual && stepCount == -1 && (walkSectionX + getAreaX()) % 5 == 0) stepCount = 0; for (int currentStep = stepCount; currentStep >= 0 && currentStep > stepCount - 25; currentStep--) { super.streamClass .addByte(sectionXArray[currentStep] - walkSectionX); super.streamClass .addByte(sectionYArray[currentStep] - walkSectionY); } super.streamClass.formatPacket(); actionPictureType = -24; actionPictureX = super.mouseX; actionPictureY = super.mouseY; return true; } public final Image createImage(int i, int j) { if (GameWindow.gameFrame != null) { return GameWindow.gameFrame.createImage(i, j); } return super.createImage(i, j); } private final void drawTradeConfirmWindow() { int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 16, 192); int i = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 16, 468, 246, i, 160); gameGraphics.drawText("Please confirm your trade with @yel@" + DataOperations.longToString(tradeConfirmOtherNameLong), byte0 + 234, byte1 + 12, 1, 0xffffff); gameGraphics.drawText("You are about to give:", byte0 + 117, byte1 + 30, 1, 0xffff00); for (int j = 0; j < tradeConfirmItemCount; j++) { String s = EntityHandler.getItemDef(tradeConfirmItems[j]).getName(); if (EntityHandler.getItemDef(tradeConfirmItems[j]).isStackable()) s = s + " x " + method74(tradeConfirmItemsCount[j]); gameGraphics.drawText(s, byte0 + 117, byte1 + 42 + j * 12, 1, 0xffffff); } if (tradeConfirmItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 117, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("In return you will receive:", byte0 + 351, byte1 + 30, 1, 0xffff00); for (int k = 0; k < tradeConfirmOtherItemCount; k++) { String s1 = EntityHandler.getItemDef(tradeConfirmOtherItems[k]) .getName(); if (EntityHandler.getItemDef(tradeConfirmOtherItems[k]) .isStackable()) s1 = s1 + " x " + method74(tradeConfirmOtherItemsCount[k]); gameGraphics.drawText(s1, byte0 + 351, byte1 + 42 + k * 12, 1, 0xffffff); } if (tradeConfirmOtherItemCount == 0) gameGraphics.drawText("Nothing!", byte0 + 351, byte1 + 42, 1, 0xffffff); gameGraphics.drawText("Are you sure you want to do this?", byte0 + 234, byte1 + 200, 4, 65535); gameGraphics.drawText( "There is NO WAY to reverse a trade if you change your mind.", byte0 + 234, byte1 + 215, 1, 0xffffff); gameGraphics.drawText("Remember that not all players are trustworthy", byte0 + 234, byte1 + 230, 1, 0xffffff); if (!tradeConfirmAccepted) { gameGraphics.drawPicture((byte0 + 118) - 35, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture((byte0 + 352) - 35, byte1 + 238, SPRITE_MEDIA_START + 26); } else { gameGraphics.drawText("Waiting for other player...", byte0 + 234, byte1 + 250, 1, 0xffff00); } if (mouseButtonClick == 1) { if (super.mouseX < byte0 || super.mouseY < byte1 || super.mouseX > byte0 + 468 || super.mouseY > byte1 + 262) { showTradeConfirmWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 118) - 35 && super.mouseX <= byte0 + 118 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { tradeConfirmAccepted = true; super.streamClass.createPacket(53); // createPacket(73 super.streamClass.formatPacket(); } if (super.mouseX >= (byte0 + 352) - 35 && super.mouseX <= byte0 + 353 + 70 && super.mouseY >= byte1 + 238 && super.mouseY <= byte1 + 238 + 21) { showTradeConfirmWindow = false; super.streamClass.createPacket(216); super.streamClass.formatPacket(); } mouseButtonClick = 0; } } private final void walkToGroundItem(int walkSectionX, int walkSectionY, int x, int y, boolean coordsEqual) { if (sendWalkCommandIgnoreCoordsEqual(walkSectionX, walkSectionY, x, y, x, y, false, coordsEqual)) { return; } else { sendWalkCommand(walkSectionX, walkSectionY, x, y, x, y, true, coordsEqual); return; } } private final Mob addNPC(int serverIndex, int x, int y, int nextSprite, int type) { if (npcRecordArray[serverIndex] == null) { npcRecordArray[serverIndex] = new Mob(); npcRecordArray[serverIndex].serverIndex = serverIndex; } Mob mob = npcRecordArray[serverIndex]; boolean npcAlreadyExists = false; for (int lastNpcIndex = 0; lastNpcIndex < lastNpcCount; lastNpcIndex++) { if (lastNpcArray[lastNpcIndex].serverIndex != serverIndex) continue; npcAlreadyExists = true; break; } if (npcAlreadyExists) { mob.type = type; mob.nextSprite = nextSprite; int waypointCurrent = mob.waypointCurrent; if (x != mob.waypointsX[waypointCurrent] || y != mob.waypointsY[waypointCurrent]) { mob.waypointCurrent = waypointCurrent = (waypointCurrent + 1) % 10; mob.waypointsX[waypointCurrent] = x; mob.waypointsY[waypointCurrent] = y; } } else { mob.serverIndex = serverIndex; mob.waypointEndSprite = 0; mob.waypointCurrent = 0; mob.waypointsX[0] = mob.currentX = x; mob.waypointsY[0] = mob.currentY = y; mob.type = type; mob.nextSprite = mob.currentSprite = nextSprite; mob.stepCount = 0; } npcArray[npcCount++] = mob; return mob; } private final void drawDuelWindow() { if (mouseButtonClick != 0 && itemIncrement == 0) itemIncrement = 1; if (itemIncrement > 0) { int i = super.mouseX - 22 - xAddition; int j = super.mouseY - 36 - yAddition; if (i >= 0 && j >= 0 && i < 468 && j < 262) { if (i > 216 && j > 30 && i < 462 && j < 235) { int k = (i - 217) / 49 + ((j - 31) / 34) * 5; if (k >= 0 && k < inventoryCount) { boolean flag1 = false; int l1 = 0; int k2 = getInventoryItems()[k]; for (int k3 = 0; k3 < duelMyItemCount; k3++) if (duelMyItems[k3] == k2) if (EntityHandler.getItemDef(k2).isStackable()) { for (int i4 = 0; i4 < itemIncrement; i4++) { if (duelMyItemsCount[k3] < inventoryItemsCount[k]) duelMyItemsCount[k3]++; flag1 = true; } } else { l1++; } if (inventoryCount(k2) <= l1) flag1 = true; if (!flag1 && duelMyItemCount < 8) { duelMyItems[duelMyItemCount] = k2; duelMyItemsCount[duelMyItemCount] = 1; duelMyItemCount++; flag1 = true; } if (flag1) { super.streamClass.createPacket(123); super.streamClass.addByte(duelMyItemCount); for (int duelItem = 0; duelItem < duelMyItemCount; duelItem++) { super.streamClass .add2ByteInt(duelMyItems[duelItem]); super.streamClass .add4ByteInt(duelMyItemsCount[duelItem]); } super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } } } if (i > 8 && j > 30 && i < 205 && j < 129) { int l = (i - 9) / 49 + ((j - 31) / 34) * 4; if (l >= 0 && l < duelMyItemCount) { int j1 = duelMyItems[l]; for (int i2 = 0; i2 < itemIncrement; i2++) { if (EntityHandler.getItemDef(j1).isStackable() && duelMyItemsCount[l] > 1) { duelMyItemsCount[l]--; continue; } duelMyItemCount--; mouseDownTime = 0; for (int l2 = l; l2 < duelMyItemCount; l2++) { duelMyItems[l2] = duelMyItems[l2 + 1]; duelMyItemsCount[l2] = duelMyItemsCount[l2 + 1]; } break; } super.streamClass.createPacket(123); super.streamClass.addByte(duelMyItemCount); for (int i3 = 0; i3 < duelMyItemCount; i3++) { super.streamClass.add2ByteInt(duelMyItems[i3]); super.streamClass.add4ByteInt(duelMyItemsCount[i3]); } super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } } boolean flag = false; if (i >= 93 && j >= 221 && i <= 104 && j <= 232) { duelNoRetreating = !duelNoRetreating; flag = true; } if (i >= 93 && j >= 240 && i <= 104 && j <= 251) { duelNoMagic = !duelNoMagic; flag = true; } if (i >= 191 && j >= 221 && i <= 202 && j <= 232) { duelNoPrayer = !duelNoPrayer; flag = true; } if (i >= 191 && j >= 240 && i <= 202 && j <= 251) { duelNoWeapons = !duelNoWeapons; flag = true; } if (flag) { super.streamClass.createPacket(225); super.streamClass.addByte(duelNoRetreating ? 1 : 0); super.streamClass.addByte(duelNoMagic ? 1 : 0); super.streamClass.addByte(duelNoPrayer ? 1 : 0); super.streamClass.addByte(duelNoWeapons ? 1 : 0); super.streamClass.formatPacket(); duelOpponentAccepted = false; duelMyAccepted = false; } if (i >= 217 && j >= 238 && i <= 286 && j <= 259) { duelMyAccepted = true; super.streamClass.createPacket(252); super.streamClass.formatPacket(); } if (i >= 394 && j >= 238 && i < 463 && j < 259) { showDuelWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } } else if (mouseButtonClick != 0) { showDuelWindow = false; super.streamClass.createPacket(35); super.streamClass.formatPacket(); } mouseButtonClick = 0; itemIncrement = 0; } if (!showDuelWindow) return; int byte0 = 22 + xAddition; int byte1 = 36 + yAddition; gameGraphics.drawBox(byte0, byte1, 468, 12, 0xc90b1d); int i1 = 0x989898; gameGraphics.drawBoxAlpha(byte0, byte1 + 12, 468, 18, i1, 160); gameGraphics.drawBoxAlpha(byte0, byte1 + 30, 8, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 205, byte1 + 30, 11, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 462, byte1 + 30, 6, 248, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 99, 197, 24, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 192, 197, 23, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 258, 197, 20, i1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 235, 246, 43, i1, 160); int k1 = 0xd0d0d0; gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 30, 197, 69, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 123, 197, 69, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 8, byte1 + 215, 197, 43, k1, 160); gameGraphics.drawBoxAlpha(byte0 + 216, byte1 + 30, 246, 205, k1, 160); for (int j2 = 0; j2 < 3; j2++) gameGraphics.drawLineX(byte0 + 8, byte1 + 30 + j2 * 34, 197, 0); for (int j3 = 0; j3 < 3; j3++) gameGraphics.drawLineX(byte0 + 8, byte1 + 123 + j3 * 34, 197, 0); for (int l3 = 0; l3 < 7; l3++) gameGraphics.drawLineX(byte0 + 216, byte1 + 30 + l3 * 34, 246, 0); for (int k4 = 0; k4 < 6; k4++) { if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 30, 69, 0); if (k4 < 5) gameGraphics.drawLineY(byte0 + 8 + k4 * 49, byte1 + 123, 69, 0); gameGraphics.drawLineY(byte0 + 216 + k4 * 49, byte1 + 30, 205, 0); } gameGraphics.drawLineX(byte0 + 8, byte1 + 215, 197, 0); gameGraphics.drawLineX(byte0 + 8, byte1 + 257, 197, 0); gameGraphics.drawLineY(byte0 + 8, byte1 + 215, 43, 0); gameGraphics.drawLineY(byte0 + 204, byte1 + 215, 43, 0); gameGraphics.drawString("Preparing to duel with: " + duelOpponentName, byte0 + 1, byte1 + 10, 1, 0xffffff); gameGraphics.drawString("Your Stake", byte0 + 9, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("Opponent's Stake", byte0 + 9, byte1 + 120, 4, 0xffffff); gameGraphics.drawString("Duel Options", byte0 + 9, byte1 + 212, 4, 0xffffff); gameGraphics.drawString("Your Inventory", byte0 + 216, byte1 + 27, 4, 0xffffff); gameGraphics.drawString("No retreating", byte0 + 8 + 1, byte1 + 215 + 16, 3, 0xffff00); gameGraphics.drawString("No magic", byte0 + 8 + 1, byte1 + 215 + 35, 3, 0xffff00); gameGraphics.drawString("No prayer", byte0 + 8 + 102, byte1 + 215 + 16, 3, 0xffff00); gameGraphics.drawString("No weapons", byte0 + 8 + 102, byte1 + 215 + 35, 3, 0xffff00); gameGraphics.drawBoxEdge(byte0 + 93, byte1 + 215 + 6, 11, 11, 0xffff00); if (duelNoRetreating) gameGraphics.drawBox(byte0 + 95, byte1 + 215 + 8, 7, 7, 0xffff00); gameGraphics .drawBoxEdge(byte0 + 93, byte1 + 215 + 25, 11, 11, 0xffff00); if (duelNoMagic) gameGraphics.drawBox(byte0 + 95, byte1 + 215 + 27, 7, 7, 0xffff00); gameGraphics .drawBoxEdge(byte0 + 191, byte1 + 215 + 6, 11, 11, 0xffff00); if (duelNoPrayer) gameGraphics.drawBox(byte0 + 193, byte1 + 215 + 8, 7, 7, 0xffff00); gameGraphics.drawBoxEdge(byte0 + 191, byte1 + 215 + 25, 11, 11, 0xffff00); if (duelNoWeapons) gameGraphics.drawBox(byte0 + 193, byte1 + 215 + 27, 7, 7, 0xffff00); if (!duelMyAccepted) gameGraphics.drawPicture(byte0 + 217, byte1 + 238, SPRITE_MEDIA_START + 25); gameGraphics.drawPicture(byte0 + 394, byte1 + 238, SPRITE_MEDIA_START + 26); if (duelOpponentAccepted) { gameGraphics.drawText("Other player", byte0 + 341, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("has accepted", byte0 + 341, byte1 + 256, 1, 0xffffff); } if (duelMyAccepted) { gameGraphics.drawText("Waiting for", byte0 + 217 + 35, byte1 + 246, 1, 0xffffff); gameGraphics.drawText("other player", byte0 + 217 + 35, byte1 + 256, 1, 0xffffff); } for (int l4 = 0; l4 < inventoryCount; l4++) { int i5 = 217 + byte0 + (l4 % 5) * 49; int k5 = 31 + byte1 + (l4 / 5) * 34; gameGraphics.spriteClip4(i5, k5, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(getInventoryItems()[l4]) .getSprite(), EntityHandler.getItemDef(getInventoryItems()[l4]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(getInventoryItems()[l4]).isStackable()) gameGraphics.drawString( String.valueOf(inventoryItemsCount[l4]), i5 + 1, k5 + 10, 1, 0xffff00); } for (int j5 = 0; j5 < duelMyItemCount; j5++) { int l5 = 9 + byte0 + (j5 % 4) * 49; int j6 = 31 + byte1 + (j5 / 4) * 34; gameGraphics.spriteClip4(l5, j6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(duelMyItems[j5]).getSprite(), EntityHandler.getItemDef(duelMyItems[j5]).getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(duelMyItems[j5]).isStackable()) gameGraphics.drawString(String.valueOf(duelMyItemsCount[j5]), l5 + 1, j6 + 10, 1, 0xffff00); if (super.mouseX > l5 && super.mouseX < l5 + 48 && super.mouseY > j6 && super.mouseY < j6 + 32) gameGraphics.drawString( EntityHandler.getItemDef(duelMyItems[j5]).getName() + ": @whi@" + EntityHandler.getItemDef(duelMyItems[j5]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } for (int i6 = 0; i6 < duelOpponentItemCount; i6++) { int k6 = 9 + byte0 + (i6 % 4) * 49; int l6 = 124 + byte1 + (i6 / 4) * 34; gameGraphics.spriteClip4(k6, l6, 48, 32, SPRITE_ITEM_START + EntityHandler.getItemDef(duelOpponentItems[i6]) .getSprite(), EntityHandler.getItemDef(duelOpponentItems[i6]) .getPictureMask(), 0, 0, false); if (EntityHandler.getItemDef(duelOpponentItems[i6]).isStackable()) gameGraphics.drawString( String.valueOf(duelOpponentItemsCount[i6]), k6 + 1, l6 + 10, 1, 0xffff00); if (super.mouseX > k6 && super.mouseX < k6 + 48 && super.mouseY > l6 && super.mouseY < l6 + 32) gameGraphics .drawString( EntityHandler.getItemDef(duelOpponentItems[i6]) .getName() + ": @whi@" + EntityHandler.getItemDef( duelOpponentItems[i6]) .getDescription(), byte0 + 8, byte1 + 273, 1, 0xffff00); } } private final void drawServerMessageBox() { int c = '\u0190'; int c1 = 'd'; if (serverMessageBoxTop) { c1 = '\u01C2'; c1 = '\u012C'; } gameGraphics.drawBox(256 - c / 2 + xAddition, 167 - c1 / 2 + yAddition, c, c1, 0); gameGraphics.drawBoxEdge(256 - c / 2 + xAddition, 167 - c1 / 2 + yAddition, c, c1, 0xffffff); gameGraphics.drawBoxTextColour(serverMessage, 256 + xAddition, (167 - c1 / 2) + 20 + yAddition, 1, 0xffffff, c - 40); int i = 157 + c1 / 2 + yAddition; int j = 0xffffff; if (super.mouseY > i - 12 && super.mouseY <= i && super.mouseX > 106 + xAddition && super.mouseX < 406 + xAddition) j = 0xff0000; gameGraphics.drawText("Click here to close window", 256 + xAddition, i, 1, j); if (mouseButtonClick == 1) { if (j == 0xff0000) showServerMessageBox = false; if ((super.mouseX < 256 - c / 2 + xAddition || super.mouseX > 256 + c / 2 + xAddition) && (super.mouseY < 167 - c1 / 2 + yAddition || super.mouseY > 167 + c1 / 2 + yAddition)) showServerMessageBox = false; } mouseButtonClick = 0; } private final void makeLoginMenus() { menuWelcome = new Menu(gameGraphics, 50); int i = 40 + yAddition; menuWelcome.drawText(256 + xAddition, 200 + i, "Click on an option", 5, true); menuWelcome.drawBox(156 + xAddition, 240 + i, 120, 35); menuWelcome.drawBox(356 + xAddition, 240 + i, 120, 35); menuWelcome.drawText(156 + xAddition, 240 + i, "New User", 5, false); menuWelcome.drawText(356 + xAddition, 240 + i, "Existing User", 5, false); loginButtonNewUser = menuWelcome.makeButton(156 + xAddition, 240 + i, 120, 35); loginButtonExistingUser = menuWelcome.makeButton(356 + xAddition, 240 + i, 120, 35); menuNewUser = new Menu(gameGraphics, 50); i = 230 + yAddition; if (referId == 0) { menuNewUser.drawText(256 + xAddition, i + 8, "To create an account please go back to the", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "www.3hit.net", 4, true); } else if (referId == 1) { menuNewUser.drawText(256 + xAddition, i + 8, "then click account", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); } else { menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); i += 20; menuNewUser.drawText(256 + xAddition, i + 8, "", 4, true); } i += 30; menuNewUser.drawBox(256 + xAddition, i + 17, 150, 34); menuNewUser.drawText(256 + xAddition, i + 17, "Ok", 5, false); newUserOkButton = menuNewUser.makeButton(256 + xAddition, i + 17, 150, 34); menuLogin = new Menu(gameGraphics, 50); i = 230 + yAddition; loginStatusText = menuLogin.drawText(256 + xAddition, i - 10, "Please enter your username and password", 4, true); i += 28; menuLogin.drawBox(140 + xAddition, i, 200, 40); menuLogin.drawText(140 + xAddition, i - 10, "Username:", 4, false); loginUsernameTextBox = menuLogin.makeTextBox(140 + xAddition, i + 10, 200, 40, 4, 12, false, false); i += 47; menuLogin.drawBox(190 + xAddition, i, 200, 40); menuLogin.drawText(190 + xAddition, i - 10, "Password:", 4, false); loginPasswordTextBox = menuLogin.makeTextBox(190 + xAddition, i + 10, 200, 40, 4, 20, true, false); i -= 55; menuLogin.drawBox(410 + xAddition, i, 120, 25); menuLogin.drawText(410 + xAddition, i, "Play Now", 4, false); loginOkButton = menuLogin.makeButton(410 + xAddition, i, 120, 25); i += 30; menuLogin.drawBox(410 + xAddition, i, 120, 25); menuLogin.drawText(410 + xAddition, i, "Cancel", 4, false); loginCancelButton = menuLogin.makeButton(410 + xAddition, i, 120, 25); i += 30; menuLogin.setFocus(loginUsernameTextBox); } private final void drawGameWindowsMenus() { if (logoutTimeout != 0) drawLoggingOutBox(); else if (showWelcomeBox) drawWelcomeBox(); else if (showServerMessageBox) drawServerMessageBox(); else if (wildernessType == 1) // 0 = not wild, 1 = close to wild, 2 = // wild drawWildernessWarningBox(); else if (showBank && lastWalkTimeout == 0) drawBankBox(); else if (showShop && lastWalkTimeout == 0) drawShopBox(); else if (showTradeConfirmWindow) drawTradeConfirmWindow(); else if (showTradeWindow) drawTradeWindow(); else if (showDuelConfirmWindow) drawDuelConfirmWindow(); else if (showDuelWindow) drawDuelWindow(); else if (showAbuseWindow == 1) drawAbuseWindow1(); else if (showAbuseWindow == 2) drawAbuseWindow2(); else if (inputBoxType != 0) { drawInputBox(); } else { if (showQuestionMenu) drawQuestionMenu(); if ((ourPlayer.currentSprite == 8 || ourPlayer.currentSprite == 9) || combatWindow) drawCombatStyleWindow(); checkMouseOverMenus(); boolean noMenusShown = !showQuestionMenu && !showRightClickMenu; if (noMenusShown) menuLength = 0; if (mouseOverMenu == 0 && noMenusShown) drawInventoryRightClickMenu(); if (mouseOverMenu == 1) drawInventoryMenu(noMenusShown); if (mouseOverMenu == 2) drawMapMenu(noMenusShown); if (mouseOverMenu == 3) drawPlayerInfoMenu(noMenusShown); if (mouseOverMenu == 4) drawMagicWindow(noMenusShown); if (mouseOverMenu == 5) drawFriendsWindow(noMenusShown); if (mouseOverMenu == 6) drawOptionsMenu(noMenusShown); if (mouseOverMenu == 7) drawOurOptionsMenu(noMenusShown); if (!showRightClickMenu && !showQuestionMenu) checkMouseStatus(); if (showRightClickMenu && !showQuestionMenu) drawRightClickMenu(); } mouseButtonClick = 0; } public final void method112(int i, int j, int k, int l, boolean flag) { sendWalkCommand(i, j, k, l, k, l, false, flag); } private final void drawInputBox() { if (mouseButtonClick != 0) { mouseButtonClick = 0; if (inputBoxType == 1 && (super.mouseX < 106 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 406 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (inputBoxType == 2 && (super.mouseX < 6 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 506 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (inputBoxType == 3 && (super.mouseX < 106 + xAddition || super.mouseY < 145 + yAddition || super.mouseX > 406 + xAddition || super.mouseY > 215 + yAddition)) { inputBoxType = 0; return; } if (super.mouseX > 236 + xAddition && super.mouseX < 276 + xAddition && super.mouseY > 193 + yAddition && super.mouseY < 213 + yAddition) { inputBoxType = 0; return; } } int i = 145 + yAddition; if (inputBoxType == 1) { gameGraphics.drawBox(106 + xAddition, i, 300, 70, 0); gameGraphics.drawBoxEdge(106 + xAddition, i, 300, 70, 0xffffff); i += 20; gameGraphics.drawText("Enter name to add to friends list", 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredText.length() > 0) { String s = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; inputBoxType = 0; if (s.length() > 0 && DataOperations.stringLength12ToLong(s) != ourPlayer.nameLong) addToFriendsList(s); } } if (inputBoxType == 2) { gameGraphics.drawBox(6 + xAddition, i, 500, 70, 0); gameGraphics.drawBoxEdge(6 + xAddition, i, 500, 70, 0xffffff); i += 20; gameGraphics .drawText( "Enter message to send to " + DataOperations .longToString(privateMessageTarget), 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputMessage + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredMessage.length() > 0) { String s1 = super.enteredMessage; super.inputMessage = ""; super.enteredMessage = ""; inputBoxType = 0; byte[] message = DataConversions.stringToByteArray(s1); sendPrivateMessage(privateMessageTarget, message, message.length); s1 = DataConversions.byteToString(message, 0, message.length); handleServerMessage("@pri@You tell " + DataOperations.longToString(privateMessageTarget) + ": " + s1); } } if (inputBoxType == 3) { gameGraphics.drawBox(106 + xAddition, i, 300, 70, 0); gameGraphics.drawBoxEdge(106 + xAddition, i, 300, 70, 0xffffff); i += 20; gameGraphics.drawText("Enter name to add to ignore list", 256 + xAddition, i, 4, 0xffffff); i += 20; gameGraphics.drawText(super.inputText + "*", 256 + xAddition, i, 4, 0xffffff); if (super.enteredText.length() > 0) { String s2 = super.enteredText.trim(); super.inputText = ""; super.enteredText = ""; inputBoxType = 0; if (s2.length() > 0 && DataOperations.stringLength12ToLong(s2) != ourPlayer.nameLong) addToIgnoreList(s2); } } int j = 0xffffff; if (super.mouseX > 236 + xAddition && super.mouseX < 276 + xAddition && super.mouseY > 193 + yAddition && super.mouseY < 213 + yAddition) j = 0xffff00; gameGraphics.drawText("Cancel", 256 + xAddition, 208 + yAddition, 1, j); } private final boolean hasRequiredRunes(int i, int j) { if (i == 31 && (method117(197) || method117(615) || method117(682))) { return true; } if (i == 32 && (method117(102) || method117(616) || method117(683))) { return true; } if (i == 33 && (method117(101) || method117(617) || method117(684))) { return true; } if (i == 34 && (method117(103) || method117(618) || method117(685))) { return true; } return inventoryCount(i) >= j; } private final void resetPrivateMessageStrings() { super.inputMessage = ""; super.enteredMessage = ""; } private final boolean method117(int i) { for (int j = 0; j < inventoryCount; j++) if (getInventoryItems()[j] == i && wearing[j] == 1) return true; return false; } private final void setPixelsAndAroundColour(int x, int y, int colour) { gameGraphics.setPixelColour(x, y, colour); gameGraphics.setPixelColour(x - 1, y, colour); gameGraphics.setPixelColour(x + 1, y, colour); gameGraphics.setPixelColour(x, y - 1, colour); gameGraphics.setPixelColour(x, y + 1, colour); } private final void method119() { for (int i = 0; i < mobMessageCount; i++) { int j = gameGraphics.messageFontHeight(1); int l = mobMessagesX[i]; int k1 = mobMessagesY[i]; int j2 = mobMessagesWidth[i]; int i3 = mobMessagesHeight[i]; boolean flag = true; while (flag) { flag = false; for (int i4 = 0; i4 < i; i4++) if (k1 + i3 > mobMessagesY[i4] - j && k1 - j < mobMessagesY[i4] + mobMessagesHeight[i4] && l - j2 < mobMessagesX[i4] + mobMessagesWidth[i4] && l + j2 > mobMessagesX[i4] - mobMessagesWidth[i4] && mobMessagesY[i4] - j - i3 < k1) { k1 = mobMessagesY[i4] - j - i3; flag = true; } } mobMessagesY[i] = k1; gameGraphics.drawBoxTextColour(mobMessages[i], l, k1, 1, 0xffff00, 300); } for (int k = 0; k < anInt699; k++) { int i1 = anIntArray858[k]; int l1 = anIntArray859[k]; int k2 = anIntArray705[k]; int j3 = anIntArray706[k]; int l3 = (39 * k2) / 100; int j4 = (27 * k2) / 100; int k4 = l1 - j4; gameGraphics.spriteClip2(i1 - l3 / 2, k4, l3, j4, SPRITE_MEDIA_START + 9, 85); int l4 = (36 * k2) / 100; int i5 = (24 * k2) / 100; gameGraphics.spriteClip4(i1 - l4 / 2, (k4 + j4 / 2) - i5 / 2, l4, i5, EntityHandler.getItemDef(j3).getSprite() + SPRITE_ITEM_START, EntityHandler.getItemDef(j3) .getPictureMask(), 0, 0, false); } for (int j1 = 0; j1 < anInt718; j1++) { int i2 = anIntArray786[j1]; int l2 = anIntArray787[j1]; int k3 = anIntArray788[j1]; gameGraphics.drawBoxAlpha(i2 - 15, l2 - 3, k3, 5, 65280, 192); gameGraphics.drawBoxAlpha((i2 - 15) + k3, l2 - 3, 30 - k3, 5, 0xff0000, 192); } } private final void drawMapMenu(boolean flag) { int i = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; char c = '\234'; char c2 = '\230'; gameGraphics.drawPicture(i - 49, 3, SPRITE_MEDIA_START + 2); i += 40; gameGraphics.drawBox(i, 36, c, c2, 0); gameGraphics.setDimensions(i, 36, i + c, 36 + c2); int k = 192 + anInt986; int i1 = cameraRotation + anInt985 & 0xff; int k1 = ((ourPlayer.currentX - 6040) * 3 * k) / 2048; int i3 = ((ourPlayer.currentY - 6040) * 3 * k) / 2048; int k4 = Camera.anIntArray384[1024 - i1 * 4 & 0x3ff]; int i5 = Camera.anIntArray384[(1024 - i1 * 4 & 0x3ff) + 1024]; int k5 = i3 * k4 + k1 * i5 >> 18; i3 = i3 * i5 - k1 * k4 >> 18; k1 = k5; gameGraphics.method242((i + c / 2) - k1, 36 + c2 / 2 + i3, SPRITE_MEDIA_START - 1, i1 + 64 & 0xff, k); for (int i7 = 0; i7 < objectCount; i7++) { int l1 = (((objectX[i7] * magicLoc + 64) - ourPlayer.currentX) * 3 * k) / 2048; int j3 = (((objectY[i7] * magicLoc + 64) - ourPlayer.currentY) * 3 * k) / 2048; int l5 = j3 * k4 + l1 * i5 >> 18; j3 = j3 * i5 - l1 * k4 >> 18; l1 = l5; setPixelsAndAroundColour(i + c / 2 + l1, (36 + c2 / 2) - j3, 65535); } for (int j7 = 0; j7 < groundItemCount; j7++) { int i2 = (((groundItemX[j7] * magicLoc + 64) - ourPlayer.currentX) * 3 * k) / 2048; int k3 = (((groundItemY[j7] * magicLoc + 64) - ourPlayer.currentY) * 3 * k) / 2048; int i6 = k3 * k4 + i2 * i5 >> 18; k3 = k3 * i5 - i2 * k4 >> 18; i2 = i6; setPixelsAndAroundColour(i + c / 2 + i2, (36 + c2 / 2) - k3, 0xff0000); } for (int k7 = 0; k7 < npcCount; k7++) { Mob mob = npcArray[k7]; int j2 = ((mob.currentX - ourPlayer.currentX) * 3 * k) / 2048; int l3 = ((mob.currentY - ourPlayer.currentY) * 3 * k) / 2048; int j6 = l3 * k4 + j2 * i5 >> 18; l3 = l3 * i5 - j2 * k4 >> 18; j2 = j6; setPixelsAndAroundColour(i + c / 2 + j2, (36 + c2 / 2) - l3, 0xffff00); } for (int l7 = 0; l7 < playerCount; l7++) { Mob mob_1 = playerArray[l7]; int k2 = ((mob_1.currentX - ourPlayer.currentX) * 3 * k) / 2048; int i4 = ((mob_1.currentY - ourPlayer.currentY) * 3 * k) / 2048; int k6 = i4 * k4 + k2 * i5 >> 18; i4 = i4 * i5 - k2 * k4 >> 18; k2 = k6; int j8 = 0xffffff; for (int k8 = 0; k8 < super.friendsCount; k8++) { if (mob_1.nameLong != super.friendsListLongs[k8] || super.friendsListOnlineStatus[k8] != 99) continue; j8 = 65280; break; } setPixelsAndAroundColour(i + c / 2 + k2, (36 + c2 / 2) - i4, j8); } gameGraphics.method212(i + c / 2, 36 + c2 / 2, 2, 0xffffff, 255); gameGraphics.method242(i + 19, 55, SPRITE_MEDIA_START + 24, cameraRotation + 128 & 0xff, 128); gameGraphics.setDimensions(0, 0, windowWidth, windowHeight + 12); if (!flag) return; i = super.mouseX - (((GameImage) (gameGraphics)).menuDefaultWidth - 199); int i8 = super.mouseY - 36; if (i >= 40 && i8 >= 0 && i < 196 && i8 < 152) { char c1 = '\234'; char c3 = '\230'; int l = 192 + anInt986; int j1 = cameraRotation + anInt985 & 0xff; int j = ((GameImage) (gameGraphics)).menuDefaultWidth - 199; j += 40; int l2 = ((super.mouseX - (j + c1 / 2)) * 16384) / (3 * l); int j4 = ((super.mouseY - (36 + c3 / 2)) * 16384) / (3 * l); int l4 = Camera.anIntArray384[1024 - j1 * 4 & 0x3ff]; int j5 = Camera.anIntArray384[(1024 - j1 * 4 & 0x3ff) + 1024]; int l6 = j4 * l4 + l2 * j5 >> 15; j4 = j4 * j5 - l2 * l4 >> 15; l2 = l6; l2 += ourPlayer.currentX; j4 = ourPlayer.currentY - j4; if (mouseButtonClick == 1) method112(getSectionX(), getSectionY(), l2 / 128, j4 / 128, false); mouseButtonClick = 0; } } public mudclient() { for (int i = 0; i < questStage.length; i++) questStage[i] = (byte) 0; combatWindow = false; threadSleepTime = 10; try { localhost = InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { e.printStackTrace(); localhost = "unknown"; } if (config.getProperty("width") == null) { Config.storeConfig("width", "502"); } if (config.getProperty("height") == null) { Config.storeConfig("height", "382"); } if (config.getProperty("refreshRate") == null) { Config.storeConfig("refreshRate", "" + Resolutions.oldDisplayMode.getRefreshRate()); } if (config.getProperty("bitDepth") == null) { Config.storeConfig("bitDepth", "" + Resolutions.oldDisplayMode.getBitDepth()); } windowWidth = Integer.valueOf(config.getProperty("width")); windowHeight = Integer.valueOf(config.getProperty("height")) - 40; screenDepth = Integer.valueOf(config.getProperty("bitDepth")); screenRefreshRate = Integer.valueOf(config.getProperty("refreshRate")); if (windowWidth < defaultWidth || windowHeight < defaultHeight) { windowWidth = defaultWidth; Config.storeConfig("width", "502"); windowHeight = defaultHeight; Config.storeConfig("height", "382"); } if (windowWidth > 532) { xAddition = (windowWidth - defaultWidth) / 2; yAddition = (windowHeight - defaultHeight) / 2; } else { xAddition = 0; yAddition = 0; } startTime = System.currentTimeMillis(); duelMyItems = new int[8]; duelMyItemsCount = new int[8]; configAutoCameraAngle = true; questionMenuAnswer = new String[10]; lastNpcArray = new Mob[500]; currentUser = ""; currentPass = ""; menuText1 = new String[250]; duelOpponentAccepted = false; duelMyAccepted = false; tradeConfirmItems = new int[14]; tradeConfirmItemsCount = new int[14]; tradeConfirmOtherItems = new int[14]; tradeConfirmOtherItemsCount = new int[14]; serverMessage = ""; duelOpponentName = ""; setInventoryItems(new int[35]); inventoryItemsCount = new int[35]; wearing = new int[35]; mobMessages = new String[50]; showBank = false; doorModel = new Model[500]; mobMessagesX = new int[50]; mobMessagesY = new int[50]; mobMessagesWidth = new int[50]; mobMessagesHeight = new int[50]; npcArray = new Mob[500]; equipmentStatus = new int[6]; prayerOn = new boolean[50]; tradeOtherAccepted = false; tradeWeAccepted = false; mobArray = new Mob[8000]; anIntArray705 = new int[50]; anIntArray706 = new int[50]; lastWildYSubtract = -1; memoryError = false; bankItemsMax = 48; showQuestionMenu = false; magicLoc = 128; cameraAutoAngle = 1; anInt727 = 2; showServerMessageBox = false; hasReceivedWelcomeBoxDetails = false; playerStatCurrent = new int[18]; wildYSubtract = -1; anInt742 = -1; anInt743 = -1; anInt744 = -1; sectionXArray = new int[8000]; sectionYArray = new int[8000]; selectedItem = -1; selectedItemName = ""; duelOpponentItems = new int[8]; duelOpponentItemsCount = new int[8]; anIntArray757 = new int[50]; menuID = new int[250]; showCharacterLookScreen = false; showDrawPointsScreen = false; lastPlayerArray = new Mob[500]; appletMode = true; gameDataModels = new Model[1000]; configMouseButtons = false; duelNoRetreating = false; duelNoMagic = false; duelNoPrayer = false; duelNoWeapons = false; anIntArray782 = new int[50]; duelConfirmOpponentItems = new int[8]; duelConfirmOpponentItemsCount = new int[8]; anIntArray786 = new int[50]; anIntArray787 = new int[50]; anIntArray788 = new int[50]; objectModelArray = new Model[1500]; cameraRotation = 128; showWelcomeBox = false; characterBodyGender = 1; character2Colour = 2; characterHairColour = 2; characterTopColour = 8; characterBottomColour = 14; characterHeadGender = 1; selectedBankItem = -1; selectedBankItemType = -2; menuText2 = new String[250]; aBooleanArray827 = new boolean[1500]; playerStatBase = new int[18]; menuActionType = new int[250]; menuActionVariable = new int[250]; menuActionVariable2 = new int[250]; shopItems = new int[256]; shopItemCount = new int[256]; shopItemsSellPrice = new int[256]; shopItemsBuyPrice = new int[256]; anIntArray858 = new int[50]; anIntArray859 = new int[50]; newBankItems = new int[256]; newBankItemsCount = new int[256]; duelConfirmMyItems = new int[8]; duelConfirmMyItemsCount = new int[8]; mobArrayIndexes = new int[500]; messagesTimeout = new int[5]; objectX = new int[1500]; objectY = new int[1500]; objectType = new int[1500]; objectID = new int[1500]; menuActionX = new int[250]; menuActionY = new int[250]; ourPlayer = new Mob(); serverIndex = -1; anInt882 = 30; showTradeConfirmWindow = false; tradeConfirmAccepted = false; playerArray = new Mob[500]; serverMessageBoxTop = false; cameraHeight = 750; bankItems = new int[256]; bankItemsCount = new int[256]; notInWilderness = false; selectedSpell = -1; anInt911 = 2; tradeOtherItems = new int[14]; tradeOtherItemsCount = new int[14]; menuIndexes = new int[250]; zoomCamera = false; playerStatExperience = new int[18]; cameraAutoAngleDebug = false; npcRecordArray = new Mob[8000]; showDuelWindow = false; anIntArray923 = new int[50]; lastLoadedNull = false; experienceArray = new int[99]; showShop = false; mouseClickXArray = new int[8192]; mouseClickYArray = new int[8192]; showDuelConfirmWindow = false; duelWeAccept = false; doorX = new int[500]; doorY = new int[500]; configSoundEffects = false; showRightClickMenu = false; attackingInt40 = 40; anIntArray944 = new int[50]; doorDirection = new int[500]; doorType = new int[500]; groundItemX = new int[8000]; groundItemY = new int[8000]; groundItemType = new int[8000]; groundItemObjectVar = new int[8000]; selectedShopItemIndex = -1; selectedShopItemType = -2; messagesArray = new String[5]; showTradeWindow = false; aBooleanArray970 = new boolean[500]; tradeMyItems = new int[14]; tradeMyItemsCount = new int[14]; cameraSizeInt = 9; tradeOtherPlayerName = ""; mc = this; } private boolean combatWindow; private int lastLoggedInDays; private int subscriptionLeftDays; private int duelMyItemCount; private int duelMyItems[]; private int duelMyItemsCount[]; private boolean configAutoCameraAngle; private String questionMenuAnswer[]; private int anInt658; private Mob lastNpcArray[]; private int loginButtonNewUser; private int loginButtonExistingUser; private String currentUser; private String currentPass; private int lastWalkTimeout; private String menuText1[]; private boolean duelOpponentAccepted; private boolean duelMyAccepted; private int tradeConfirmItemCount; private int tradeConfirmItems[]; private int tradeConfirmItemsCount[]; private int tradeConfirmOtherItemCount; private int tradeConfirmOtherItems[]; private int tradeConfirmOtherItemsCount[]; static String serverMessage; private String duelOpponentName; private int mouseOverBankPageText; public int playerCount; private int lastPlayerCount; private int fightCount; private int inventoryCount; private int inventoryItems[]; private int inventoryItemsCount[]; private int wearing[]; private int mobMessageCount; String mobMessages[]; private boolean showBank; private Model doorModel[]; private int mobMessagesX[]; private int mobMessagesY[]; private int mobMessagesWidth[]; private int mobMessagesHeight[]; public Mob npcArray[]; private int equipmentStatus[]; private final int characterTopBottomColours[] = { 0xff0000, 0xff8000, 0xffe000, 0xa0e000, 57344, 32768, 41088, 45311, 33023, 12528, 0xe000e0, 0x303030, 0x604000, 0x805000, 0xffffff }; private int loginScreenNumber; private int anInt699; private boolean prayerOn[]; private boolean tradeOtherAccepted; private boolean tradeWeAccepted; private Mob mobArray[]; private int npcCombatModelArray1[] = { 0, 1, 2, 1, 0, 0, 0, 0 }; private int anIntArray705[]; private int anIntArray706[]; public int npcCount; private int lastNpcCount; private int wildX; private int wildY; private int wildYMultiplier; private int lastWildYSubtract; private boolean memoryError; private int bankItemsMax; private int mouseOverMenu; private int walkModel[] = { 0, 1, 2, 1 }; private boolean showQuestionMenu; private int anInt718; public int magicLoc; public int loggedIn; private int cameraAutoAngle; private int cameraRotationBaseAddition; private Menu spellMenu; int spellMenuHandle; int menuMagicPrayersSelected; private int screenRotationX; private int anInt727; private int showAbuseWindow; private int duelCantRetreat; private int duelUseMagic; private int duelUsePrayer; private int duelUseWeapons; static boolean showServerMessageBox; private boolean hasReceivedWelcomeBoxDetails; private String lastLoggedInAddress; private int loginTimer; private int playerStatCurrent[]; private int areaX; private int areaY; private int wildYSubtract; private int anInt742; private int anInt743; private int anInt744; public int sectionXArray[]; public int sectionYArray[]; private int selectedItem; String selectedItemName; private int menuX; private int menuY; private int menuWidth; private int menuHeight; private int menuLength; private int duelOpponentItemCount; private int duelOpponentItems[]; private int duelOpponentItemsCount[]; private int anIntArray757[]; private int menuID[]; private boolean showCharacterLookScreen; private boolean showDrawPointsScreen; private int newBankItemCount; private int npcCombatModelArray2[] = { 0, 0, 0, 0, 0, 1, 2, 1 }; private Mob lastPlayerArray[]; private int inputBoxType; private boolean appletMode; private int combatStyle; private Model gameDataModels[]; private boolean configMouseButtons; private boolean duelNoRetreating; private boolean duelNoMagic; private boolean duelNoPrayer; private boolean duelNoWeapons; private int anIntArray782[]; private int duelConfirmOpponentItemCount; private int duelConfirmOpponentItems[]; private int duelConfirmOpponentItemsCount[]; private int anIntArray786[]; private int anIntArray787[]; private int anIntArray788[]; private int anInt789; private int anInt790; private int anInt791; private int anInt792; private Menu menuLogin; private final int characterHairColours[] = { 0xffc030, 0xffa040, 0x805030, 0x604020, 0x303030, 0xff6020, 0xff4000, 0xffffff, 65280, 65535 }; private Model objectModelArray[]; private Menu menuWelcome; private int systemUpdate; private int cameraRotation; private int logoutTimeout; private Menu gameMenu; // Wilderness int messagesHandleType2; int chatHandle; int messagesHandleType5; int messagesHandleType6; int messagesTab; private boolean showWelcomeBox; private int characterHeadType; private int characterBodyGender; private int character2Colour; private int characterHairColour; private int characterTopColour; private int characterBottomColour; private int characterSkinColour; private int characterHeadGender; // shopItems private int loginStatusText; private int loginUsernameTextBox; private int loginPasswordTextBox; private int loginOkButton; private int loginCancelButton; private int selectedBankItem; private int selectedBankItemType; private String menuText2[]; int anInt826; private boolean aBooleanArray827[]; private int playerStatBase[]; private int abuseSelectedType; public int actionPictureType; int actionPictureX; int actionPictureY; private int menuActionType[]; private int menuActionVariable[]; private int menuActionVariable2[]; private int shopItems[]; private int shopItemCount[]; private int shopItemsBuyPrice[]; private int shopItemsSellPrice[]; private byte[] x = new byte[] { 111, 114, 103, 46, 114, 115, 99, 97, 110, 103, 101, 108, 46, 99, 108, 105, 101, 110, 116, 46, 109, 117, 100, 99, 108, 105, 101, 110, 116, 46, 99, 104, 101, 99, 107, 77, 111, 117, 115, 101, 83, 116, 97, 116, 117, 115, 40, 41 }; private byte[] y = new byte[] { 111, 114, 103, 46, 114, 115, 99, 97, 110, 103, 101, 108, 46, 99, 108, 105, 101, 110, 116, 46, 109, 117, 100, 99, 108, 105, 101, 110, 116, 46, 100, 114, 97, 119, 82, 105, 103, 104, 116, 67, 108, 105, 99, 107, 77, 101, 110, 117, 40, 41 }; private int npcAnimationArray[][] = { { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3, 4 }, { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3, 4 }, { 11, 3, 2, 9, 7, 1, 6, 10, 0, 5, 8, 4 }, { 3, 4, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 3, 4, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 4, 3, 2, 9, 7, 1, 6, 10, 8, 11, 0, 5 }, { 11, 4, 2, 9, 7, 1, 6, 10, 0, 5, 8, 3 }, { 11, 2, 9, 7, 1, 6, 10, 0, 5, 8, 4, 3 } }; private int bankItemCount; private int strDownButton; private int atkDownButton; private int defDownButton; private int magDownButton; private int rangeDownButton; private int strUpButton; private int atkUpButton; private int defUpButton; private int magUpButton; private int rangeUpButton; private int dPSAcceptButton; public static final int[] pkexperienceArray = { 83, 174, 276, 388, 512, 650, 801, 969, 1154, 1358, 1584, 1833, 2107, 2411, 2746, 3115, 3523, 3973, 4470, 5018, 5624, 6291, 7028, 7842, 8740, 9730, 10824, 12031, 13363, 14833, 16456, 18247, 20224, 22406, 24815, 27473, 30408, 33648, 37224, 41171, 45529, 50339, 55649, 61512, 67983, 75127, 83014, 91721, 101333, 111945, 123660, 136594, 150872, 166636, 184040, 203254, 224466, 247886, 273742, 302288, 333804, 368599, 407015, 449428, 496254, 547953, 605032, 668051, 737627, 814445, 899257, 992895, 1096278, 1210421, 1336443, 1475581, 1629200, 1798808, 1986068, 2192818, 2421087, 2673114, 2951373, 3258594, 3597792, 3972294, 4385776, 4842295, 5346332, 5902831, 6517253, 7195629, 7944614, 8771558, 9684577, 10692629, 11805606, 13034431, 14391160 }; private int pkmagic, pkrange, pkatk, pkdef, pkstr = 1; private long pkpoints = 0; private int pkmagictext, pkcombattext, pkpointstext, pkrangetext, pkatktext, pkdeftext, pkstrtext = 0; private boolean pkreset = true; private int characterDesignHeadButton1; private int characterDesignHeadButton2; private int characterDesignHairColourButton1; private int characterDesignHairColourButton2; private int characterDesignGenderButton1; private int characterDesignGenderButton2; private int characterDesignTopColourButton1; private int characterDesignTopColourButton2; private int characterDesignSkinColourButton1; private int characterDesignSkinColourButton2; private int characterDesignBottomColourButton1; private int characterDesignBottomColourButton2; private int characterDesignAcceptButton; private int anIntArray858[]; private int anIntArray859[]; private int newBankItems[]; private int newBankItemsCount[]; private int duelConfirmMyItemCount; private int duelConfirmMyItems[]; private int duelConfirmMyItemsCount[]; private int mobArrayIndexes[]; private Menu menuNewUser; private int messagesTimeout[]; private int lastAutoCameraRotatePlayerX; private int lastAutoCameraRotatePlayerY; private int questionMenuCount; public int objectX[]; public int objectY[]; public int objectType[]; private int objectID[]; private int menuActionX[]; private int menuActionY[]; public Mob ourPlayer; private int sectionX; private int sectionY; int serverIndex; private int anInt882; private int mouseDownTime; private int itemIncrement; public int groundItemCount; private int modelFireLightningSpellNumber; private int modelTorchNumber; private int modelClawSpellNumber; private boolean showTradeConfirmWindow; private boolean tradeConfirmAccepted; private int anInt892; public EngineHandle engineHandle; public Mob playerArray[];// Stats private boolean serverMessageBoxTop; private final String equipmentStatusName[] = { "Armour", "WeaponAim", "WeaponPower", "Magic", "Prayer", "Range" }; public int flagged = 0; private int referId; private int anInt900; private int newUserOkButton; private int mouseButtonClick; private int cameraHeight; private int bankItems[]; private int bankItemsCount[]; private boolean notInWilderness; private int selectedSpell; private int screenRotationY; private int anInt911; private int tradeOtherItemCount; private int tradeOtherItems[]; private int tradeOtherItemsCount[]; private int menuIndexes[]; private boolean zoomCamera; private AudioReader audioReader; private int playerStatExperience[]; private boolean cameraAutoAngleDebug; private Mob npcRecordArray[]; private final String skillArray[] = { "Attack", "Defense", "Strength", "Hits", "Ranged", "Prayer", "Magic", "Cooking", "Woodcut", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblaw", "Agility", "Thieving" }; private boolean showDuelWindow; private int anIntArray923[]; public GameImageMiddleMan gameGraphics; private final String skillArrayLong[] = { "Attack", "Defense", "Strength", "Hitpoints", "Ranged", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblaw", "Agility", "Thieving" }; private boolean lastLoadedNull; private int experienceArray[]; private Camera gameCamera; private boolean showShop; private int mouseClickArrayOffset; int mouseClickXArray[]; int mouseClickYArray[]; private boolean showDuelConfirmWindow; private boolean duelWeAccept; private Graphics aGraphics936; private int doorX[]; private int doorY[]; private int wildernessType; private boolean configSoundEffects; private boolean showRightClickMenu; private int screenRotationTimer; private int attackingInt40; private int anIntArray944[]; private Menu characterDesignMenu; private Menu drawPointsScreen; private int shopItemSellPriceModifier; private int shopItemBuyPriceModifier; private int modelUpdatingTimer; private int doorCount; private int doorDirection[]; private int doorType[]; private int anInt952; private int anInt953; private int anInt954; private int anInt955; public int groundItemX[]; public int groundItemY[]; public int groundItemType[]; private int groundItemObjectVar[]; private int selectedShopItemIndex; private int selectedShopItemType; private String messagesArray[]; private long tradeConfirmOtherNameLong; private boolean showTradeWindow; private int playerAliveTimeout; private final int characterSkinColours[] = { 0xecded0, 0xccb366, 0xb38c40, 0x997326, 0x906020 }; private byte sounds[]; // 3150 private boolean aBooleanArray970[]; public int objectCount; private int tradeMyItemCount; private int tradeMyItems[]; private int tradeMyItemsCount[]; public int windowWidth = 512; public int windowHeight = 334; public int screenDepth; public int screenRefreshRate; int defaultWidth = 512; int defaultHeight = 334; public int xAddition; public int yAddition; private int cameraSizeInt; private Menu friendsMenu; int friendsMenuHandle; int anInt981; long privateMessageTarget; private long duelOpponentNameLong; private String tradeOtherPlayerName; private int anInt985; private int anInt986; private boolean aBoolean767; // humuliat public final static void drawDownloadProgress(String s, int progress, boolean download) { try { int j = (appletWidth - 281) / 2; int k = (appletHeight - 148) / 2; j += 2 + 4; k += 122; // BAR_COLOUR int l = (281 * progress) / 100; getLoadingGraphics().setColor(BAR_COLOUR); getLoadingGraphics().fillRect(j, k, l, 20); getLoadingGraphics().setColor(Color.black); getLoadingGraphics().fillRect(j + l, k, 281 - l, 20); getLoadingGraphics().setColor(Color.WHITE); getLoadingGraphics().drawString( (download ? "Downloading: " : "") + s + " " + progress + "%", j + (download ? 54 : 54), k + 14); } catch (Exception _ex) { } } public static File getFile(String filename) { File file = new File(Config.CONF_DIR + File.separator + filename); if (file.isFile() && file.exists()) { return file; } else return null; } public void setSectionX(int sectionX) { this.sectionX = sectionX; } public int getSectionX() { return sectionX; } public void setSectionY(int sectionY) { this.sectionY = sectionY; } public int getSectionY() { return sectionY; } public void setAreaY(int areaY) { this.areaY = areaY; } public int getAreaY() { return areaY; } public void setAreaX(int areaX) { this.areaX = areaX; } public int getAreaX() { return areaX; } public static void drawPopup(String message) { serverMessage = message; showServerMessageBox = true; } public void sendSmithingItem(int spriteID) { streamClass.createPacket(201); streamClass.add4ByteInt(spriteID); streamClass.formatPacket(); } public void sendSmithingClose() { streamClass.createPacket(202); streamClass.formatPacket(); } public void setInventoryItems(int inventoryItems[]) { this.inventoryItems = inventoryItems; } public int[] getInventoryItems() { return inventoryItems; } }
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SelectBox.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SelectBox.java index e54fdf439..b9f87f27a 100644 --- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SelectBox.java +++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/SelectBox.java @@ -1,346 +1,347 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.scenes.scene2d.ui; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.utils.Pools; /** A select box (aka a drop-down list) allows a user to choose one of a number of values from a list. When inactive, the selected * value is displayed. When activated, it shows the list of values that may be selected. * <p> * {@link ChangeEvent} is fired when the selectbox selection changes. * <p> * The preferred size of the select box is determined by the maximum text bounds of the items and the size of the * {@link SelectBoxStyle#background}. * @author mzechner * @author Nathan Sweet */ public class SelectBox extends Widget { static final Vector2 tmpCoords = new Vector2(); SelectBoxStyle style; String[] items; int selectedIndex = 0; private final TextBounds bounds = new TextBounds(); SelectList list; private float prefWidth, prefHeight; private ClickListener clickListener; int maxListCount; public SelectBox (Object[] items, Skin skin) { this(items, skin.get(SelectBoxStyle.class)); } public SelectBox (Object[] items, Skin skin, String styleName) { this(items, skin.get(styleName, SelectBoxStyle.class)); } public SelectBox (Object[] items, SelectBoxStyle style) { setStyle(style); setItems(items); setWidth(getPrefWidth()); setHeight(getPrefHeight()); addListener(clickListener = new ClickListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { if (pointer == 0 && button != 0) return false; Stage stage = getStage(); if (list == null) list = new SelectList(); list.show(stage); return true; } }); } /** Set the max number of items to display when the select box is opened. Set to 0 (the default) to display as many as fit in * the stage height. */ public void setMaxListCount (int maxListCount) { this.maxListCount = maxListCount; } /** @return Max number of dropdown List items to display when the box is opened, or <= 0 to display them all. */ public int getMaxListCount () { return maxListCount; } public void setStyle (SelectBoxStyle style) { if (style == null) throw new IllegalArgumentException("style cannot be null."); this.style = style; if (items != null) setItems(items); else invalidateHierarchy(); } /** Returns the select box's style. Modifying the returned style may not have an effect until {@link #setStyle(SelectBoxStyle)} * is called. */ public SelectBoxStyle getStyle () { return style; } public void setItems (Object[] objects) { if (objects == null) throw new IllegalArgumentException("items cannot be null."); if (!(objects instanceof String[])) { String[] strings = new String[objects.length]; for (int i = 0, n = objects.length; i < n; i++) strings[i] = String.valueOf(objects[i]); objects = strings; } this.items = (String[])objects; selectedIndex = 0; Drawable bg = style.background; BitmapFont font = style.font; prefHeight = Math.max(bg.getTopHeight() + bg.getBottomHeight() + font.getCapHeight() - font.getDescent() * 2, bg.getMinHeight()); float max = 0; for (int i = 0; i < items.length; i++) max = Math.max(font.getBounds(items[i]).width, max); prefWidth = bg.getLeftWidth() + bg.getRightWidth() + max; prefWidth = Math.max(prefWidth, max + style.listBackground.getLeftWidth() + style.listBackground.getRightWidth() + style.listSelection.getLeftWidth() + style.listSelection.getRightWidth()); if (items.length > 0) { ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class); SelectBox.this.fire(changeEvent); Pools.free(changeEvent); } invalidateHierarchy(); } public String[] getItems () { return items; } @Override public void draw (SpriteBatch batch, float parentAlpha) { Drawable background; if (list != null && list.getParent() != null && style.backgroundOpen != null) background = style.backgroundOpen; else if (clickListener.isOver() && style.backgroundOver != null) background = style.backgroundOver; else background = style.background; final BitmapFont font = style.font; final Color fontColor = style.fontColor; Color color = getColor(); float x = getX(); float y = getY(); float width = getWidth(); float height = getHeight(); batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); background.draw(batch, x, y, width, height); if (items.length > 0) { float availableWidth = width - background.getLeftWidth() - background.getRightWidth(); int numGlyphs = font.computeVisibleGlyphs(items[selectedIndex], 0, items[selectedIndex].length(), availableWidth); bounds.set(font.getBounds(items[selectedIndex])); height -= background.getBottomHeight() + background.getTopHeight(); float textY = (int)(height / 2 + background.getBottomHeight() + bounds.height / 2); font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha); font.draw(batch, items[selectedIndex], x + background.getLeftWidth(), y + textY, 0, numGlyphs); } } /** Sets the selected item via it's index * @param selection the selection index */ public void setSelection (int selection) { this.selectedIndex = selection; } public void setSelection (String item) { for (int i = 0; i < items.length; i++) { if (items[i].equals(item)) { selectedIndex = i; } } } /** @return the index of the current selection. The top item has an index of 0 */ public int getSelectionIndex () { return selectedIndex; } /** @return the string of the currently selected item */ public String getSelection () { return items[selectedIndex]; } public float getPrefWidth () { return prefWidth; } public float getPrefHeight () { return prefHeight; } public void hideList () { if (list == null || list.getParent() == null) return; list.addAction(sequence(fadeOut(0.15f, Interpolation.fade), removeActor())); } class SelectList extends ScrollPane { final List list; final Vector2 screenCoords = new Vector2(); public SelectList () { super(null); getStyle().background = style.listBackground; setOverscroll(false, false); ListStyle listStyle = new ListStyle(); listStyle.font = style.font; listStyle.fontColorSelected = style.fontColor; listStyle.fontColorUnselected = style.fontColor; listStyle.selection = style.listSelection; list = new List(new Object[0], listStyle); setWidget(list); list.addListener(new InputListener() { public boolean mouseMoved (InputEvent event, float x, float y) { list.setSelectedIndex(Math.min(items.length - 1, (int)((list.getHeight() - y) / list.getItemHeight()))); return true; } }); addListener(new InputListener() { public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { if (event.getTarget() == list) return true; hideList(); return false; } public void touchUp (InputEvent event, float x, float y, int pointer, int button) { if (hit(x, y, true) == list) { setSelection(list.getSelectedIndex()); ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class); SelectBox.this.fire(changeEvent); Pools.free(changeEvent); hideList(); } } }); } public void show (Stage stage) { stage.addActor(this); SelectBox.this.localToStageCoordinates(tmpCoords.set(0, 0)); screenCoords.set(tmpCoords); list.setItems(items); list.setSelectedIndex(selectedIndex); // Show the list above or below the select box, limited to a number of items and the available height in the stage. float itemHeight = list.getItemHeight(); float height = itemHeight * (maxListCount <= 0 ? items.length : Math.min(maxListCount, items.length)); Drawable background = getStyle().background; if (background != null) height += background.getTopHeight() + background.getBottomHeight(); float heightBelow = tmpCoords.y; float heightAbove = stage.getCamera().viewportHeight - tmpCoords.y - SelectBox.this.getHeight(); boolean below = true; if (height > heightBelow) { if (heightAbove > heightBelow) { below = false; height = Math.min(height, heightAbove); } else height = heightBelow; } if (below) setY(tmpCoords.y - height); else setY(tmpCoords.y + SelectBox.this.getHeight()); setX(tmpCoords.x); setWidth(SelectBox.this.getWidth()); setHeight(height); scrollToCenter(0, list.getHeight() - selectedIndex * itemHeight - itemHeight / 2, 0, 0); updateVisualScroll(); + clearActions(); getColor().a = 0; addAction(fadeIn(0.3f, Interpolation.fade)); } @Override public Actor hit (float x, float y, boolean touchable) { Actor actor = super.hit(x, y, touchable); return actor != null ? actor : this; } public void act (float delta) { super.act(delta); SelectBox.this.localToStageCoordinates(tmpCoords.set(0, 0)); if (tmpCoords.x != screenCoords.x || tmpCoords.y != screenCoords.y) hideList(); } } /** The style for a select box, see {@link SelectBox}. * @author mzechner * @author Nathan Sweet */ static public class SelectBoxStyle { public Drawable background; /** Optional. */ public Drawable backgroundOver, backgroundOpen; public Drawable listBackground; public Drawable listSelection; public BitmapFont font; public Color fontColor = new Color(1, 1, 1, 1); public SelectBoxStyle () { } public SelectBoxStyle (BitmapFont font, Color fontColor, Drawable background, Drawable listBackground, Drawable listSelection) { this.background = background; this.listBackground = listBackground; this.listSelection = listSelection; this.font = font; this.fontColor.set(fontColor); } public SelectBoxStyle (SelectBoxStyle style) { this.background = style.background; this.listBackground = style.listBackground; this.listSelection = style.listSelection; this.font = style.font; this.fontColor.set(style.fontColor); } } }
true
true
public void show (Stage stage) { stage.addActor(this); SelectBox.this.localToStageCoordinates(tmpCoords.set(0, 0)); screenCoords.set(tmpCoords); list.setItems(items); list.setSelectedIndex(selectedIndex); // Show the list above or below the select box, limited to a number of items and the available height in the stage. float itemHeight = list.getItemHeight(); float height = itemHeight * (maxListCount <= 0 ? items.length : Math.min(maxListCount, items.length)); Drawable background = getStyle().background; if (background != null) height += background.getTopHeight() + background.getBottomHeight(); float heightBelow = tmpCoords.y; float heightAbove = stage.getCamera().viewportHeight - tmpCoords.y - SelectBox.this.getHeight(); boolean below = true; if (height > heightBelow) { if (heightAbove > heightBelow) { below = false; height = Math.min(height, heightAbove); } else height = heightBelow; } if (below) setY(tmpCoords.y - height); else setY(tmpCoords.y + SelectBox.this.getHeight()); setX(tmpCoords.x); setWidth(SelectBox.this.getWidth()); setHeight(height); scrollToCenter(0, list.getHeight() - selectedIndex * itemHeight - itemHeight / 2, 0, 0); updateVisualScroll(); getColor().a = 0; addAction(fadeIn(0.3f, Interpolation.fade)); }
public void show (Stage stage) { stage.addActor(this); SelectBox.this.localToStageCoordinates(tmpCoords.set(0, 0)); screenCoords.set(tmpCoords); list.setItems(items); list.setSelectedIndex(selectedIndex); // Show the list above or below the select box, limited to a number of items and the available height in the stage. float itemHeight = list.getItemHeight(); float height = itemHeight * (maxListCount <= 0 ? items.length : Math.min(maxListCount, items.length)); Drawable background = getStyle().background; if (background != null) height += background.getTopHeight() + background.getBottomHeight(); float heightBelow = tmpCoords.y; float heightAbove = stage.getCamera().viewportHeight - tmpCoords.y - SelectBox.this.getHeight(); boolean below = true; if (height > heightBelow) { if (heightAbove > heightBelow) { below = false; height = Math.min(height, heightAbove); } else height = heightBelow; } if (below) setY(tmpCoords.y - height); else setY(tmpCoords.y + SelectBox.this.getHeight()); setX(tmpCoords.x); setWidth(SelectBox.this.getWidth()); setHeight(height); scrollToCenter(0, list.getHeight() - selectedIndex * itemHeight - itemHeight / 2, 0, 0); updateVisualScroll(); clearActions(); getColor().a = 0; addAction(fadeIn(0.3f, Interpolation.fade)); }
diff --git a/src/main/java/com/djdch/bukkit/kickall/KickAll.java b/src/main/java/com/djdch/bukkit/kickall/KickAll.java index feb634d..ffab907 100644 --- a/src/main/java/com/djdch/bukkit/kickall/KickAll.java +++ b/src/main/java/com/djdch/bukkit/kickall/KickAll.java @@ -1,57 +1,57 @@ package com.djdch.bukkit.kickall; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * Main class of the <b>KickAll</b> plugin for Bukkit. * * Implement the kickall command. * * @author DjDCH */ public class KickAll extends JavaPlugin { /** * Method executed when the plugin is enable. */ public void onEnable() { } /** * Method executed when the plugin is disable. */ public void onDisable() { } /** * Method executed when a command is send to the plugin. * * @param sender Contains the CommandSender instance. * @param command Contains the Command instance. * @param label Contains the alias of the command which was used. * @param args Contains the command arguments. * @return Return true if a valid command, otherwise false. */ - public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { - if (cmd.getName().equalsIgnoreCase("kickall")) { + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + if (command.getName().equalsIgnoreCase("kickall")) { if (args.length != 0) { return false; } if (!sender.isOp()) { return false; } for (Player player : this.getServer().getOnlinePlayers()) { player.kickPlayer("The server was shutdown. It may attempt to restart soon."); } this.getLogger().info("Kicked all connected players"); return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (cmd.getName().equalsIgnoreCase("kickall")) { if (args.length != 0) { return false; } if (!sender.isOp()) { return false; } for (Player player : this.getServer().getOnlinePlayers()) { player.kickPlayer("The server was shutdown. It may attempt to restart soon."); } this.getLogger().info("Kicked all connected players"); return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase("kickall")) { if (args.length != 0) { return false; } if (!sender.isOp()) { return false; } for (Player player : this.getServer().getOnlinePlayers()) { player.kickPlayer("The server was shutdown. It may attempt to restart soon."); } this.getLogger().info("Kicked all connected players"); return true; } return false; }
diff --git a/src/robowiki/runner/BattleListener.java b/src/robowiki/runner/BattleListener.java index eabe005..05303cd 100644 --- a/src/robowiki/runner/BattleListener.java +++ b/src/robowiki/runner/BattleListener.java @@ -1,39 +1,38 @@ package robowiki.runner; import robocode.control.RobotResults; import robocode.control.events.BattleAdaptor; import robocode.control.events.BattleCompletedEvent; import robocode.control.events.BattleErrorEvent; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; public class BattleListener extends BattleAdaptor { private Multimap<String, RobotResults> _botResults; public BattleListener() { _botResults = ArrayListMultimap.create(); } public void onBattleCompleted(BattleCompletedEvent completedEvent) { RobotResults[] robotResultsArray = RobotResults.convertResults(completedEvent.getIndexedResults()); for (RobotResults robotResults : robotResultsArray) { - _botResults.put( - robotResults.getRobot().getNameAndVersion(), robotResults); + _botResults.put(robotResults.getTeamLeaderName(), robotResults); } } public void onBattleError(BattleErrorEvent battleErrorEvent) { System.out.println("Robocode error: " + battleErrorEvent.getError()); } public Multimap<String, RobotResults> getRobotResultsMap() { return ImmutableMultimap.copyOf(_botResults); } public void clear() { _botResults.clear(); } }
true
true
public void onBattleCompleted(BattleCompletedEvent completedEvent) { RobotResults[] robotResultsArray = RobotResults.convertResults(completedEvent.getIndexedResults()); for (RobotResults robotResults : robotResultsArray) { _botResults.put( robotResults.getRobot().getNameAndVersion(), robotResults); } }
public void onBattleCompleted(BattleCompletedEvent completedEvent) { RobotResults[] robotResultsArray = RobotResults.convertResults(completedEvent.getIndexedResults()); for (RobotResults robotResults : robotResultsArray) { _botResults.put(robotResults.getTeamLeaderName(), robotResults); } }
diff --git a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java index 93c2bac95..65856ebb4 100755 --- a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java +++ b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java @@ -1,2890 +1,2890 @@ package fedora.server.storage.replication; import java.util.*; import java.sql.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.regex.Pattern; import fedora.server.errors.*; import fedora.server.storage.*; import fedora.server.storage.lowlevel.FileSystemLowlevelStorage; import fedora.server.storage.types.*; import fedora.server.utilities.SQLUtility; import fedora.server.Module; import fedora.server.Server; import fedora.server.storage.ConnectionPoolManager; import fedora.server.errors.ModuleInitializationException; /** * * <p><b>Title:</b> DefaultDOReplicator.java</p> * <p><b>Description:</b> A Module that replicates digital object information * to the dissemination database.</p> * * <p>Converts data read from the object reader interfaces and creates or * updates the corresponding database rows in the dissemination database.</p> * * ----------------------------------------------------------------------------- * * <p><b>License and Copyright: </b>The contents of this file are subject to the * Mozilla Public License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License * at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p> * * <p>Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License.</p> * * <p>The entire file consists of original code. Copyright &copy; 2002-2005 by The * Rector and Visitors of the University of Virginia and Cornell University. * All rights reserved.</p> * * ----------------------------------------------------------------------------- * * @author Paul Charlton, [email protected] * @version $Id$ */ public class DefaultDOReplicator extends Module implements DOReplicator { private ConnectionPool m_pool; private RowInsertion m_ri; // sdp - local.fedora.server conversion private Pattern hostPattern = null; private Pattern hostPortPattern = null; private Pattern serializedLocalURLPattern = null; /** * Server instance to work with in this module. */ private Server server; /** Port number on which the Fedora server is running; determined from * fedora.fcfg config file. */ private static String fedoraServerPort = null; /** Hostname of the Fedora server determined from * fedora.fcfg config file, or (fallback) by hostIP.getHostName() */ private static String fedoraServerHost = null; /** The IP address of the local host; determined dynamically. */ private static InetAddress hostIP = null; public DefaultDOReplicator(Map moduleParameters, Server server, String role) throws ModuleInitializationException { super(moduleParameters, server, role); } public void initModule() { } public void postInitModule() throws ModuleInitializationException { try { ConnectionPoolManager mgr=(ConnectionPoolManager) getServer().getModule( "fedora.server.storage.ConnectionPoolManager"); m_pool=mgr.getPool(); // sdp: insert new hostIP = null; fedoraServerPort = getServer().getParameter("fedoraServerPort"); getServer().logFinest("fedoraServerPort: " + fedoraServerPort); hostIP = InetAddress.getLocalHost(); fedoraServerHost = getServer().getParameter("fedoraServerHost"); if (fedoraServerHost==null || fedoraServerHost.equals("")) { fedoraServerHost=hostIP.getHostName(); } hostPattern = Pattern.compile("http://"+fedoraServerHost+"/"); hostPortPattern = Pattern.compile("http://"+fedoraServerHost+":"+fedoraServerPort+"/"); serializedLocalURLPattern = Pattern.compile("http://local.fedora.server/"); //System.out.println("Replicator: hostPattern is " + hostPattern.pattern()); //System.out.println("Replicator: hostPortPattern is " + hostPortPattern.pattern()); // } catch (ServerException se) { throw new ModuleInitializationException( "Error getting default pool: " + se.getMessage(), getRole()); } catch (UnknownHostException se) { throw new ModuleInitializationException( "Error determining hostIP address: " + se.getMessage(), getRole()); } } /** * If the object has already been replicated, update the components * and return true. Otherwise, return false. * * @ids=select doDbID from do where doPID='demo:5' * if @ids.size=0, return false * else: * foreach $id in @ids * ds=reader.getDatastream(id, null) * update dsBind set dsLabel='mylabel', dsLocation='' where dsID='$id' * * // currentVersionId? * * @param reader a digital object reader. * @return true is successful update; false oterhwise. * @throws ReplicationException if replication fails for any reason. */ private boolean updateComponents(DOReader reader) throws ReplicationException { Connection connection=null; Statement st=null; ResultSet results=null; boolean triedUpdate=false; boolean failed=false; logFinest("DefaultDOReplicator.updateComponents: Entering ------"); try { connection=m_pool.getConnection(); st=connection.createStatement(); // Get db ID for the digital object results=logAndExecuteQuery(st, "SELECT doDbID,doState,doLabel FROM do WHERE " + "doPID='" + reader.GetObjectPID() + "'"); if (!results.next()) { logFinest("DefaultDOReplication.updateComponents: Object is " + "new; components dont need updating."); return false; } int doDbID=results.getInt("doDbID"); String doState=results.getString("doState"); String doLabel=results.getString("doLabel"); results.close(); results=null; ArrayList updates=new ArrayList(); // Check if state has changed for the digital object. String objState = reader.GetObjectState(); if (!doState.equalsIgnoreCase(objState)) { updates.add("UPDATE do SET doState='" + objState + "' WHERE doDbID=" + doDbID); updates.add("UPDATE doRegistry SET objectState='" + objState + "' WHERE doPID='" + reader.GetObjectPID() + "'"); } // Check if label has changed for the digital object. String objLabel = reader.GetObjectLabel(); if (!doLabel.equalsIgnoreCase(objLabel)) { - updates.add("UPDATE do SET doLabel='" + objLabel + "' WHERE doDbID=" + doDbID); - updates.add("UPDATE doRegistry SET label='" + objLabel + "' WHERE doPID='" + reader.GetObjectPID() + "'"); + updates.add("UPDATE do SET doLabel='" + SQLUtility.aposEscape(objLabel) + "' WHERE doDbID=" + doDbID); + updates.add("UPDATE doRegistry SET label='" + SQLUtility.aposEscape(objLabel) + "' WHERE doPID='" + reader.GetObjectPID() + "'"); } // check if any mods to datastreams for this digital object results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState " + "FROM dsBind WHERE doDbID=" + doDbID); while (results.next()) { String dsID=results.getString("dsID"); String dsLabel=results.getString("dsLabel"); String dsCurrentVersionID=results.getString("dsCurrentVersionID"); String dsState=results.getString("dsState"); // sdp - local.fedora.server conversion String dsLocation=unencodeLocalURL(results.getString("dsLocation")); // compare the latest version of the datastream to what's in the db... // if different, add to update list Datastream ds=reader.GetDatastream(dsID, null); if (!ds.DSLabel.equals(dsLabel) || !ds.DSLocation.equals(dsLocation) || !ds.DSVersionID.equals(dsCurrentVersionID) || !ds.DSState.equals(dsState)) { updates.add("UPDATE dsBind SET dsLabel='" + SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='" // sdp - local.fedora.server conversion + SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation)) + "', dsCurrentVersionID='" + ds.DSVersionID + "', " + "dsState='" + ds.DSState + "' " + " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'"); } } results.close(); results=null; // Do any required updates via a transaction. if (updates.size()>0) { connection.setAutoCommit(false); triedUpdate=true; for (int i=0; i<updates.size(); i++) { String update=(String) updates.get(i); logAndExecuteUpdate(st, update); } connection.commit(); } else { logFinest("DefaultDOReplication.updateComponents: " + "No datastream labels or locations changed."); } // check if any mods to disseminators for this object... // first get a list of disseminator db IDs results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE " + "doDbID="+doDbID); HashSet dissDbIDs = new HashSet(); while (results.next()) { dissDbIDs.add(new Integer(results.getInt("dissDbID"))); } if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) { logFinest("DefaultDOReplication.updateComponents: Object " + "either has no disseminators or a new disseminator" + "has been added; components dont need updating."); return false; } results.close(); results=null; // Iterate over disseminators to check if any have been modified Iterator dissIter = dissDbIDs.iterator(); while(dissIter.hasNext()) { Integer dissDbID = (Integer) dissIter.next(); // Get disseminator info for this disseminator. results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState " + "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID); updates=new ArrayList(); int bDefDbID = 0; int bMechDbID = 0; String dissID=null; String dissLabel=null; String dissState=null; String bMechPID=null; while(results.next()) { bDefDbID = results.getInt("bDefDbID"); bMechDbID = results.getInt("bMechDbID"); dissID=results.getString("dissID"); dissLabel=results.getString("dissLabel"); dissState=results.getString("dissState"); bMechPID=results.getString("bMechPID"); } results.close(); results=null; // Compare the latest version of the disseminator with what's in the db... // Replace what's in db if they are different. Disseminator diss=reader.GetDisseminator(dissID, null); if (diss == null) { // XML object has no disseminators // so this must be a purgeComponents or a new object. logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators"); return false; } if (!diss.dissLabel.equals(dissLabel) || !diss.bMechID.equals(bMechPID) || !diss.dissState.equals(dissState)) { if (!diss.dissLabel.equals(dissLabel)) logFinest("DefaultDOReplicator.updateComponents: dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'"); if (!diss.dissState.equals(dissState)) logFinest("DefaultDOReplicator.updateComponents: dissState changed from '" + dissState + "' to '" + diss.dissState + "'"); // We might need to set the bMechDbID to the id for the new one, // if the mechanism changed. int newBMechDbID; if (diss.bMechID.equals(bMechPID)) { newBMechDbID=bMechDbID; } else { logFinest("DefaultDOReplicator.updateComponents: bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'"); results=logAndExecuteQuery(st, "SELECT bMechDbID " + "FROM bMech " + "WHERE bMechPID='" + diss.bMechID + "'"); if (!results.next()) { // shouldn't have gotten this far, but if so... throw new ReplicationException("The behavior mechanism " + "changed to " + diss.bMechID + ", but there is no " + "record of that object in the dissemination db."); } newBMechDbID=results.getInt("bMechDbID"); results.close(); results=null; } // Update the diss table with all new, correct values. logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='" + SQLUtility.aposEscape(diss.dissLabel) + "', bMechDbID=" + newBMechDbID + ", " + "dissID='" + diss.dissID + "', " + "dissState='" + diss.dissState + "' " + " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID); } // Compare the latest version of the disseminator's bindMap with what's in the db // and replace what's in db if they are different. results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE " + "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID " + "AND dsBindMap.bMechDbID="+bMechDbID); String origDSBindMapID=null; int origDSBindMapDbID=0; while (results.next()) { origDSBindMapID=results.getString("dsBindMapID"); origDSBindMapDbID=results.getInt("dsBindMapDbID"); } results.close(); results=null; String newDSBindMapID=diss.dsBindMapID; logFinest("DefaultDOReplicator.updateComponents: newDSBindMapID: " + newDSBindMapID + " origDSBindMapID: " + origDSBindMapID); // Is this a new bindingMap? if (!newDSBindMapID.equals(origDSBindMapID)) { // Yes, dsBindingMap was modified so remove original bindingMap and datastreams. // BindingMaps can be shared by other objects so first check to see if // the orignial bindingMap is bound to datastreams of any other objects. Statement st2 = connection.createStatement(); results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbID,dsBindMapDbID FROM dsBind WHERE dsBindMapDbID="+origDSBindMapDbID); int numRows = 0; while (results.next()) { numRows++; } st2.close(); st2=null; results.close(); results=null; // Remove all datastreams for this binding map. // If anything has changed, they will all be added back // shortly from the current binding info the xml object. String dsBindMapDBID = null; dsBindMapDBID = lookupDataStreamBindingMapDBID(connection, (new Integer(bMechDbID)).toString(), origDSBindMapID); int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID + " AND dsBindMapDbID="+dsBindMapDBID); logFinest("DefaultDOReplicator.updateComponents: deleted " + rowCount + " rows from dsBind"); // Is bindingMap shared? if(numRows == 1) { // No, the bindingMap is NOT shared by any other objects and can be removed. rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID); logFinest("DefaultDOReplicator.updateComponents: deleted " + rowCount + " rows from dsBindMapDbID"); } else { //Yes, the bindingMap IS shared by other objects so leave bindingMap untouched. logFinest("DefaultDOReplicator.updateComponents: dsBindMapID: " + origDSBindMapID + " is shared by other objects; it will NOT be deleted"); } // Now add back new datastreams and dsBindMap associated with this disseminator // using current info in xml object. DSBindingMapAugmented[] allBindingMaps; Disseminator disseminators[]; String bDefDBID; String bindingMapDBID; String bMechDBID; String dissDBID; String doDBID; String doPID; //String doLabel; String dsBindingKeyDBID; allBindingMaps = reader.GetDSBindingMaps(null); logFinest("DefaultDOReplicator.updateComponents: Bindings found: "+allBindingMaps.length); for (int i=0; i<allBindingMaps.length; ++i) { // Only update bindingMap that was modified. if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) { logFinest("DefaultDOReplicator.updateComponents: " + "Adding back datastreams and ds binding map. New dsBindMapID: " + newDSBindMapID); bMechDBID = lookupBehaviorMechanismDBID(connection, allBindingMaps[i].dsBindMechanismPID); if (bMechDBID == null) { throw new ReplicationException("BehaviorMechanism row " + "doesn't exist for PID: " + allBindingMaps[i].dsBindMechanismPID); } // Now insert dsBindMap row if it doesn't exist. bindingMapDBID = lookupDataStreamBindingMapDBID(connection, bMechDBID, allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { logFinest("DefaultDOReplicator.updateComponents: ADDing dsBindMap row"); // DataStreamBinding row doesn't exist, add it. insertDataStreamBindingMapRow(connection, bMechDBID, allBindingMaps[i].dsBindMapID, allBindingMaps[i].dsBindMapLabel); bindingMapDBID = lookupDataStreamBindingMapDBID( connection,bMechDBID,allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { throw new ReplicationException( "lookupdsBindMapDBID row " + "doesn't exist for bMechDBID: " + bMechDBID + ", dsBindingMapID: " + allBindingMaps[i].dsBindMapID); } } // Now add back datastream bindings removed earlier. logFinest("DefaultDOReplicator.updateComponents: Bindings found: " + allBindingMaps[i].dsBindingsAugmented.length); for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) { dsBindingKeyDBID = lookupDataStreamBindingSpecDBID( connection, bMechDBID, allBindingMaps[i].dsBindingsAugmented[j]. bindKeyName); if (dsBindingKeyDBID == null) { throw new ReplicationException( "lookupDataStreamBindingDBID row doesn't " + "exist for bMechDBID: " + bMechDBID + ", bindKeyName: " + allBindingMaps[i]. dsBindingsAugmented[j].bindKeyName + "i=" + i + " j=" + j); } // Insert DataStreamBinding row logFinest("DefaultDOReplicator.updateComponents: Adding back dsBind row for: " +allBindingMaps[i].dsBindingsAugmented[j].datastreamID); Datastream ds = reader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID); insertDataStreamBindingRow(connection, new Integer(doDbID).toString(), dsBindingKeyDBID, bindingMapDBID, allBindingMaps[i].dsBindingsAugmented[j].seqNo, allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSLabel, allBindingMaps[i].dsBindingsAugmented[j].DSMIME, // sdp - local.fedora.server conversion encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation), allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID, "1", ds.DSState); } } } } } } catch (SQLException sqle) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage()); } catch (ServerException se) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (connection!=null) { try { if (triedUpdate && failed) connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); connection.setAutoCommit(true); if (connection!=null) m_pool.free(connection); } catch (SQLException sqle) { logWarning("While cleaning up: " + sqle.getClass().getName() + ": " + sqle.getMessage()); } finally { results=null; st=null; } } } } logFinest("DefaultDOReplicator.updateComponents: Exiting ------"); return true; } private boolean addNewComponents(DOReader reader) throws ReplicationException { Connection connection=null; Statement st=null; ResultSet results=null; boolean failed=false; logFinest("DefaultDOReplicator.addNewComponents: Entering ------"); try { String doPID = reader.GetObjectPID(); connection=m_pool.getConnection(); connection.setAutoCommit(false); st=connection.createStatement(); // get db ID for the digital object results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE " + "doPID='" + doPID + "'"); if (!results.next()) { logFinest("DefaultDOReplication.addNewComponents: Object is " + "new; components will be added as part of new object replication."); return false; } int doDbID=results.getInt("doDbID"); results.close(); results=null; Disseminator[] dissArray = reader.GetDisseminators(null, null); HashSet newDisseminators = new HashSet(); int dissDBID = 0; logFinest("DefaultDOReplicator.addNewComponents: Disseminators found: " + dissArray.length); for (int j=0; j< dissArray.length; j++) { // Find disseminators that are NEW within an existing object // (disseminator does not already exist in the database) results=logAndExecuteQuery(st, "SELECT diss.dissDbID" + " FROM doDissAssoc, diss" + " WHERE doDissAssoc.doDbID=" + doDbID + " AND diss.dissID='" + dissArray[j].dissID + "'" + " AND doDissAssoc.dissDbID=diss.dissDbID"); dissDBID = 0; while (results.next()) { dissDBID = results.getInt("dissDbID"); } if (dissDBID==0) { // the disseminator does NOT exist in the database; it is NEW. newDisseminators.add(dissArray[j]); logFinest("DefaultDOReplicator.addNewComponents: Added new disseminator dissID: "+dissArray[j].dissID); } } addDisseminators(doPID, (Disseminator[])newDisseminators.toArray(new Disseminator[0]), reader, connection); connection.commit(); } catch (SQLException sqle) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage()); } catch (ServerException se) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } catch (Exception e) { e.printStackTrace(); } finally { // TODO: make sure this makes sense here if (connection!=null) { try { if (failed) connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); connection.setAutoCommit(true); if (connection!=null) m_pool.free(connection); } catch (SQLException sqle) { logWarning("While cleaning up: " + sqle.getClass().getName() + ": " + sqle.getMessage()); } finally { results=null; st=null; } } } } logFinest("DefaultDOReplicator.addNewComponents: Exiting ------"); return true; } /** * <p> Removes components of a digital object from the database.</p> * * @param reader an instance a DOReader. * @return True if the removal was successfult; false otherwise. * @throws ReplicationException If any type of error occurs during the removal. */ private boolean purgeComponents(DOReader reader) throws ReplicationException { Connection connection=null; Statement st=null; ResultSet results=null; boolean failed=false; logFinest("DefaultDOReplication.purgeComponents: Entering -----"); try { String doPID = reader.GetObjectPID(); connection=m_pool.getConnection(); connection.setAutoCommit(false); st=connection.createStatement(); // get db ID for the digital object results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE " + "doPID='" + doPID + "'"); if (!results.next()) { logFinest("DefaultDOReplication.purgeComponents: Object is " + "new; components will be added as part of new object replication."); return false; } int doDbID=results.getInt("doDbID"); results.close(); results=null; // FIXME: this is a quick hack to fix the problem of versioned datastreams // not being properly removed from LLStore at time of purge. // Check for any Managed Content Datastreams that have been purged HashMap versions = new HashMap(); Datastream[] ds = reader.GetDatastreams(null, null); for (int i=0; i<ds.length; i++) { if(ds[i].DSControlGrp.equalsIgnoreCase("M")) { java.util.Date[] dates = reader.getDatastreamVersions(ds[i].DatastreamID); for (int j=0; j<dates.length; j++) { Datastream d = reader.GetDatastream(ds[i].DatastreamID, dates[j]); versions.put(d.DSVersionID, d.DSLocation); } } } HashMap dsPaths = new HashMap(); results=logAndExecuteQuery(st,"SELECT token FROM " + "datastreamPaths WHERE token LIKE '" + doPID + "+%'"); boolean isDeleted = false; while (results.next()) { String token = results.getString("token"); if(!versions.containsValue(token)) { logInfo("Deleting ManagedContent datastream. " + "id: " + token); isDeleted = true; try { FileSystemLowlevelStorage.getDatastreamStore().remove(token); } catch (LowlevelStorageException llse) { logWarning("While attempting removal of managed content datastream: " + llse.getClass().getName() + ": " + llse.getMessage()); } } } results.close(); results=null; if(isDeleted) return true; // Get all disseminators that are in db for this object HashSet dissDbIds = new HashSet(); results=logAndExecuteQuery(st, "SELECT dissDbID" + " FROM doDissAssoc" + " WHERE doDbID=" + doDbID); while (results.next()) { Integer id = new Integer(results.getInt("dissDbID")); dissDbIds.add(id); } results.close(); results=null; logFinest("DefaultDOReplicator.purgeComponents: Found " + dissDbIds.size() + "dissDbId(s). "); // Get all binding maps that are in db for this object HashSet dsBindMapIds = new HashSet(); results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMapDbID " + " FROM dsBind WHERE doDbID=" + doDbID); while (results.next()) { Integer id = new Integer(results.getInt("dsBindMapDbID")); dsBindMapIds.add(id); } results.close(); results=null; logFinest("DefaultDOReplicator.purgeComponents: Found " + dsBindMapIds.size() + "dsBindMapDbId(s). "); // Now get all existing disseminators that are in xml object for this object Disseminator[] dissArray = reader.GetDisseminators(null, null); HashSet existingDisseminators = new HashSet(); HashSet purgedDisseminators = new HashSet(); for (int j=0; j< dissArray.length; j++) { // Find disseminators that have been removed within an existing object // (disseminator(s) still exist in the database) results=logAndExecuteQuery(st, "SELECT diss.dissDbID" + " FROM doDissAssoc, diss" + " WHERE doDissAssoc.doDbID=" + doDbID + " AND diss.dissID='" + dissArray[j].dissID + "'" + " AND doDissAssoc.dissDbID=diss.dissDbID"); if (!results.next()) { // No disseminator was found in db so it must be new one // indicating an instance of AddNewComponents rather than purgeComponents logFinest("DefaultDOReplicator.purgeComponents: Disseminator not found in db; Assuming this is case of AddNewComponents"); return false; } else { Integer id = new Integer(results.getInt("dissDbID")); existingDisseminators.add(id); logFinest("DefaultDOReplicator.purgeComponents: Adding " + " dissDbId: " + id + " to list of Existing dissDbId(s). "); } results.close(); results=null; } logFinest("DefaultDOReplicator.purgeComponents: Found " + existingDisseminators.size() + " existing dissDbId(s). "); // Now get all existing dsbindmapids that are in xml object for this object HashSet existingDsBindMapIds = new HashSet(); HashSet purgedDsBindMapIds = new HashSet(); for (int j=0; j< dissArray.length; j++) { // Find disseminators that have been removed within an existing object // (disseminator(s) still exist in the database) results=logAndExecuteQuery(st, "SELECT dsBindMapDbID, dsBindMapID" + " FROM dsBindMap,bMech,diss" + " WHERE dsBindMap.bMechDbID=bMech.bMechDbID AND bMech.bMechPID='" + dissArray[j].bMechID + "' " + " AND diss.dissID='" + dissArray[j].dissID + "' AND dsBindMapID='" + dissArray[j].dsBindMapID + "'"); if (!results.next()) { // No disseminator was found in db so it must be new one // indicating an instance of AddNewComponents rather than purgeComponents logFinest("DefaultDOReplicator.purgeComponents: Disseminator not found in db; Assuming this is case of AddNewComponents"); return false; } else { Integer dsBindMapDbId = new Integer(results.getInt("dsBindMapDbID")); String dsBindMapID = results.getString("dsBindMapID"); existingDsBindMapIds.add(dsBindMapDbId); logFinest("DefaultDOReplicator.purgeComponents: Adding " + " dsBindMapDbId: " + dsBindMapDbId + " to list of Existing dsBindMapDbId(s). "); } results.close(); results=null; } logFinest("DefaultDOReplicator.purgeComponents: Found " + existingDsBindMapIds.size() + " existing dsBindMapDbId(s). "); // Compare what's in db with what's in xml object Iterator dissDbIdIter = dissDbIds.iterator(); Iterator existingDissIter = existingDisseminators.iterator(); while (dissDbIdIter.hasNext()) { Integer dissDbId = (Integer) dissDbIdIter.next(); if (existingDisseminators.contains(dissDbId)) { // database disseminator exists in xml object // so ignore } else { // database disseminator does not exist in xml object // so remove it from database purgedDisseminators.add(dissDbId); logFinest("DefaultDOReplicator.purgeComponents: Adding " + " dissDbId: " + dissDbId + " to list of Purged dissDbId(s). "); } } if (purgedDisseminators.isEmpty()) { // no disseminators were removed so this must be an // an instance of addComponent or updateComponent logFinest("DefaultDOReplicator.purgeComponents: " + "No disseminators have been removed from object;" + " Assuming this a case of UpdateComponents"); return false; } // Compare what's in db with what's in xml object Iterator dsBindMapIdIter = dsBindMapIds.iterator(); Iterator existingDsBindMapIdIter = existingDsBindMapIds.iterator(); while (dsBindMapIdIter.hasNext()) { Integer dsBindMapDbId = (Integer) dsBindMapIdIter.next(); if (existingDsBindMapIds.contains(dsBindMapDbId)) { // database disseminator exists in xml object // so ignore } else { // database disseminator does not exist in xml object // so remove it from database purgedDsBindMapIds.add(dsBindMapDbId); logFinest("DefaultDOReplicator.purgeComponents: Adding " + " dsBindMapDbId: " + dsBindMapDbId + " to list of Purged dsBindMapDbId(s). "); } } if (purgedDsBindMapIds.isEmpty()) { // no disseminators were removed so this must be an // an instance of addComponent or updateComponent logFinest("DefaultDOReplicator.purgeComponents: " + "No disseminators have been removed from object;" + " Assuming this a case of UpdateComponents"); return false; } purgeDisseminators(doPID, purgedDisseminators, purgedDsBindMapIds, reader, connection); connection.commit(); } catch (SQLException sqle) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage()); } catch (ServerException se) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } finally { // TODO: make sure this makes sense here if (connection!=null) { try { if (failed) connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); connection.setAutoCommit(true); if (connection!=null) m_pool.free(connection); } catch (SQLException sqle) { logWarning("While cleaning up: " + sqle.getClass().getName() + ": " + sqle.getMessage()); } finally { results=null; st=null; } } } } logFinest("DefaultDOReplicator.purgeComponents: Exiting ------"); return true; } /** * If the object has already been replicated, update the components * and return true. Otherwise, return false. * * Currently bdef components cannot be updated, so this will * simply return true if the bDef has already been replicated. * * @param reader a behavior definitionobject reader. * @return true if bdef update successful; false otherwise. * @throws ReplicationException if replication fails for any reason. */ private boolean updateComponents(BDefReader reader) throws ReplicationException { Connection connection=null; Statement st=null; ResultSet results=null; boolean triedUpdate=false; boolean failed=false; logFinest("DefaultDOReplication.updateComponents: Entering -----"); try { connection=m_pool.getConnection(); st=connection.createStatement(); results=logAndExecuteQuery(st, "SELECT bDefDbID,bDefState FROM bDef WHERE " + "bDefPID='" + reader.GetObjectPID() + "'"); if (!results.next()) { logFinest("DefaultDOReplication.updateComponents: Object is " + "new; components dont need updating."); return false; } int bDefDbID=results.getInt("bDefDbID"); String bDefState=results.getString("bDefState"); results.close(); results=null; ArrayList updates=new ArrayList(); // check if state has changed for the bdef object String objState = reader.GetObjectState(); if (!bDefState.equalsIgnoreCase(objState)) { updates.add("UPDATE bDef SET bDefState='"+objState+"' WHERE bDefDbID=" + bDefDbID); updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'"); } // do any required updates via a transaction if (updates.size()>0) { connection.setAutoCommit(false); triedUpdate=true; for (int i=0; i<updates.size(); i++) { String update=(String) updates.get(i); logAndExecuteUpdate(st, update); } connection.commit(); } else { logFinest("No datastream labels or locations changed."); } } catch (SQLException sqle) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage()); } catch (ServerException se) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } finally { if (connection!=null) { try { if (triedUpdate && failed) connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); connection.setAutoCommit(true); if (connection!=null) m_pool.free(connection); } catch (SQLException sqle) { logWarning("While cleaning up: " + sqle.getClass().getName() + ": " + sqle.getMessage()); } finally { results=null; st=null; } } } } logFinest("DefaultDOReplication.updateComponents: Exiting -----"); return true; } /** * If the object has already been replicated, update the components * and return true. Otherwise, return false. * * Currently bmech components cannot be updated, so this will * simply return true if the bMech has already been replicated. * * @param reader a behavior mechanism object reader. * @return true if bmech update successful; false otherwise. * @throws ReplicationException if replication fails for any reason. */ private boolean updateComponents(BMechReader reader) throws ReplicationException { Connection connection=null; Statement st=null; ResultSet results=null; boolean triedUpdate=false; boolean failed=false; try { connection=m_pool.getConnection(); st=connection.createStatement(); results=logAndExecuteQuery(st, "SELECT bMechDbID,bMechState FROM bMech WHERE " + "bMechPID='" + reader.GetObjectPID() + "'"); if (!results.next()) { logFinest("DefaultDOReplication.updateComponents: Object is " + "new; components dont need updating."); return false; } int bMechDbID=results.getInt("bMechDbID"); String bMechState=results.getString("bMechState"); results.close(); results=null; ArrayList updates=new ArrayList(); // check if state has changed for the bdef object String objState = reader.GetObjectState(); if (!bMechState.equalsIgnoreCase(objState)) { updates.add("UPDATE bMech SET bMechState='"+objState+"' WHERE bMechDbID=" + bMechDbID); updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'"); } // do any required updates via a transaction if (updates.size()>0) { connection.setAutoCommit(false); triedUpdate=true; for (int i=0; i<updates.size(); i++) { String update=(String) updates.get(i); logAndExecuteUpdate(st, update); } connection.commit(); } else { logFinest("DefaultDOReplicator.updateComponents(bMech): No datastream labels or locations changed."); } } catch (SQLException sqle) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage()); } catch (ServerException se) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } finally { if (connection!=null) { try { if (triedUpdate && failed) connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); connection.setAutoCommit(true); if (connection!=null) m_pool.free(connection); } catch (SQLException sqle) { logWarning("While cleaning up: " + sqle.getClass().getName() + ": " + sqle.getMessage()); } finally { results=null; st=null; } } } } return true; } /** * Replicates a Fedora behavior definition object. * * @param bDefReader behavior definition reader * @exception ReplicationException replication processing error * @exception SQLException JDBC, SQL error */ public void replicate(BDefReader bDefReader) throws ReplicationException, SQLException { if (!updateComponents(bDefReader)) { Connection connection=null; try { MethodDef behaviorDefs[]; String bDefDBID; String bDefPID; String bDefLabel; String methDBID; String methodName; String parmRequired; String[] parmDomainValues; connection = m_pool.getConnection(); connection.setAutoCommit(false); // Insert Behavior Definition row bDefPID = bDefReader.GetObjectPID(); bDefLabel = bDefReader.GetObjectLabel(); insertBehaviorDefinitionRow(connection, bDefPID, bDefLabel, bDefReader.GetObjectState()); // Insert method rows bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID); if (bDefDBID == null) { throw new ReplicationException( "BehaviorDefinition row doesn't exist for PID: " + bDefPID); } behaviorDefs = bDefReader.getAbstractMethods(null); for (int i=0; i<behaviorDefs.length; ++i) { insertMethodRow(connection, bDefDBID, behaviorDefs[i].methodName, behaviorDefs[i].methodLabel); // Insert method parm rows methDBID = lookupMethodDBID(connection, bDefDBID, behaviorDefs[i].methodName); for (int j=0; j<behaviorDefs[i].methodParms.length; j++) { MethodParmDef[] methodParmDefs = new MethodParmDef[behaviorDefs[i].methodParms.length]; methodParmDefs = behaviorDefs[i].methodParms; parmRequired = methodParmDefs[j].parmRequired ? "true" : "false"; parmDomainValues = methodParmDefs[j].parmDomainValues; StringBuffer sb = new StringBuffer(); if (parmDomainValues != null && parmDomainValues.length > 0) { for (int k=0; k<parmDomainValues.length; k++) { if (k < parmDomainValues.length-1) { sb.append(parmDomainValues[k]+","); } else { sb.append(parmDomainValues[k]); } } } else { sb.append("null"); } insertMethodParmRow(connection, methDBID, bDefDBID, methodParmDefs[j].parmName, methodParmDefs[j].parmDefaultValue, sb.toString(), parmRequired, methodParmDefs[j].parmLabel, methodParmDefs[j].parmType); } } connection.commit(); } catch (ReplicationException re) { throw re; } catch (ServerException se) { throw new ReplicationException("Replication exception caused by " + "ServerException - " + se.getMessage()); } finally { if (connection!=null) { try { connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { connection.setAutoCommit(true); m_pool.free(connection); } } } } } /** * Replicates a Fedora behavior mechanism object. * * @param bMechReader behavior mechanism reader * @exception ReplicationException replication processing error * @exception SQLException JDBC, SQL error */ public void replicate(BMechReader bMechReader) throws ReplicationException, SQLException { if (!updateComponents(bMechReader)) { Connection connection=null; try { BMechDSBindSpec dsBindSpec; MethodDefOperationBind behaviorBindings[]; MethodDefOperationBind behaviorBindingsEntry; String bDefDBID; String bDefPID; String bMechDBID; String bMechPID; String bMechLabel; String dsBindingKeyDBID; String methodDBID; String ordinality_flag; String cardinality; String[] parmDomainValues; String parmRequired; connection = m_pool.getConnection(); connection.setAutoCommit(false); // Insert Behavior Mechanism row dsBindSpec = bMechReader.getServiceDSInputSpec(null); bDefPID = dsBindSpec.bDefPID; bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID); if (bDefDBID == null) { throw new ReplicationException("BehaviorDefinition row doesn't " + "exist for PID: " + bDefPID); } bMechPID = bMechReader.GetObjectPID(); bMechLabel = bMechReader.GetObjectLabel(); insertBehaviorMechanismRow(connection, bDefDBID, bMechPID, bMechLabel, bMechReader.GetObjectState()); // Insert dsBindSpec rows bMechDBID = lookupBehaviorMechanismDBID(connection, bMechPID); if (bMechDBID == null) { throw new ReplicationException("BehaviorMechanism row doesn't " + "exist for PID: " + bDefPID); } for (int i=0; i<dsBindSpec.dsBindRules.length; ++i) { // Convert from type boolean to type String ordinality_flag = dsBindSpec.dsBindRules[i].ordinality ? "true" : "false"; // Convert from type int to type String cardinality = Integer.toString( dsBindSpec.dsBindRules[i].maxNumBindings); insertDataStreamBindingSpecRow(connection, bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName, ordinality_flag, cardinality, dsBindSpec.dsBindRules[i].bindingLabel); // Insert dsMIME rows dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(connection, bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName); if (dsBindingKeyDBID == null) { throw new ReplicationException( "dsBindSpec row doesn't exist for " + "bMechDBID: " + bMechDBID + ", binding key name: " + dsBindSpec.dsBindRules[i].bindingKeyName); } for (int j=0; j<dsBindSpec.dsBindRules[i].bindingMIMETypes.length; ++j) { insertDataStreamMIMERow(connection, dsBindingKeyDBID, dsBindSpec.dsBindRules[i].bindingMIMETypes[j]); } } // Insert mechImpl rows behaviorBindings = bMechReader.getServiceMethodBindings(null); for (int i=0; i<behaviorBindings.length; ++i) { behaviorBindingsEntry = (MethodDefOperationBind)behaviorBindings[i]; if (!behaviorBindingsEntry.protocolType.equals("HTTP")) { // For the time being, ignore bindings other than HTTP. continue; } // Insert mechDefParm rows methodDBID = lookupMethodDBID(connection, bDefDBID, behaviorBindingsEntry.methodName); if (methodDBID == null) { throw new ReplicationException("Method row doesn't " + "exist for method name: " + behaviorBindingsEntry.methodName); } for (int j=0; j<behaviorBindings[i].methodParms.length; j++) { MethodParmDef[] methodParmDefs = new MethodParmDef[behaviorBindings[i].methodParms.length]; methodParmDefs = behaviorBindings[i].methodParms; //if (methodParmDefs[j].parmType.equalsIgnoreCase("fedora:defaultInputType")) if (methodParmDefs[j].parmType.equalsIgnoreCase(MethodParmDef.DEFAULT_INPUT)) { parmRequired = methodParmDefs[j].parmRequired ? "true" : "false"; parmDomainValues = methodParmDefs[j].parmDomainValues; StringBuffer sb = new StringBuffer(); if (parmDomainValues != null && parmDomainValues.length > 0) { for (int k=0; k<parmDomainValues.length; k++) { if (k < parmDomainValues.length-1) { sb.append(parmDomainValues[k]+","); } else { sb.append(parmDomainValues[k]); } } } else { if (sb.length() == 0) sb.append("null"); } insertMechDefaultMethodParmRow(connection, methodDBID, bMechDBID, methodParmDefs[j].parmName, methodParmDefs[j].parmDefaultValue, sb.toString(), parmRequired, methodParmDefs[j].parmLabel, methodParmDefs[j].parmType); } } for (int j=0; j<dsBindSpec.dsBindRules.length; ++j) { dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(connection, bMechDBID, dsBindSpec.dsBindRules[j].bindingKeyName); if (dsBindingKeyDBID == null) { throw new ReplicationException( "dsBindSpec " + "row doesn't exist for bMechDBID: " + bMechDBID + ", binding key name: " + dsBindSpec.dsBindRules[j].bindingKeyName); } for (int k=0; k<behaviorBindingsEntry.dsBindingKeys.length; k++) { // A row is added to the mechImpl table for each // method with a different BindingKeyName. In cases where // a single method may have multiple binding keys, // multiple rows are added for each different // BindingKeyName for that method. if (behaviorBindingsEntry.dsBindingKeys[k]. equalsIgnoreCase( dsBindSpec.dsBindRules[j].bindingKeyName)) { insertMechanismImplRow(connection, bMechDBID, bDefDBID, methodDBID, dsBindingKeyDBID, "http", "text/html", // sdp - local.fedora.server conversion encodeLocalURL(behaviorBindingsEntry.serviceBindingAddress), encodeLocalURL(behaviorBindingsEntry.operationLocation), "1"); } } } } connection.commit(); } catch (ReplicationException re) { re.printStackTrace(); throw re; } catch (ServerException se) { se.printStackTrace(); throw new ReplicationException( "Replication exception caused by ServerException - " + se.getMessage()); } finally { if (connection!=null) { try { connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { connection.setAutoCommit(true); m_pool.free(connection); } } } } } /** * Replicates a Fedora data object. * * @param doReader data object reader * @exception ReplicationException replication processing error * @exception SQLException JDBC, SQL error */ public void replicate(DOReader doReader) throws ReplicationException, SQLException { // Do updates only if the object already existed. boolean componentsUpdated=false; boolean componentsAdded=false; boolean componentsPurged=purgeComponents(doReader); logFinest("DefaultDOReplicator.replicate: ----- componentsPurged: "+componentsPurged); // Update operations are mutually exclusive if (!componentsPurged) { componentsUpdated=updateComponents(doReader); logFinest("DefaultDOReplicator.replicate: ----- componentsUpdated: "+componentsUpdated); if (!componentsUpdated) { // and do adds if the object already existed componentsAdded=addNewComponents(doReader); logFinest("DefaultDOReplicator.replicate: ----- newComponentsAdded: "+componentsAdded); } } if ( !componentsUpdated && !componentsAdded && !componentsPurged ) { // Object is New Connection connection=null; logFinest("DefaultDOReplicator.replicate: ----- New Object"); try { DSBindingMapAugmented[] allBindingMaps; Disseminator disseminators[]; String bDefDBID; String bindingMapDBID; String bMechDBID; String dissDBID; String doDBID; String doPID; String doLabel; String dsBindingKeyDBID; int rc; doPID = doReader.GetObjectPID(); connection = m_pool.getConnection(); connection.setAutoCommit(false); // Insert Digital Object row doPID = doReader.GetObjectPID(); doLabel = doReader.GetObjectLabel(); insertDigitalObjectRow(connection, doPID, doLabel, doReader.GetObjectState()); doDBID = lookupDigitalObjectDBID(connection, doPID); if (doDBID == null) { throw new ReplicationException("do row doesn't " + "exist for PID: " + doPID); } // add disseminator components (which include associated datastream components) disseminators = doReader.GetDisseminators(null, null); addDisseminators(doPID, disseminators, doReader, connection); connection.commit(); } catch (ReplicationException re) { re.printStackTrace(); throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + re.getClass().getName() + " \". The cause was \" " + re.getMessage() + " \""); } catch (ServerException se) { se.printStackTrace(); throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } finally { if (connection!=null) { try { connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { connection.setAutoCommit(true); m_pool.free(connection); } } } } } private ResultSet logAndExecuteQuery(Statement statement, String sql) throws SQLException { logFinest("Executing query: " + sql); return statement.executeQuery(sql); } private int logAndExecuteUpdate(Statement statement, String sql) throws SQLException { logFinest("Executing update: " + sql); return statement.executeUpdate(sql); } /** * Gets a string suitable for a SQL WHERE clause, of the form * <b>x=y1 or x=y2 or x=y3</b>...etc, where x is the value from the * column, and y1 is composed of the integer values from the given set. * <p></p> * If the set doesn't contain any items, returns a condition that * always evaluates to false, <b>1=2</b>. * * @param column value of the column. * @param integers set of integers. * @return string suitable for SQL WHERE clause. */ private String inIntegerSetWhereConditionString(String column, Set integers) { StringBuffer out=new StringBuffer(); Iterator iter=integers.iterator(); int n=0; while (iter.hasNext()) { if (n>0) { out.append(" OR "); } out.append(column); out.append('='); int i=((Integer) iter.next()).intValue(); out.append(i); n++; } if (n>0) { return out.toString(); } else { return "1=2"; } } /** * Deletes all rows pertinent to the given behavior definition object, * if they exist. * <p></p> * Pseudocode: * <ul><pre> * $bDefDbID=SELECT bDefDbID FROM bDef WHERE bDefPID=$PID * DELETE FROM bDef,method,parm * WHERE bDefDbID=$bDefDbID * </pre></ul> * * @param connection a database connection. * @param pid the idenitifer of a digital object. * @throws SQLException If something totally unexpected happened. */ private void deleteBehaviorDefinition(Connection connection, String pid) throws SQLException { logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Entering -----"); Statement st=null; ResultSet results=null; try { st=connection.createStatement(); // // READ // logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Checking BehaviorDefinition table for " + pid + "..."); results=logAndExecuteQuery(st, "SELECT bDefDbID FROM " + "bDef WHERE bDefPID='" + pid + "'"); if (!results.next()) { // must not be a bdef...exit early logFinest("DefaultDOReplicator.deleteBehaviorDefinition: " + pid + " wasn't found in BehaviorDefinition table..." + "skipping deletion as such."); return; } int dbid=results.getInt("bDefDbID"); logFinest("DefaultDOReplicator.deleteBehaviorDefinition: " + pid + " was found in BehaviorDefinition table (DBID=" + dbid + ")"); // // WRITE // int rowCount; logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Attempting row deletion from BehaviorDefinition " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM bDef " + "WHERE bDefDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Attempting row deletion from method table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM method WHERE " + "bDefDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Attempting row deletion from parm table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM parm WHERE " + "bDefDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Deleted " + rowCount + " row(s)."); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); } catch (SQLException sqle) { } finally { results=null; st=null; logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Exiting -----"); } } } /** * Deletes all rows pertinent to the given behavior mechanism object, * if they exist. * <p></p> * Pseudocode: * <ul><pre> * $bMechDbID=SELECT bMechDbID * FROM bMech WHERE bMechPID=$PID * bMech * @BKEYIDS=SELECT dsBindKeyDbID * FROM dsBindSpec * WHERE bMechDbID=$bMechDbID * dsMIME WHERE dsBindKeyDbID in @BKEYIDS * mechImpl * </pre></ul> * * @param connection a database connection. * @param pid the identifier of a digital object. * @throws SQLException If something totally unexpected happened. */ private void deleteBehaviorMechanism(Connection connection, String pid) throws SQLException { logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Entering -----"); Statement st=null; ResultSet results=null; try { st=connection.createStatement(); // // READ // logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Checking bMech table for " + pid + "..."); //results=logAndExecuteQuery(st, "SELECT bMechDbID, SMType_DBID " results=logAndExecuteQuery(st, "SELECT bMechDbID " + "FROM bMech WHERE bMechPID='" + pid + "'"); if (!results.next()) { // must not be a bmech...exit early logFinest("DefaultDOReplicator.deleteBehaviorMechanism: " + pid + " wasn't found in bMech table..." + "skipping deletion as such."); return; } int dbid=results.getInt("bMechDbID"); //int smtype_dbid=results.getInt("bMechDbID"); results.close(); results=null; logFinest("DefaultDOReplicator.deleteBehaviorMechanism:" + pid + " was found in bMech table (DBID=" // + dbid + ", SMTYPE_DBID=" + smtype_dbid + ")"); + dbid); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Getting dsBindKeyDbID(s) from dsBindSpec " + "table..."); HashSet dsBindingKeyIds=new HashSet(); results=logAndExecuteQuery(st, "SELECT dsBindKeyDbID from " + "dsBindSpec WHERE bMechDbID=" + dbid); while (results.next()) { dsBindingKeyIds.add(new Integer( results.getInt("dsBindKeyDbID"))); } results.close(); results=null; logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Found " + dsBindingKeyIds.size() + " dsBindKeyDbID(s)."); // // WRITE // int rowCount; logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from bMech table.."); rowCount=logAndExecuteUpdate(st, "DELETE FROM bMech " + "WHERE bMechDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from dsBindSpec " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM " + "dsBindSpec WHERE bMechDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from dsMIME table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsMIME WHERE " + inIntegerSetWhereConditionString("dsBindKeyDbID", dsBindingKeyIds)); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s)."); //logFinest("Attempting row deletion from StructMapType table..."); //rowCount=logAndExecuteUpdate(st, "DELETE FROM StructMapType WHERE " // + "SMType_DBID=" + smtype_dbid); //logFinest("Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from dsBindMap table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE " + "bMechDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from mechImpl table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM mechImpl WHERE " + "bMechDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from mechDefParm table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM mechDefParm " + "WHERE bMechDbID=" + dbid); logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s)."); } finally { try { if (results != null) results.close(); if (st!=null)st.close(); } catch (SQLException sqle) { } finally { results=null; st=null; logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Exiting -----"); } } } /** * Deletes all rows pertinent to the given digital object (treated as a * data object) if they exist. * <p></p> * Pseudocode: * <ul><pre> * $doDbID=SELECT doDbID FROM do where doPID=$PID * @DISSIDS=SELECT dissDbID * FROM doDissAssoc WHERE doDbID=$doDbID * @BMAPIDS=SELECT dsBindMapDbID * FROM dsBind WHERE doDbID=$doDbID * do * doDissAssoc where $doDbID=doDbID * dsBind WHERE $doDbID=doDbID * diss WHERE dissDbID in @DISSIDS * dsBindMap WHERE dsBindMapDbID in @BMAPIDS * </pre></ul> * * @param connection a databae connection. * @param pid the identifier for a digital object. * @throws SQLException If something totally unexpected happened. */ private void deleteDigitalObject(Connection connection, String pid) throws SQLException { logFinest("DefaultDOReplicator.deleteDigitalObject: Entering -----"); Statement st=null; Statement st2=null; Statement st3=null; ResultSet results=null; try { st=connection.createStatement(); // // READ // logFinest("DefaultDOReplicator.deleteDigitalObject: Checking do table for " + pid + "..."); results=logAndExecuteQuery(st, "SELECT doDbID FROM " + "do WHERE doPID='" + pid + "'"); if (!results.next()) { // must not be a digitalobject...exit early logFinest("DefaultDOReplicator.deleteDigitalObject: " + pid + " wasn't found in do table..." + "skipping deletion as such."); return; } int dbid=results.getInt("doDbID"); results.close(); results=null; logFinest("DefaultDOReplicator.deleteDigitalObject: " + pid + " was found in do table (DBID=" + dbid + ")"); logFinest("DefaultDOReplicator.deleteDigitalObject: Getting dissDbID(s) from doDissAssoc " + "table..."); HashSet dissIds=new HashSet(); HashSet dissIdsNotShared = new HashSet(); // Get all dissIds in db for this object results=logAndExecuteQuery(st, "SELECT dissDbID from " + "doDissAssoc WHERE doDbID=" + dbid); while (results.next()) { dissIds.add(new Integer(results.getInt("dissDbID"))); } results.close(); results=null; logFinest("DefaultDOReplicator.deleteDigitalObject: Found " + dissIds.size() + " dissDbID(s)."); logFinest("DefaultDOReplicator.deleteDigitalObject: Getting dissDbID(s) from doDissAssoc " + "table unique to this object..."); Iterator iterator = dissIds.iterator(); // Iterate over dissIds and separate those that are unique // (i.e., not shared by other objects) while (iterator.hasNext()) { Integer id = (Integer)iterator.next(); logFinest("DefaultDOReplicator.deleteDigitalObject: Getting occurrences of dissDbID(s) in " + "doDissAssoc table..."); results=logAndExecuteQuery(st, "SELECT COUNT(*) from " + "doDissAssoc WHERE dissDbID=" + id); while (results.next()) { Integer i1 = new Integer(results.getInt("COUNT(*)")); if ( i1.intValue() == 1 ) { // A dissDbID that occurs only once indicates that the // disseminator is not used by other objects. In this case, we // want to keep track of this dissDbID. dissIdsNotShared.add(id); logFinest("DefaultDOReplicator.deleteDigitalObject: added " + "dissDbId that was not shared: " + id); } } results.close(); results=null; } // Get all binding map Ids in db for this object. HashSet bmapIds=new HashSet(); results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM " + "dsBind WHERE doDbID=" + dbid); while (results.next()) { bmapIds.add(new Integer(results.getInt("dsBindMapDbID"))); } results.close(); results=null; logFinest("DefaultDOReplicator.deleteDigitalObject: Found " + bmapIds.size() + " dsBindMapDbID(s)."); // Iterate over bmapIds and separate those that are unique // (i.e., not shared by other objects) iterator = bmapIds.iterator(); HashSet bmapIdsNotShared = new HashSet(); while (iterator.hasNext() ) { Integer id = (Integer)iterator.next(); ResultSet rs = null; logFinest("DefaultDOReplicator.deleteDigitalObject: Getting associated bmapId(s) that are unique " + "for this object in diss table..."); st2 = connection.createStatement(); rs=logAndExecuteQuery(st2, "SELECT DISTINCT doDbID FROM " + "dsBind WHERE dsBindMapDbID=" + id); int rowCount = 0; while (rs.next()) { rowCount++; } if ( rowCount == 1 ) { // A bmapId that occurs only once indicates that // a bmapId is not used by other objects. In this case, we // want to keep track of this bpamId. bmapIdsNotShared.add(id); logFinest("DefaultDOReplicator.deleteDigitalObject: added " + "dsBindMapDbId that was not shared: " + id); } rs.close(); rs=null; st2.close(); st2=null; } // // WRITE // int rowCount; logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from do table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM do " + "WHERE doDbID=" + dbid); logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from doDissAssoc " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM " + "doDissAssoc WHERE doDbID=" + dbid); logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from dsBind table.."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind " + "WHERE doDbID=" + dbid); logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s)."); // Since dissIds can be shared by other objects in db, only remove // those Ids that are not shared. logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from diss table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE " + inIntegerSetWhereConditionString("dissDbID", dissIdsNotShared)); logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s)."); logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from dsBindMap " + "table..."); // Since bmapIds can be shared by other objects in db, only remove // thos Ids that are not shared. rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap " + "WHERE " + inIntegerSetWhereConditionString( "dsBindMapDbID", bmapIdsNotShared)); logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s)."); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); if (st2!=null) st2.close(); } catch (SQLException sqle) { } finally { results=null; st=null; st2=null; logFinest("DefaultDOReplicator.deleteDigitalObject: Exiting -----"); } } } /** * Removes a digital object from the dissemination database. * <p></p> * If the object is a behavior definition or mechanism, it's deleted * as such, and then an attempt is made to delete it as a data object * as well. * <p></p> * Note that this does not do cascading check object dependencies at * all. It is expected at this point that when this is called, any * referencial integrity issues have been ironed out or checked as * appropriate. * <p></p> * All deletions happen in a transaction. If any database errors occur, * the change is rolled back. * * @param pid The pid of the object to delete. * @throws ReplicationException If the request couldn't be fulfilled for * any reason. */ public void delete(String pid) throws ReplicationException { logFinest("DefaultDOReplicator.delete: Entering -----"); Connection connection=null; try { connection = m_pool.getConnection(); connection.setAutoCommit(false); deleteBehaviorDefinition(connection, pid); deleteBehaviorMechanism(connection, pid); deleteDigitalObject(connection, pid); connection.commit(); } catch (SQLException sqle) { throw new ReplicationException("Error while replicator was trying " + "to delete " + pid + ". " + sqle.getMessage()); } finally { if (connection!=null) { try { connection.rollback(); connection.setAutoCommit(true); m_pool.free(connection); } catch (SQLException sqle) {} } logFinest("DefaultDOReplicator.delete: Exiting -----"); } } /** * * Inserts a Behavior Definition row. * * @param connection JDBC DBMS connection * @param bDefPID Behavior definition PID * @param bDefLabel Behavior definition label * @param bDefState State of behavior definition object. * * @exception SQLException JDBC, SQL error */ public void insertBehaviorDefinitionRow(Connection connection, String bDefPID, String bDefLabel, String bDefState) throws SQLException { String insertionStatement = "INSERT INTO bDef (bDefPID, bDefLabel, bDefState) VALUES ('" + bDefPID + "', '" + SQLUtility.aposEscape(bDefLabel) + "', '" + bDefState + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a Behavior Mechanism row. * * @param connection JDBC DBMS connection * @param bDefDbID Behavior definition DBID * @param bMechPID Behavior mechanism DBID * @param bMechLabel Behavior mechanism label * @param bMechState Statye of behavior mechanism object. * * @throws SQLException JDBC, SQL error */ public void insertBehaviorMechanismRow(Connection connection, String bDefDbID, String bMechPID, String bMechLabel, String bMechState) throws SQLException { String insertionStatement = "INSERT INTO bMech (bDefDbID, bMechPID, bMechLabel, bMechState) VALUES ('" + bDefDbID + "', '" + bMechPID + "', '" + SQLUtility.aposEscape(bMechLabel) + "', '" + bMechState + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a DataStreamBindingRow row. * * @param connection JDBC DBMS connection * @param doDbID Digital object DBID * @param dsBindKeyDbID Datastream binding key DBID * @param dsBindMapDbID Binding map DBID * @param dsBindKeySeq Datastream binding key sequence number * @param dsID Datastream ID * @param dsLabel Datastream label * @param dsMIME Datastream mime type * @param dsLocation Datastream location * @param dsControlGroupType Datastream type * @param dsCurrentVersionID Datastream current version ID * @param policyDbID Policy DBID * @param dsState State of datastream. * * @exception SQLException JDBC, SQL error */ public void insertDataStreamBindingRow(Connection connection, String doDbID, String dsBindKeyDbID, String dsBindMapDbID, String dsBindKeySeq, String dsID, String dsLabel, String dsMIME, String dsLocation, String dsControlGroupType, String dsCurrentVersionID, String policyDbID, String dsState) throws SQLException { if (dsBindKeySeq == null || dsBindKeySeq.equals("")) dsBindKeySeq = "0"; String insertionStatement = "INSERT INTO dsBind (doDbID, dsBindKeyDbID, dsBindMapDbID, dsBindKeySeq, dsID, dsLabel, dsMIME, dsLocation, dsControlGroupType, dsCurrentVersionID, policyDbID, dsState) VALUES ('" + doDbID + "', '" + dsBindKeyDbID + "', '" + dsBindMapDbID + "', '" + dsBindKeySeq + "', '" + dsID + "', '" + SQLUtility.aposEscape(dsLabel) + "', '" + dsMIME + "', '" + SQLUtility.aposEscape(dsLocation) + "', '" + dsControlGroupType + "', '" + dsCurrentVersionID + "', '" + policyDbID + "', '" + dsState + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a dsBindMap row. * * @param connection JDBC DBMS connection * @param bMechDbID Behavior mechanism DBID * @param dsBindMapID Datastream binding map ID * @param dsBindMapLabel Datastream binding map label * * @exception SQLException JDBC, SQL error */ public void insertDataStreamBindingMapRow(Connection connection, String bMechDbID, String dsBindMapID, String dsBindMapLabel) throws SQLException { String insertionStatement = "INSERT INTO dsBindMap (bMechDbID, dsBindMapID, dsBindMapLabel) VALUES ('" + bMechDbID + "', '" + dsBindMapID + "', '" + SQLUtility.aposEscape(dsBindMapLabel) + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a dsBindSpec row. * * @param connection JDBC DBMS connection * @param bMechDbID Behavior mechanism DBID * @param dsBindSpecName Datastream binding spec name * @param dsBindSpecOrdinality Datastream binding spec ordinality flag * @param dsBindSpecCardinality Datastream binding cardinality * @param dsBindSpecLabel Datastream binding spec lable * * @exception SQLException JDBC, SQL error */ public void insertDataStreamBindingSpecRow(Connection connection, String bMechDbID, String dsBindSpecName, String dsBindSpecOrdinality, String dsBindSpecCardinality, String dsBindSpecLabel) throws SQLException { String insertionStatement = "INSERT INTO dsBindSpec (bMechDbID, dsBindSpecName, dsBindSpecOrdinality, dsBindSpecCardinality, dsBindSpecLabel) VALUES ('" + bMechDbID + "', '" + SQLUtility.aposEscape(dsBindSpecName) + "', '" + dsBindSpecOrdinality + "', '" + dsBindSpecCardinality + "', '" + SQLUtility.aposEscape(dsBindSpecLabel) + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a dsMIME row. * * @param connection JDBC DBMS connection * @param dsBindKeyDbID Datastream binding key DBID * @param dsMIMEName Datastream MIME type name * * @exception SQLException JDBC, SQL error */ public void insertDataStreamMIMERow(Connection connection, String dsBindKeyDbID, String dsMIMEName) throws SQLException { String insertionStatement = "INSERT INTO dsMIME (dsBindKeyDbID, dsMIMEName) VALUES ('" + dsBindKeyDbID + "', '" + dsMIMEName + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a do row. * * @param connection JDBC DBMS connection * @param doPID DigitalObject PID * @param doLabel DigitalObject label * @param doState State of digital object. * * @exception SQLException JDBC, SQL error */ public void insertDigitalObjectRow(Connection connection, String doPID, String doLabel, String doState) throws SQLException { String insertionStatement = "INSERT INTO do (doPID, doLabel, doState) VALUES ('" + doPID + "', '" + SQLUtility.aposEscape(doLabel) + "', '" + doState + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a doDissAssoc row. * * @param connection JDBC DBMS connection * @param doDbID DigitalObject DBID * @param dissDbID Disseminator DBID * * @exception SQLException JDBC, SQL error */ public void insertDigitalObjectDissAssocRow(Connection connection, String doDbID, String dissDbID) throws SQLException { String insertionStatement = "INSERT INTO doDissAssoc (doDbID, dissDbID) VALUES ('" + doDbID + "', '" + dissDbID + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a Disseminator row. * * @param connection JDBC DBMS connection * @param bDefDbID Behavior definition DBID * @param bMechDbID Behavior mechanism DBID * @param dissID Disseminator ID * @param dissLabel Disseminator label * @param dissState State of disseminator. * * @exception SQLException JDBC, SQL error */ public void insertDisseminatorRow(Connection connection, String bDefDbID, String bMechDbID, String dissID, String dissLabel, String dissState) throws SQLException { String insertionStatement = "INSERT INTO diss (bDefDbID, bMechDbID, dissID, dissLabel, dissState) VALUES ('" + bDefDbID + "', '" + bMechDbID + "', '" + dissID + "', '" + SQLUtility.aposEscape(dissLabel) + "', '" + dissState + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a mechImpl row. * * @param connection JDBC DBMS connection * @param bMechDbID Behavior mechanism DBID * @param bDefDbID Behavior definition DBID * @param methodDbID Method DBID * @param dsBindKeyDbID Datastream binding key DBID * @param protocolType Mechanism implementation protocol type * @param returnType Mechanism implementation return type * @param addressLocation Mechanism implementation address location * @param operationLocation Mechanism implementation operation location * @param policyDbID Policy DBID * * @exception SQLException JDBC, SQL error */ public void insertMechanismImplRow(Connection connection, String bMechDbID, String bDefDbID, String methodDbID, String dsBindKeyDbID, String protocolType, String returnType, String addressLocation, String operationLocation, String policyDbID) throws SQLException { String insertionStatement = "INSERT INTO mechImpl (bMechDbID, bDefDbID, methodDbID, dsBindKeyDbID, protocolType, returnType, addressLocation, operationLocation, policyDbID) VALUES ('" + bMechDbID + "', '" + bDefDbID + "', '" + methodDbID + "', '" + dsBindKeyDbID + "', '" + protocolType + "', '" + returnType + "', '" + addressLocation + "', '" + operationLocation + "', '" + policyDbID + "')"; insertGen(connection, insertionStatement); } /** * * Inserts a method row. * * @param connection JDBC DBMS connection * @param bDefDbID Behavior definition DBID * @param methodName Behavior definition label * @param methodLabel Behavior definition label * * @exception SQLException JDBC, SQL error */ public void insertMethodRow(Connection connection, String bDefDbID, String methodName, String methodLabel) throws SQLException { String insertionStatement = "INSERT INTO method (bDefDbID, methodName, methodLabel) VALUES ('" + bDefDbID + "', '" + SQLUtility.aposEscape(methodName) + "', '" + SQLUtility.aposEscape(methodLabel) + "')"; insertGen(connection, insertionStatement); } /** * * @param connection An SQL Connection. * @param methDBID The method database ID. * @param bdefDBID The behavior Definition object database ID. * @param parmName the parameter name. * @param parmDefaultValue A default value for the parameter. * @param parmDomainValues A list of possible values for the parameter. * @param parmRequiredFlag A boolean flag indicating whether the * parameter is required or not. * @param parmLabel The parameter label. * @param parmType The parameter type. * @throws SQLException JDBC, SQL error */ public void insertMethodParmRow(Connection connection, String methDBID, String bdefDBID, String parmName, String parmDefaultValue, String parmDomainValues, String parmRequiredFlag, String parmLabel, String parmType) throws SQLException { String insertionStatement = "INSERT INTO parm " + "(methodDbID, bDefDbID, parmName, parmDefaultValue, " + "parmDomainValues, parmRequiredFlag, parmLabel, " + "parmType) VALUES ('" + methDBID + "', '" + bdefDBID + "', '" + SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '" + SQLUtility.aposEscape(parmDomainValues) + "', '" + parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '" + parmType + "')"; insertGen(connection, insertionStatement); } /** * * @param connection An SQL Connection. * @param methDBID The method database ID. * @param bmechDBID The behavior Mechanism object database ID. * @param parmName the parameter name. * @param parmDefaultValue A default value for the parameter. * @param parmRequiredFlag A boolean flag indicating whether the * parameter is required or not. * @param parmDomainValues A list of possible values for the parameter. * @param parmLabel The parameter label. * @param parmType The parameter type. * @throws SQLException JDBC, SQL error */ public void insertMechDefaultMethodParmRow(Connection connection, String methDBID, String bmechDBID, String parmName, String parmDefaultValue, String parmDomainValues, String parmRequiredFlag, String parmLabel, String parmType) throws SQLException { String insertionStatement = "INSERT INTO mechDefParm " + "(methodDbID, bMechDbID, defParmName, defParmDefaultValue, " + "defParmDomainValues, defParmRequiredFlag, defParmLabel, " + "defParmType) VALUES ('" + methDBID + "', '" + bmechDBID + "', '" + SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '" + SQLUtility.aposEscape(parmDomainValues) + "', '" + parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '" + parmType + "')"; insertGen(connection, insertionStatement); } /** * * General JDBC row insertion method. * * @param connection JDBC DBMS connection * @param insertionStatement SQL row insertion statement * * @exception SQLException JDBC, SQL error */ public void insertGen(Connection connection, String insertionStatement) throws SQLException { int rowCount = 0; Statement statement = null; statement = connection.createStatement(); logFinest("Doing DB Insert: " + insertionStatement); rowCount = statement.executeUpdate(insertionStatement); statement.close(); statement=null; } /** * * Looks up a BehaviorDefinition DBID. * * @param connection JDBC DBMS connection * @param bDefPID Behavior definition PID * * @return The DBID of the specified Behavior Definition row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupBehaviorDefinitionDBID(Connection connection, String bDefPID) throws StorageDeviceException { return lookupDBID1(connection, "bDefDbID", "bDef", "bDefPID", bDefPID); } /** * * Looks up a BehaviorMechanism DBID. * * @param connection JDBC DBMS connection * @param bMechPID Behavior mechanism PID * * @return The DBID of the specified Behavior Mechanism row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupBehaviorMechanismDBID(Connection connection, String bMechPID) throws StorageDeviceException { return lookupDBID1(connection, "bMechDbID", "bMech", "bMechPID", bMechPID); } /** * * Looks up a dsBindMap DBID. * * @param connection JDBC DBMS connection * @param bMechDBID Behavior mechanism DBID * @param dsBindingMapID Data stream binding map ID * * @return The DBID of the specified dsBindMap row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupDataStreamBindingMapDBID(Connection connection, String bMechDBID, String dsBindingMapID) throws StorageDeviceException { return lookupDBID2FirstNum(connection, "dsBindMapDbID", "dsBindMap", "bMechDbID", bMechDBID, "dsBindMapID", dsBindingMapID); } public String lookupDataStreamBinding(Connection connection, String doDbID, String dsBindKeyDbID, String dsBindMapDbID, String dsBindKeySeq, String dsID, String dsLocation, String dsState) throws StorageDeviceException { return lookupDBID4(connection, "dsID", "dsBind", "doDbID", doDbID, "dsBindKeyDbID", dsBindKeyDbID, "dsBindMapDbID", dsBindMapDbID, "dsBindKeySeq", dsBindKeySeq, "dsID", dsID, "dsLocation", dsLocation, "dsState", dsState); } //public String lookupDsBindingMapDBID(Connection connection, String bMechDBID, String dsBindingMapID) throws StorageDeviceException { // return lookupDBID2FirstNum(connection, "dsBindMapDbID", "dsBindMap", "bMechDbID", bMechDBID, "dsBindMapID", dsBindingMapID); //} /** * * Looks up a dsBindSpec DBID. * * @param connection JDBC DBMS connection * @param bMechDBID Behavior mechanism DBID * @param dsBindingSpecName Data stream binding spec name * * @return The DBID of the specified dsBindSpec row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupDataStreamBindingSpecDBID(Connection connection, String bMechDBID, String dsBindingSpecName) throws StorageDeviceException { return lookupDBID2FirstNum(connection, "dsBindKeyDbID", "dsBindSpec", "bMechDbID", bMechDBID, "dsBindSpecName", dsBindingSpecName); } /** * * Looks up a do DBID. * * @param connection JDBC DBMS connection * @param doPID Data object PID * * @return The DBID of the specified DigitalObject row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupDigitalObjectDBID(Connection connection, String doPID) throws StorageDeviceException { return lookupDBID1(connection, "doDbID", "do", "doPID", doPID); } /** * * Looks up a Disseminator DBID. * * @param connection JDBC DBMS connection * @param bDefDBID Behavior definition DBID * @param bMechDBID Behavior mechanism DBID * @param dissID Disseminator ID * * @return The DBID of the specified Disseminator row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupDisseminatorDBID(Connection connection, String bDefDBID, String bMechDBID, String dissID) throws StorageDeviceException { Statement statement = null; ResultSet rs = null; String query = null; String ID = null; try { query = "SELECT dissDbID FROM diss WHERE "; query += "bDefDbID = " + bDefDBID + " AND "; query += "bMechDbID = " + bMechDBID + " AND "; query += "dissID = '" + dissID + "'"; logFinest("Doing Query: " + query); statement = connection.createStatement(); rs = statement.executeQuery(query); while (rs.next()) ID = rs.getString(1); } catch (Throwable th) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + th.getClass().getName() + " \". The cause was \" " + th.getMessage() + " \""); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException sqle) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage() + " \""); } finally { rs=null; statement=null; } } return ID; } /** * * Looks up a method DBID. * * @param connection JDBC DBMS connection * @param bDefDBID Behavior definition DBID * @param methName Method name * * @return The DBID of the specified method row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupMethodDBID(Connection connection, String bDefDBID, String methName) throws StorageDeviceException { return lookupDBID2FirstNum(connection, "methodDbID", "method", "bDefDbID", bDefDBID, "methodName", methName); } /** * * General JDBC lookup method with 1 lookup column value. * * @param connection JDBC DBMS connection * @param DBIDName DBID column name * @param tableName Table name * @param lookupColumnName Lookup column name * @param lookupColumnValue Lookup column value * * @return The DBID of the specified row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupDBID1(Connection connection, String DBIDName, String tableName, String lookupColumnName, String lookupColumnValue) throws StorageDeviceException { String query = null; String ID = null; Statement statement = null; ResultSet rs = null; try { query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE "; query += lookupColumnName + " = '" + lookupColumnValue + "'"; logFinest("Doing Query: " + query); statement = connection.createStatement(); rs = statement.executeQuery(query); while (rs.next()) ID = rs.getString(1); } catch (Throwable th) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + th.getClass().getName() + " \". The cause was \" " + th.getMessage() + " \""); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException sqle) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage() + " \""); } finally { rs=null; statement=null; } } return ID; } /** * * General JDBC lookup method with 2 lookup column values. * * @param connection JDBC DBMS connection * @param DBIDName DBID Column name * @param tableName Table name * @param lookupColumnName1 First lookup column name * @param lookupColumnValue1 First lookup column value * @param lookupColumnName2 Second lookup column name * @param lookupColumnValue2 Second lookup column value * * @return The DBID of the specified row. * * @throws StorageDeviceException if db lookup fails for any reason. */ public String lookupDBID2(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException { String query = null; String ID = null; Statement statement = null; ResultSet rs = null; try { query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE "; query += lookupColumnName1 + " = '" + lookupColumnValue1 + "' AND "; query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'"; logFinest("Doing Query: " + query); statement = connection.createStatement(); rs = statement.executeQuery(query); while (rs.next()) ID = rs.getString(1); } catch (Throwable th) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + th.getClass().getName() + " \". The cause was \" " + th.getMessage() + " \""); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException sqle) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage() + " \""); } finally { rs=null; statement=null; } } return ID; } public String lookupDBID4(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2, String lookupColumnName3, String lookupColumnValue3, String lookupColumnName4, String lookupColumnValue4, String lookupColumnName5, String lookupColumnValue5, String lookupColumnName6, String lookupColumnValue6, String lookupColumnName7, String lookupColumnValue7) throws StorageDeviceException { String query = null; String ID = null; Statement statement = null; ResultSet rs = null; try { query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE "; query += lookupColumnName1 + " =" + lookupColumnValue1 + " AND "; query += lookupColumnName2 + " =" + lookupColumnValue2 + " AND "; query += lookupColumnName3 + " =" + lookupColumnValue3 + " AND "; query += lookupColumnName4 + " =" + lookupColumnValue4 + " AND "; query += lookupColumnName5 + " ='" + lookupColumnValue5 + "' AND "; query += lookupColumnName6 + " ='" + lookupColumnValue6 + "' AND "; query += lookupColumnName7 + " ='" + lookupColumnValue7 + "'"; logFinest("Doing Query: " + query); statement = connection.createStatement(); rs = statement.executeQuery(query); while (rs.next()) ID = rs.getString(1); } catch (Throwable th) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + th.getClass().getName() + " \". The cause was \" " + th.getMessage() + " \""); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException sqle) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage() + " \""); } finally { rs=null; statement=null; } } return ID; } public String lookupDBID2FirstNum(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException { String query = null; String ID = null; Statement statement = null; ResultSet rs = null; try { query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE "; query += lookupColumnName1 + " =" + lookupColumnValue1 + " AND "; query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'"; logFinest("Doing Query: " + query); statement = connection.createStatement(); rs = statement.executeQuery(query); while (rs.next()) ID = rs.getString(1); } catch (Throwable th) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + th.getClass().getName() + " \". The cause was \" " + th.getMessage() + " \""); } finally { try { if (rs != null) rs.close(); if (statement != null) statement.close(); } catch (SQLException sqle) { throw new StorageDeviceException("[DBIDLookup] An error has " + "occurred. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage() + " \""); } finally { rs=null; statement=null; } } return ID; } private String encodeLocalURL(String locationString) { // Replace any occurences of the host:port of the local Fedora // server with the internal serialization string "local.fedora.server." // This will make sure that local URLs (self-referential to the // local server) will be recognizable if the server host and // port configuration changes after an object is stored in the // repository. if (fedoraServerPort.equalsIgnoreCase("80") && hostPattern.matcher(locationString).find()) { //System.out.println("port is 80 and host-only pattern found - convert to l.f.s"); return hostPattern.matcher( locationString).replaceAll("http://local.fedora.server/"); } else { //System.out.println("looking for hostPort pattern to convert to l.f.s"); return hostPortPattern.matcher( locationString).replaceAll("http://local.fedora.server/"); } } private String unencodeLocalURL(String storedLocationString) { // Replace any occurrences of the internal serialization string // "local.fedora.server" with the current host and port of the // local Fedora server. This translates local URLs (self-referential // to the local server) back into resolvable URLs that reflect // the currently configured host and port for the server. if (fedoraServerPort.equalsIgnoreCase("80")) { return serializedLocalURLPattern.matcher( storedLocationString).replaceAll(fedoraServerHost); } else { return serializedLocalURLPattern.matcher( storedLocationString).replaceAll( fedoraServerHost+":"+fedoraServerPort); } } private void addDisseminators(String doPID, Disseminator[] disseminators, DOReader doReader, Connection connection) throws ReplicationException, SQLException, ServerException { DSBindingMapAugmented[] allBindingMaps; String bDefDBID; String bindingMapDBID; String bMechDBID; String dissDBID; String doDBID; String doLabel; String dsBindingKeyDBID; int rc; logFinest("DefaultDOReplicator.addDisseminators: Entering ------"); doDBID = lookupDigitalObjectDBID(connection, doPID); for (int i=0; i<disseminators.length; ++i) { bDefDBID = lookupBehaviorDefinitionDBID(connection, disseminators[i].bDefID); if (bDefDBID == null) { throw new ReplicationException("BehaviorDefinition row " + "doesn't exist for PID: " + disseminators[i].bDefID); } bMechDBID = lookupBehaviorMechanismDBID(connection, disseminators[i].bMechID); if (bMechDBID == null) { throw new ReplicationException("BehaviorMechanism row " + "doesn't exist for PID: " + disseminators[i].bMechID); } // Insert Disseminator row if it doesn't exist. dissDBID = lookupDisseminatorDBID(connection, bDefDBID, bMechDBID, disseminators[i].dissID); if (dissDBID == null) { // Disseminator row doesn't exist, add it. insertDisseminatorRow(connection, bDefDBID, bMechDBID, disseminators[i].dissID, disseminators[i].dissLabel, disseminators[i].dissState); //insertDisseminatorRow(connection, bDefDBID, bMechDBID, //disseminators[i].dissID, disseminators[i].dissLabel, disseminators[i].dissState, disseminators[i].dsBindMapID); dissDBID = lookupDisseminatorDBID(connection, bDefDBID, bMechDBID, disseminators[i].dissID); if (dissDBID == null) { throw new ReplicationException("diss row " + "doesn't exist for PID: " + disseminators[i].dissID); } } // Insert doDissAssoc row insertDigitalObjectDissAssocRow(connection, doDBID, dissDBID); } allBindingMaps = doReader.GetDSBindingMaps(null); for (int i=0; i<allBindingMaps.length; ++i) { bMechDBID = lookupBehaviorMechanismDBID(connection, allBindingMaps[i].dsBindMechanismPID); if (bMechDBID == null) { throw new ReplicationException("BehaviorMechanism row " + "doesn't exist for PID: " + allBindingMaps[i].dsBindMechanismPID); } // Insert dsBindMap row if it doesn't exist. bindingMapDBID = lookupDataStreamBindingMapDBID(connection, bMechDBID, allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { // DataStreamBinding row doesn't exist, add it. insertDataStreamBindingMapRow(connection, bMechDBID, allBindingMaps[i].dsBindMapID, allBindingMaps[i].dsBindMapLabel); bindingMapDBID = lookupDataStreamBindingMapDBID( connection,bMechDBID,allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { throw new ReplicationException( "lookupdsBindMapDBID row " + "doesn't exist for bMechDBID: " + bMechDBID + ", dsBindingMapID: " + allBindingMaps[i].dsBindMapID); } } for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) { dsBindingKeyDBID = lookupDataStreamBindingSpecDBID( connection, bMechDBID, allBindingMaps[i].dsBindingsAugmented[j]. bindKeyName); if (dsBindingKeyDBID == null) { throw new ReplicationException( "lookupDataStreamBindingDBID row doesn't " + "exist for bMechDBID: " + bMechDBID + ", bindKeyName: " + allBindingMaps[i]. dsBindingsAugmented[j].bindKeyName + "i=" + i + " j=" + j); } // Insert DataStreamBinding row Datastream ds = doReader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID); // Add binding only if it does not exist. logFinest("DefaultDOReplicator.addDisseminators: ----- adding dsBind row: " +allBindingMaps[i].dsBindingsAugmented[j].datastreamID); insertDataStreamBindingRow(connection, doDBID, dsBindingKeyDBID, bindingMapDBID, allBindingMaps[i].dsBindingsAugmented[j].seqNo, allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSLabel, allBindingMaps[i].dsBindingsAugmented[j].DSMIME, // sdp - local.fedora.server conversion encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation), allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID, "1", ds.DSState); } } return; } /** * <p> Permanently removes a disseminator from the database incuding * all associated datastream bindings and datastream binding maps. * Associated entries are removed from the following db tables:</p> * <ul> * <li>doDissAssoc - all entries matching pid of data object.</li> * <li>diss - all entries matching disseminator ID provided that no * other objects depend on this disseminator.</li> * <li>dsBind - all entries matching pid of data object.</li> * <li>dsBindMap - all entries matching associated bMech object pid * provided that no other objects depend on this binding map.</li> * </ul> * @param pid Persistent identifier for the data object. * @param dissIds Set of disseminator IDs to be removed. * @param doReader An instance of DOReader. * @param connection A database connection. * @throws SQLException If something totally unexpected happened. */ private void purgeDisseminators(String pid, HashSet dissIds, HashSet bmapIds, DOReader doReader, Connection connection) throws SQLException { logFinest("DefaultDOReplicator.purgeDisseminators: Entering ------"); Statement st=null; Statement st2=null; ResultSet results=null; try { st=connection.createStatement(); // // READ // logFinest("DefaultDOReplicator.purgeDisseminators: Checking do table for " + pid + "..."); results=logAndExecuteQuery(st, "SELECT doDbID FROM " + "do WHERE doPID='" + pid + "'"); if (!results.next()) { // must not be a digitalobject...exit early logFinest("DefaultDOReplicator.purgeDisseminators: " + pid + " wasn't found in do table..." + "skipping deletion as such."); return; } int dbid=results.getInt("doDbID"); results.close(); results=null; logFinest("DefaultDOReplicator.purgeDisseminators: " + pid + " was found in do table (DBID=" + dbid + ")"); logFinest("DefaultDOReplicator.purgeDisseminators: Getting dissDbID(s) from doDissAssoc " + "table..."); HashSet dissIdsNotShared = new HashSet(); logFinest("DefaultDOReplicator.purgeDisseminators: Getting dissDbID(s) from doDissAssoc " + "table unique to this object..."); logFinest("DefaultDOReplicator.purgeDisseminators: Found " + dissIds.size() + " dissDbId(s). "); // Iterate over dissIds and separate those that are unique // (i.e., not shared by other objects) Iterator iterator = dissIds.iterator(); while (iterator.hasNext()) { Integer id = (Integer)iterator.next(); logFinest("DefaultDOReplicator.purgeDisseminators: Getting occurrences of dissDbID(s) in " + "doDissAssoc table..."); results=logAndExecuteQuery(st, "SELECT COUNT(*) from " + "doDissAssoc WHERE dissDbID=" + id); while (results.next()) { Integer i1 = new Integer(results.getInt("COUNT(*)")); if ( i1.intValue() == 1 ) { // A dissDbID that occurs only once indicates that the // disseminator is not used by other objects. In this case, // we want to keep track of this dissDbID. dissIdsNotShared.add(id); } } results.close(); results=null; } // Iterate over bmapIds and separate those that are unique // (i.e., not shared by other objects) logFinest("DefaultDOReplicator.purgeDisseminators: Found " + bmapIds.size() + " dsBindMapDbId(s). "); iterator = bmapIds.iterator(); HashSet bmapIdsInUse = new HashSet(); HashSet bmapIdsShared = new HashSet(); HashSet bmapIdsNotShared = new HashSet(); while (iterator.hasNext() ) { Integer id = (Integer)iterator.next(); ResultSet rs = null; logFinest("DefaultDOReplicator.purgeDisseminators: Getting associated bmapId(s) that are unique " + "for this object in diss table..."); st2 = connection.createStatement(); rs=logAndExecuteQuery(st2, "SELECT DISTINCT doDbID FROM " + "dsBind WHERE dsBindMapDbID=" + id); int rowCount = 0; while (rs.next()) { rowCount++; } if ( rowCount == 1 ) { // A dsBindMapDbId that occurs only once indicates that // the dsBindMapId is not used by other objects. In this case, // we want to keep track of this dsBindMapDbId. bmapIdsNotShared.add(id); } rs.close(); rs=null; st2.close(); st2=null; } // // WRITE // int rowCount; // In doDissAssoc table, we are removing rows specific to the // doDbId, so remove all dissDbIds (both shared and nonShared). logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from doDissAssoc " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM " + "doDissAssoc WHERE doDbID=" + dbid + " AND ( " + inIntegerSetWhereConditionString("dissDbID", dissIds) + " )"); logFinest("DefaultDOReplicator.purgeDisseminators: Deleted " + rowCount + " row(s)."); // In dsBind table, we are removing rows specific to the doDbID, // so remove all dsBindMapIds (both shared and nonShared). logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from dsBind table.."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind " + "WHERE doDbID=" + dbid + " AND ( " + inIntegerSetWhereConditionString("dsBindMapDbID", bmapIds) + " )"); // In diss table, dissDbIds can be shared by other objects so only // remove dissDbIds that are not shared. logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from diss table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE " + inIntegerSetWhereConditionString("dissDbID", dissIdsNotShared)); logFinest("DefaultDOReplicator.purgeDisseminators: Deleted " + rowCount + " row(s)."); // In dsBindMap table, dsBindMapIds can be shared by other objects // so only remove dsBindMapIds that are not shared. logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from dsBindMap " + "table..."); rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap " + "WHERE " + inIntegerSetWhereConditionString( "dsBindMapDbID", bmapIdsNotShared)); logFinest("DefaultDOReplicator.purgeDisseminators: Deleted " + rowCount + " row(s)."); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); if (st2!=null) st2.close(); } catch (SQLException sqle) { } finally { results=null; st=null; st2=null; logFinest("DefaultDOReplicator.purgeDisseminators: Exiting ------"); } } } }
true
true
private boolean updateComponents(DOReader reader) throws ReplicationException { Connection connection=null; Statement st=null; ResultSet results=null; boolean triedUpdate=false; boolean failed=false; logFinest("DefaultDOReplicator.updateComponents: Entering ------"); try { connection=m_pool.getConnection(); st=connection.createStatement(); // Get db ID for the digital object results=logAndExecuteQuery(st, "SELECT doDbID,doState,doLabel FROM do WHERE " + "doPID='" + reader.GetObjectPID() + "'"); if (!results.next()) { logFinest("DefaultDOReplication.updateComponents: Object is " + "new; components dont need updating."); return false; } int doDbID=results.getInt("doDbID"); String doState=results.getString("doState"); String doLabel=results.getString("doLabel"); results.close(); results=null; ArrayList updates=new ArrayList(); // Check if state has changed for the digital object. String objState = reader.GetObjectState(); if (!doState.equalsIgnoreCase(objState)) { updates.add("UPDATE do SET doState='" + objState + "' WHERE doDbID=" + doDbID); updates.add("UPDATE doRegistry SET objectState='" + objState + "' WHERE doPID='" + reader.GetObjectPID() + "'"); } // Check if label has changed for the digital object. String objLabel = reader.GetObjectLabel(); if (!doLabel.equalsIgnoreCase(objLabel)) { updates.add("UPDATE do SET doLabel='" + objLabel + "' WHERE doDbID=" + doDbID); updates.add("UPDATE doRegistry SET label='" + objLabel + "' WHERE doPID='" + reader.GetObjectPID() + "'"); } // check if any mods to datastreams for this digital object results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState " + "FROM dsBind WHERE doDbID=" + doDbID); while (results.next()) { String dsID=results.getString("dsID"); String dsLabel=results.getString("dsLabel"); String dsCurrentVersionID=results.getString("dsCurrentVersionID"); String dsState=results.getString("dsState"); // sdp - local.fedora.server conversion String dsLocation=unencodeLocalURL(results.getString("dsLocation")); // compare the latest version of the datastream to what's in the db... // if different, add to update list Datastream ds=reader.GetDatastream(dsID, null); if (!ds.DSLabel.equals(dsLabel) || !ds.DSLocation.equals(dsLocation) || !ds.DSVersionID.equals(dsCurrentVersionID) || !ds.DSState.equals(dsState)) { updates.add("UPDATE dsBind SET dsLabel='" + SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='" // sdp - local.fedora.server conversion + SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation)) + "', dsCurrentVersionID='" + ds.DSVersionID + "', " + "dsState='" + ds.DSState + "' " + " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'"); } } results.close(); results=null; // Do any required updates via a transaction. if (updates.size()>0) { connection.setAutoCommit(false); triedUpdate=true; for (int i=0; i<updates.size(); i++) { String update=(String) updates.get(i); logAndExecuteUpdate(st, update); } connection.commit(); } else { logFinest("DefaultDOReplication.updateComponents: " + "No datastream labels or locations changed."); } // check if any mods to disseminators for this object... // first get a list of disseminator db IDs results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE " + "doDbID="+doDbID); HashSet dissDbIDs = new HashSet(); while (results.next()) { dissDbIDs.add(new Integer(results.getInt("dissDbID"))); } if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) { logFinest("DefaultDOReplication.updateComponents: Object " + "either has no disseminators or a new disseminator" + "has been added; components dont need updating."); return false; } results.close(); results=null; // Iterate over disseminators to check if any have been modified Iterator dissIter = dissDbIDs.iterator(); while(dissIter.hasNext()) { Integer dissDbID = (Integer) dissIter.next(); // Get disseminator info for this disseminator. results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState " + "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID); updates=new ArrayList(); int bDefDbID = 0; int bMechDbID = 0; String dissID=null; String dissLabel=null; String dissState=null; String bMechPID=null; while(results.next()) { bDefDbID = results.getInt("bDefDbID"); bMechDbID = results.getInt("bMechDbID"); dissID=results.getString("dissID"); dissLabel=results.getString("dissLabel"); dissState=results.getString("dissState"); bMechPID=results.getString("bMechPID"); } results.close(); results=null; // Compare the latest version of the disseminator with what's in the db... // Replace what's in db if they are different. Disseminator diss=reader.GetDisseminator(dissID, null); if (diss == null) { // XML object has no disseminators // so this must be a purgeComponents or a new object. logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators"); return false; } if (!diss.dissLabel.equals(dissLabel) || !diss.bMechID.equals(bMechPID) || !diss.dissState.equals(dissState)) { if (!diss.dissLabel.equals(dissLabel)) logFinest("DefaultDOReplicator.updateComponents: dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'"); if (!diss.dissState.equals(dissState)) logFinest("DefaultDOReplicator.updateComponents: dissState changed from '" + dissState + "' to '" + diss.dissState + "'"); // We might need to set the bMechDbID to the id for the new one, // if the mechanism changed. int newBMechDbID; if (diss.bMechID.equals(bMechPID)) { newBMechDbID=bMechDbID; } else { logFinest("DefaultDOReplicator.updateComponents: bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'"); results=logAndExecuteQuery(st, "SELECT bMechDbID " + "FROM bMech " + "WHERE bMechPID='" + diss.bMechID + "'"); if (!results.next()) { // shouldn't have gotten this far, but if so... throw new ReplicationException("The behavior mechanism " + "changed to " + diss.bMechID + ", but there is no " + "record of that object in the dissemination db."); } newBMechDbID=results.getInt("bMechDbID"); results.close(); results=null; } // Update the diss table with all new, correct values. logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='" + SQLUtility.aposEscape(diss.dissLabel) + "', bMechDbID=" + newBMechDbID + ", " + "dissID='" + diss.dissID + "', " + "dissState='" + diss.dissState + "' " + " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID); } // Compare the latest version of the disseminator's bindMap with what's in the db // and replace what's in db if they are different. results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE " + "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID " + "AND dsBindMap.bMechDbID="+bMechDbID); String origDSBindMapID=null; int origDSBindMapDbID=0; while (results.next()) { origDSBindMapID=results.getString("dsBindMapID"); origDSBindMapDbID=results.getInt("dsBindMapDbID"); } results.close(); results=null; String newDSBindMapID=diss.dsBindMapID; logFinest("DefaultDOReplicator.updateComponents: newDSBindMapID: " + newDSBindMapID + " origDSBindMapID: " + origDSBindMapID); // Is this a new bindingMap? if (!newDSBindMapID.equals(origDSBindMapID)) { // Yes, dsBindingMap was modified so remove original bindingMap and datastreams. // BindingMaps can be shared by other objects so first check to see if // the orignial bindingMap is bound to datastreams of any other objects. Statement st2 = connection.createStatement(); results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbID,dsBindMapDbID FROM dsBind WHERE dsBindMapDbID="+origDSBindMapDbID); int numRows = 0; while (results.next()) { numRows++; } st2.close(); st2=null; results.close(); results=null; // Remove all datastreams for this binding map. // If anything has changed, they will all be added back // shortly from the current binding info the xml object. String dsBindMapDBID = null; dsBindMapDBID = lookupDataStreamBindingMapDBID(connection, (new Integer(bMechDbID)).toString(), origDSBindMapID); int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID + " AND dsBindMapDbID="+dsBindMapDBID); logFinest("DefaultDOReplicator.updateComponents: deleted " + rowCount + " rows from dsBind"); // Is bindingMap shared? if(numRows == 1) { // No, the bindingMap is NOT shared by any other objects and can be removed. rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID); logFinest("DefaultDOReplicator.updateComponents: deleted " + rowCount + " rows from dsBindMapDbID"); } else { //Yes, the bindingMap IS shared by other objects so leave bindingMap untouched. logFinest("DefaultDOReplicator.updateComponents: dsBindMapID: " + origDSBindMapID + " is shared by other objects; it will NOT be deleted"); } // Now add back new datastreams and dsBindMap associated with this disseminator // using current info in xml object. DSBindingMapAugmented[] allBindingMaps; Disseminator disseminators[]; String bDefDBID; String bindingMapDBID; String bMechDBID; String dissDBID; String doDBID; String doPID; //String doLabel; String dsBindingKeyDBID; allBindingMaps = reader.GetDSBindingMaps(null); logFinest("DefaultDOReplicator.updateComponents: Bindings found: "+allBindingMaps.length); for (int i=0; i<allBindingMaps.length; ++i) { // Only update bindingMap that was modified. if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) { logFinest("DefaultDOReplicator.updateComponents: " + "Adding back datastreams and ds binding map. New dsBindMapID: " + newDSBindMapID); bMechDBID = lookupBehaviorMechanismDBID(connection, allBindingMaps[i].dsBindMechanismPID); if (bMechDBID == null) { throw new ReplicationException("BehaviorMechanism row " + "doesn't exist for PID: " + allBindingMaps[i].dsBindMechanismPID); } // Now insert dsBindMap row if it doesn't exist. bindingMapDBID = lookupDataStreamBindingMapDBID(connection, bMechDBID, allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { logFinest("DefaultDOReplicator.updateComponents: ADDing dsBindMap row"); // DataStreamBinding row doesn't exist, add it. insertDataStreamBindingMapRow(connection, bMechDBID, allBindingMaps[i].dsBindMapID, allBindingMaps[i].dsBindMapLabel); bindingMapDBID = lookupDataStreamBindingMapDBID( connection,bMechDBID,allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { throw new ReplicationException( "lookupdsBindMapDBID row " + "doesn't exist for bMechDBID: " + bMechDBID + ", dsBindingMapID: " + allBindingMaps[i].dsBindMapID); } } // Now add back datastream bindings removed earlier. logFinest("DefaultDOReplicator.updateComponents: Bindings found: " + allBindingMaps[i].dsBindingsAugmented.length); for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) { dsBindingKeyDBID = lookupDataStreamBindingSpecDBID( connection, bMechDBID, allBindingMaps[i].dsBindingsAugmented[j]. bindKeyName); if (dsBindingKeyDBID == null) { throw new ReplicationException( "lookupDataStreamBindingDBID row doesn't " + "exist for bMechDBID: " + bMechDBID + ", bindKeyName: " + allBindingMaps[i]. dsBindingsAugmented[j].bindKeyName + "i=" + i + " j=" + j); } // Insert DataStreamBinding row logFinest("DefaultDOReplicator.updateComponents: Adding back dsBind row for: " +allBindingMaps[i].dsBindingsAugmented[j].datastreamID); Datastream ds = reader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID); insertDataStreamBindingRow(connection, new Integer(doDbID).toString(), dsBindingKeyDBID, bindingMapDBID, allBindingMaps[i].dsBindingsAugmented[j].seqNo, allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSLabel, allBindingMaps[i].dsBindingsAugmented[j].DSMIME, // sdp - local.fedora.server conversion encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation), allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID, "1", ds.DSState); } } } } } } catch (SQLException sqle) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage()); } catch (ServerException se) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (connection!=null) { try { if (triedUpdate && failed) connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); connection.setAutoCommit(true); if (connection!=null) m_pool.free(connection); } catch (SQLException sqle) { logWarning("While cleaning up: " + sqle.getClass().getName() + ": " + sqle.getMessage()); } finally { results=null; st=null; } } } } logFinest("DefaultDOReplicator.updateComponents: Exiting ------"); return true; }
private boolean updateComponents(DOReader reader) throws ReplicationException { Connection connection=null; Statement st=null; ResultSet results=null; boolean triedUpdate=false; boolean failed=false; logFinest("DefaultDOReplicator.updateComponents: Entering ------"); try { connection=m_pool.getConnection(); st=connection.createStatement(); // Get db ID for the digital object results=logAndExecuteQuery(st, "SELECT doDbID,doState,doLabel FROM do WHERE " + "doPID='" + reader.GetObjectPID() + "'"); if (!results.next()) { logFinest("DefaultDOReplication.updateComponents: Object is " + "new; components dont need updating."); return false; } int doDbID=results.getInt("doDbID"); String doState=results.getString("doState"); String doLabel=results.getString("doLabel"); results.close(); results=null; ArrayList updates=new ArrayList(); // Check if state has changed for the digital object. String objState = reader.GetObjectState(); if (!doState.equalsIgnoreCase(objState)) { updates.add("UPDATE do SET doState='" + objState + "' WHERE doDbID=" + doDbID); updates.add("UPDATE doRegistry SET objectState='" + objState + "' WHERE doPID='" + reader.GetObjectPID() + "'"); } // Check if label has changed for the digital object. String objLabel = reader.GetObjectLabel(); if (!doLabel.equalsIgnoreCase(objLabel)) { updates.add("UPDATE do SET doLabel='" + SQLUtility.aposEscape(objLabel) + "' WHERE doDbID=" + doDbID); updates.add("UPDATE doRegistry SET label='" + SQLUtility.aposEscape(objLabel) + "' WHERE doPID='" + reader.GetObjectPID() + "'"); } // check if any mods to datastreams for this digital object results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState " + "FROM dsBind WHERE doDbID=" + doDbID); while (results.next()) { String dsID=results.getString("dsID"); String dsLabel=results.getString("dsLabel"); String dsCurrentVersionID=results.getString("dsCurrentVersionID"); String dsState=results.getString("dsState"); // sdp - local.fedora.server conversion String dsLocation=unencodeLocalURL(results.getString("dsLocation")); // compare the latest version of the datastream to what's in the db... // if different, add to update list Datastream ds=reader.GetDatastream(dsID, null); if (!ds.DSLabel.equals(dsLabel) || !ds.DSLocation.equals(dsLocation) || !ds.DSVersionID.equals(dsCurrentVersionID) || !ds.DSState.equals(dsState)) { updates.add("UPDATE dsBind SET dsLabel='" + SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='" // sdp - local.fedora.server conversion + SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation)) + "', dsCurrentVersionID='" + ds.DSVersionID + "', " + "dsState='" + ds.DSState + "' " + " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'"); } } results.close(); results=null; // Do any required updates via a transaction. if (updates.size()>0) { connection.setAutoCommit(false); triedUpdate=true; for (int i=0; i<updates.size(); i++) { String update=(String) updates.get(i); logAndExecuteUpdate(st, update); } connection.commit(); } else { logFinest("DefaultDOReplication.updateComponents: " + "No datastream labels or locations changed."); } // check if any mods to disseminators for this object... // first get a list of disseminator db IDs results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE " + "doDbID="+doDbID); HashSet dissDbIDs = new HashSet(); while (results.next()) { dissDbIDs.add(new Integer(results.getInt("dissDbID"))); } if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) { logFinest("DefaultDOReplication.updateComponents: Object " + "either has no disseminators or a new disseminator" + "has been added; components dont need updating."); return false; } results.close(); results=null; // Iterate over disseminators to check if any have been modified Iterator dissIter = dissDbIDs.iterator(); while(dissIter.hasNext()) { Integer dissDbID = (Integer) dissIter.next(); // Get disseminator info for this disseminator. results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState " + "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID); updates=new ArrayList(); int bDefDbID = 0; int bMechDbID = 0; String dissID=null; String dissLabel=null; String dissState=null; String bMechPID=null; while(results.next()) { bDefDbID = results.getInt("bDefDbID"); bMechDbID = results.getInt("bMechDbID"); dissID=results.getString("dissID"); dissLabel=results.getString("dissLabel"); dissState=results.getString("dissState"); bMechPID=results.getString("bMechPID"); } results.close(); results=null; // Compare the latest version of the disseminator with what's in the db... // Replace what's in db if they are different. Disseminator diss=reader.GetDisseminator(dissID, null); if (diss == null) { // XML object has no disseminators // so this must be a purgeComponents or a new object. logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators"); return false; } if (!diss.dissLabel.equals(dissLabel) || !diss.bMechID.equals(bMechPID) || !diss.dissState.equals(dissState)) { if (!diss.dissLabel.equals(dissLabel)) logFinest("DefaultDOReplicator.updateComponents: dissLabel changed from '" + dissLabel + "' to '" + diss.dissLabel + "'"); if (!diss.dissState.equals(dissState)) logFinest("DefaultDOReplicator.updateComponents: dissState changed from '" + dissState + "' to '" + diss.dissState + "'"); // We might need to set the bMechDbID to the id for the new one, // if the mechanism changed. int newBMechDbID; if (diss.bMechID.equals(bMechPID)) { newBMechDbID=bMechDbID; } else { logFinest("DefaultDOReplicator.updateComponents: bMechPID changed from '" + bMechPID + "' to '" + diss.bMechID + "'"); results=logAndExecuteQuery(st, "SELECT bMechDbID " + "FROM bMech " + "WHERE bMechPID='" + diss.bMechID + "'"); if (!results.next()) { // shouldn't have gotten this far, but if so... throw new ReplicationException("The behavior mechanism " + "changed to " + diss.bMechID + ", but there is no " + "record of that object in the dissemination db."); } newBMechDbID=results.getInt("bMechDbID"); results.close(); results=null; } // Update the diss table with all new, correct values. logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='" + SQLUtility.aposEscape(diss.dissLabel) + "', bMechDbID=" + newBMechDbID + ", " + "dissID='" + diss.dissID + "', " + "dissState='" + diss.dissState + "' " + " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID + " AND bMechDbID=" + bMechDbID); } // Compare the latest version of the disseminator's bindMap with what's in the db // and replace what's in db if they are different. results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE " + "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID " + "AND dsBindMap.bMechDbID="+bMechDbID); String origDSBindMapID=null; int origDSBindMapDbID=0; while (results.next()) { origDSBindMapID=results.getString("dsBindMapID"); origDSBindMapDbID=results.getInt("dsBindMapDbID"); } results.close(); results=null; String newDSBindMapID=diss.dsBindMapID; logFinest("DefaultDOReplicator.updateComponents: newDSBindMapID: " + newDSBindMapID + " origDSBindMapID: " + origDSBindMapID); // Is this a new bindingMap? if (!newDSBindMapID.equals(origDSBindMapID)) { // Yes, dsBindingMap was modified so remove original bindingMap and datastreams. // BindingMaps can be shared by other objects so first check to see if // the orignial bindingMap is bound to datastreams of any other objects. Statement st2 = connection.createStatement(); results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbID,dsBindMapDbID FROM dsBind WHERE dsBindMapDbID="+origDSBindMapDbID); int numRows = 0; while (results.next()) { numRows++; } st2.close(); st2=null; results.close(); results=null; // Remove all datastreams for this binding map. // If anything has changed, they will all be added back // shortly from the current binding info the xml object. String dsBindMapDBID = null; dsBindMapDBID = lookupDataStreamBindingMapDBID(connection, (new Integer(bMechDbID)).toString(), origDSBindMapID); int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID + " AND dsBindMapDbID="+dsBindMapDBID); logFinest("DefaultDOReplicator.updateComponents: deleted " + rowCount + " rows from dsBind"); // Is bindingMap shared? if(numRows == 1) { // No, the bindingMap is NOT shared by any other objects and can be removed. rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID=" + origDSBindMapDbID); logFinest("DefaultDOReplicator.updateComponents: deleted " + rowCount + " rows from dsBindMapDbID"); } else { //Yes, the bindingMap IS shared by other objects so leave bindingMap untouched. logFinest("DefaultDOReplicator.updateComponents: dsBindMapID: " + origDSBindMapID + " is shared by other objects; it will NOT be deleted"); } // Now add back new datastreams and dsBindMap associated with this disseminator // using current info in xml object. DSBindingMapAugmented[] allBindingMaps; Disseminator disseminators[]; String bDefDBID; String bindingMapDBID; String bMechDBID; String dissDBID; String doDBID; String doPID; //String doLabel; String dsBindingKeyDBID; allBindingMaps = reader.GetDSBindingMaps(null); logFinest("DefaultDOReplicator.updateComponents: Bindings found: "+allBindingMaps.length); for (int i=0; i<allBindingMaps.length; ++i) { // Only update bindingMap that was modified. if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) { logFinest("DefaultDOReplicator.updateComponents: " + "Adding back datastreams and ds binding map. New dsBindMapID: " + newDSBindMapID); bMechDBID = lookupBehaviorMechanismDBID(connection, allBindingMaps[i].dsBindMechanismPID); if (bMechDBID == null) { throw new ReplicationException("BehaviorMechanism row " + "doesn't exist for PID: " + allBindingMaps[i].dsBindMechanismPID); } // Now insert dsBindMap row if it doesn't exist. bindingMapDBID = lookupDataStreamBindingMapDBID(connection, bMechDBID, allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { logFinest("DefaultDOReplicator.updateComponents: ADDing dsBindMap row"); // DataStreamBinding row doesn't exist, add it. insertDataStreamBindingMapRow(connection, bMechDBID, allBindingMaps[i].dsBindMapID, allBindingMaps[i].dsBindMapLabel); bindingMapDBID = lookupDataStreamBindingMapDBID( connection,bMechDBID,allBindingMaps[i].dsBindMapID); if (bindingMapDBID == null) { throw new ReplicationException( "lookupdsBindMapDBID row " + "doesn't exist for bMechDBID: " + bMechDBID + ", dsBindingMapID: " + allBindingMaps[i].dsBindMapID); } } // Now add back datastream bindings removed earlier. logFinest("DefaultDOReplicator.updateComponents: Bindings found: " + allBindingMaps[i].dsBindingsAugmented.length); for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) { dsBindingKeyDBID = lookupDataStreamBindingSpecDBID( connection, bMechDBID, allBindingMaps[i].dsBindingsAugmented[j]. bindKeyName); if (dsBindingKeyDBID == null) { throw new ReplicationException( "lookupDataStreamBindingDBID row doesn't " + "exist for bMechDBID: " + bMechDBID + ", bindKeyName: " + allBindingMaps[i]. dsBindingsAugmented[j].bindKeyName + "i=" + i + " j=" + j); } // Insert DataStreamBinding row logFinest("DefaultDOReplicator.updateComponents: Adding back dsBind row for: " +allBindingMaps[i].dsBindingsAugmented[j].datastreamID); Datastream ds = reader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID); insertDataStreamBindingRow(connection, new Integer(doDbID).toString(), dsBindingKeyDBID, bindingMapDBID, allBindingMaps[i].dsBindingsAugmented[j].seqNo, allBindingMaps[i].dsBindingsAugmented[j].datastreamID, allBindingMaps[i].dsBindingsAugmented[j].DSLabel, allBindingMaps[i].dsBindingsAugmented[j].DSMIME, // sdp - local.fedora.server conversion encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation), allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp, allBindingMaps[i].dsBindingsAugmented[j].DSVersionID, "1", ds.DSState); } } } } } } catch (SQLException sqle) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + sqle.getClass().getName() + " \". The cause was \" " + sqle.getMessage()); } catch (ServerException se) { failed=true; throw new ReplicationException("An error has occurred during " + "Replication. The error was \" " + se.getClass().getName() + " \". The cause was \" " + se.getMessage()); } catch (Exception e) { e.printStackTrace(); } finally { if (connection!=null) { try { if (triedUpdate && failed) connection.rollback(); } catch (Throwable th) { logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage()); } finally { try { if (results != null) results.close(); if (st!=null) st.close(); connection.setAutoCommit(true); if (connection!=null) m_pool.free(connection); } catch (SQLException sqle) { logWarning("While cleaning up: " + sqle.getClass().getName() + ": " + sqle.getMessage()); } finally { results=null; st=null; } } } } logFinest("DefaultDOReplicator.updateComponents: Exiting ------"); return true; }
diff --git a/ch04/src/main/java/coprocessor/LoadWithTableDescriptorExample.java b/ch04/src/main/java/coprocessor/LoadWithTableDescriptorExample.java index 1eb53a5..c819bec 100644 --- a/ch04/src/main/java/coprocessor/LoadWithTableDescriptorExample.java +++ b/ch04/src/main/java/coprocessor/LoadWithTableDescriptorExample.java @@ -1,42 +1,42 @@ package coprocessor; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.coprocessor.Coprocessor; import org.apache.hadoop.hbase.util.Bytes; import util.HBaseHelper; import java.io.IOException; // cc LoadWithTableDescriptorExample Example region observer checking for special get requests // vv LoadWithTableDescriptorExample public class LoadWithTableDescriptorExample { public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); // ^^ LoadWithTableDescriptorExample HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); // vv LoadWithTableDescriptorExample FileSystem fs = FileSystem.get(conf); Path path = new Path(fs.getUri() + Path.SEPARATOR + "test.jar"); // co LoadWithTableDescriptorExample-1-Path Get the location of the JAR file containing the coprocessor implementation. HTableDescriptor htd = new HTableDescriptor("testtable"); // co LoadWithTableDescriptorExample-2-Define Define a table descriptor. htd.addFamily(new HColumnDescriptor("colfam1")); htd.setValue("COPROCESSOR$1", path.toString() + - ":" + RegionObserverExample.class.getCanonicalName() + // co LoadWithTableDescriptorExample-3-AddCP Add the coprocessor definition to the descriptor. - ":" + Coprocessor.Priority.USER); + "|" + RegionObserverExample.class.getCanonicalName() + // co LoadWithTableDescriptorExample-3-AddCP Add the coprocessor definition to the descriptor. + "|" + Coprocessor.Priority.USER); HBaseAdmin admin = new HBaseAdmin(conf); // co LoadWithTableDescriptorExample-4-Admin Instantiate an administrative API to the cluster and add the table. admin.createTable(htd); System.out.println(admin.getTableDescriptor(Bytes.toBytes("testtable"))); // co LoadWithTableDescriptorExample-5-Check Verify if the definition has been applied as expected. } } // ^^ LoadWithTableDescriptorExample
true
true
public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); // ^^ LoadWithTableDescriptorExample HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); // vv LoadWithTableDescriptorExample FileSystem fs = FileSystem.get(conf); Path path = new Path(fs.getUri() + Path.SEPARATOR + "test.jar"); // co LoadWithTableDescriptorExample-1-Path Get the location of the JAR file containing the coprocessor implementation. HTableDescriptor htd = new HTableDescriptor("testtable"); // co LoadWithTableDescriptorExample-2-Define Define a table descriptor. htd.addFamily(new HColumnDescriptor("colfam1")); htd.setValue("COPROCESSOR$1", path.toString() + ":" + RegionObserverExample.class.getCanonicalName() + // co LoadWithTableDescriptorExample-3-AddCP Add the coprocessor definition to the descriptor. ":" + Coprocessor.Priority.USER); HBaseAdmin admin = new HBaseAdmin(conf); // co LoadWithTableDescriptorExample-4-Admin Instantiate an administrative API to the cluster and add the table. admin.createTable(htd); System.out.println(admin.getTableDescriptor(Bytes.toBytes("testtable"))); // co LoadWithTableDescriptorExample-5-Check Verify if the definition has been applied as expected. }
public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); // ^^ LoadWithTableDescriptorExample HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); // vv LoadWithTableDescriptorExample FileSystem fs = FileSystem.get(conf); Path path = new Path(fs.getUri() + Path.SEPARATOR + "test.jar"); // co LoadWithTableDescriptorExample-1-Path Get the location of the JAR file containing the coprocessor implementation. HTableDescriptor htd = new HTableDescriptor("testtable"); // co LoadWithTableDescriptorExample-2-Define Define a table descriptor. htd.addFamily(new HColumnDescriptor("colfam1")); htd.setValue("COPROCESSOR$1", path.toString() + "|" + RegionObserverExample.class.getCanonicalName() + // co LoadWithTableDescriptorExample-3-AddCP Add the coprocessor definition to the descriptor. "|" + Coprocessor.Priority.USER); HBaseAdmin admin = new HBaseAdmin(conf); // co LoadWithTableDescriptorExample-4-Admin Instantiate an administrative API to the cluster and add the table. admin.createTable(htd); System.out.println(admin.getTableDescriptor(Bytes.toBytes("testtable"))); // co LoadWithTableDescriptorExample-5-Check Verify if the definition has been applied as expected. }
diff --git a/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java b/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java index 9b44db669..afc51e9ab 100644 --- a/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java +++ b/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java @@ -1,430 +1,434 @@ /* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.servlet; import grails.util.GrailsUtil; import org.codehaus.groovy.grails.commons.*; import org.codehaus.groovy.grails.commons.spring.GrailsApplicationContext; import org.codehaus.groovy.grails.web.MultipartRequestHolder; import org.codehaus.groovy.grails.web.context.GrailsConfigUtils; import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest; import org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController; import org.codehaus.groovy.grails.web.util.WebUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.access.BootstrapException; import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.WebRequestInterceptor; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.servlet.*; import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter; import org.springframework.web.util.NestedServletException; import org.springframework.web.util.UrlPathHelper; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Iterator; import java.util.Locale; import java.util.Map; /** * <p>Servlet that handles incoming requests for Grails. * <p/> * <p>This servlet loads the Spring configuration based on the Grails application * in the parent application context. * * @author Steven Devijver * @author Graeme Rocher * * @since Jul 2, 2005 */ public class GrailsDispatcherServlet extends DispatcherServlet { private GrailsApplication application; private UrlPathHelper urlHelper = new GrailsUrlPathHelper(); private SimpleGrailsController grailsController; protected HandlerInterceptor[] interceptors; protected MultipartResolver multipartResolver; private static final String EXCEPTION_ATTRIBUTE = "exception"; public GrailsDispatcherServlet() { super(); setDetectAllHandlerMappings(false); } protected void initFrameworkServlet() throws ServletException, BeansException { super.initFrameworkServlet(); initMultipartResolver(); } /** * Initialize the MultipartResolver used by this class. * If no bean is defined with the given name in the BeanFactory * for this namespace, no multipart handling is provided. */ private void initMultipartResolver() throws BeansException { try { this.multipartResolver = (MultipartResolver) getWebApplicationContext().getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class); if (logger.isInfoEnabled()) { logger.info("Using MultipartResolver [" + this.multipartResolver + "]"); } } catch (NoSuchBeanDefinitionException ex) { // Default is no multipart resolver. this.multipartResolver = null; if (logger.isInfoEnabled()) { logger.info("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME + "': no multipart request handling provided"); } } } protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException { WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); WebApplicationContext webContext; // construct the SpringConfig for the container managed application Assert.notNull(parent, "Grails requires a parent ApplicationContext, is the /WEB-INF/applicationContext.xml file missing?"); this.application = (GrailsApplication) parent.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); if(wac instanceof GrailsApplicationContext) { webContext = wac; } else { webContext = GrailsConfigUtils.configureWebApplicationContext(getServletContext(), parent); try { GrailsConfigUtils.executeGrailsBootstraps(application, webContext, getServletContext()); } catch (Exception e) { GrailsUtil.deepSanitize(e); if(e instanceof BeansException) throw (BeansException)e; else { throw new BootstrapException("Error executing bootstraps", e); } } } initGrailsController(webContext); this.interceptors = establishInterceptors(webContext); return webContext; } private void initGrailsController(WebApplicationContext webContext) { if(webContext.containsBean(SimpleGrailsController.APPLICATION_CONTEXT_ID)) { this.grailsController = (SimpleGrailsController)webContext.getBean(SimpleGrailsController.APPLICATION_CONTEXT_ID); } } /** * Evalutes the given WebApplicationContext for all HandlerInterceptor and WebRequestInterceptor instances * * @param webContext The WebApplicationContext * @return An array of HandlerInterceptor instances */ protected HandlerInterceptor[] establishInterceptors(WebApplicationContext webContext) { HandlerInterceptor[] interceptors; String[] interceptorNames = webContext.getBeanNamesForType(HandlerInterceptor.class); String[] webRequestInterceptors = webContext.getBeanNamesForType( WebRequestInterceptor.class); interceptors = new HandlerInterceptor[interceptorNames.length+webRequestInterceptors.length]; // Merge the handler and web request interceptors into a single // array. Note that we start with the web request interceptors // to ensure that the OpenSessionInViewInterceptor (which is a // web request interceptor) is invoked before the user-defined // filters (which are attached to a handler interceptor). This // should ensure that the Hibernate session is in the proper // state if and when users access the database within their // filters. int j = 0; for (int i = 0; i < webRequestInterceptors.length; i++) { interceptors[j++] = new WebRequestHandlerInterceptorAdapter((WebRequestInterceptor)webContext.getBean(webRequestInterceptors[i])); } for (int i = 0; i < interceptorNames.length; i++) { interceptors[j++] = (HandlerInterceptor)webContext.getBean(interceptorNames[i]); } return interceptors; } public void destroy() { WebApplicationContext webContext = getWebApplicationContext(); GrailsApplication application = (GrailsApplication) webContext.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); GrailsClass[] bootstraps = application.getArtefacts(BootstrapArtefactHandler.TYPE); for (int i = 0; i < bootstraps.length; i++) { ((GrailsBootstrapClass)bootstraps[i]).callDestroy(); } super.destroy(); } public void setApplication(GrailsApplication application) { this.application = application; } /* (non-Javadoc) * @see org.springframework.web.servlet.DispatcherServlet#doDispatch(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ protected void doDispatch(final HttpServletRequest request, HttpServletResponse response) throws Exception { HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; final LocaleResolver localeResolver = (LocaleResolver)request.getAttribute(LOCALE_RESOLVER_ATTRIBUTE); // Expose current LocaleResolver and request as LocaleContext. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); LocaleContextHolder.setLocaleContext(new LocaleContext() { public Locale getLocale() { return localeResolver.resolveLocale(request); } }); // If the request is an include we need to try to use the original wrapped sitemesh // response, otherwise layouts won't work properly if(WebUtils.isIncludeRequest(request)) { response = useWrappedOrOriginalResponse(response); } GrailsWebRequest requestAttributes = null; GrailsWebRequest previousRequestAttributes = null; + Exception handlerException = null; try { ModelAndView mv = null; try { Object exceptionAttribute = request.getAttribute(EXCEPTION_ATTRIBUTE); // only process multipart requests if an exception hasn't occured if(exceptionAttribute == null) processedRequest = checkMultipart(request); // Expose current RequestAttributes to current thread. previousRequestAttributes = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); requestAttributes = new GrailsWebRequest(processedRequest, response, getServletContext()); copyParamsFromPreviousRequest(previousRequestAttributes, requestAttributes); // Update the current web request. WebUtils.storeGrailsWebRequest(requestAttributes); if (logger.isDebugEnabled()) { logger.debug("Bound request context to thread: " + request); logger.debug("Using response object: " + response.getClass()); } // Determine handler for the current request. mappedHandler = getHandler(processedRequest, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Apply preHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = 0; i < mappedHandler.getInterceptors().length; i++) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i; } } // Actually invoke the handler. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // Apply postHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } } catch (ModelAndViewDefiningException ex) { GrailsUtil.deepSanitize(ex); + handlerException = ex; if (logger.isDebugEnabled()) logger.debug("ModelAndViewDefiningException encountered", ex); mv = ex.getModelAndView(); } catch (Exception ex) { GrailsUtil.deepSanitize(ex); + handlerException = ex; Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, ex); } // Did the handler return a view to render? if (mv != null && !mv.wasCleared()) { // If an exception occurs in here, like a bad closing tag, // we have nothing to render. try { render(mv, processedRequest, response); } catch (Exception e) { mv = super.processHandlerException(processedRequest, response, mappedHandler, e); + handlerException = e; render(mv, processedRequest, response); } } else { if (logger.isDebugEnabled()) { logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling"); } } // Trigger after-completion for successful outcome. - triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); + triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, handlerException); } catch (Exception ex) { // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } catch (Error err) { ServletException ex = new NestedServletException("Handler processing failed", err); // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } finally { // Clean up any resources used by a multipart request. if (processedRequest instanceof MultipartHttpServletRequest && processedRequest != request) { if(multipartResolver != null) this.multipartResolver.cleanupMultipart((MultipartHttpServletRequest) processedRequest); } // Reset thread-bound RequestAttributes. if(requestAttributes != null) { requestAttributes.requestCompleted(); WebUtils.storeGrailsWebRequest(previousRequestAttributes); } // Reset thread-bound LocaleContext. LocaleContextHolder.setLocaleContext(previousLocaleContext); if (logger.isDebugEnabled()) { logger.debug("Cleared thread-bound request context: " + request); } } } protected HttpServletResponse useWrappedOrOriginalResponse(HttpServletResponse response) { HttpServletResponse r = WrappedResponseHolder.getWrappedResponse(); if(r != null) return r; return response; } protected void copyParamsFromPreviousRequest(GrailsWebRequest previousRequestAttributes, GrailsWebRequest requestAttributes) { Map previousParams = previousRequestAttributes.getParams(); Map params = requestAttributes.getParams(); for (Iterator i = previousParams.keySet().iterator(); i.hasNext();) { String name = (String)i.next(); params.put(name, previousParams.get(name)); } } /** * Trigger afterCompletion callbacks on the mapped HandlerInterceptors. * Will just invoke afterCompletion for all interceptors whose preHandle * invocation has successfully completed and returned true. * @param mappedHandler the mapped HandlerExecutionChain * @param interceptorIndex index of last interceptor that successfully completed * @param ex Exception thrown on handler execution, or <code>null</code> if none * @see HandlerInterceptor#afterCompletion */ protected void triggerAfterCompletion( HandlerExecutionChain mappedHandler, int interceptorIndex, HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception { // Apply afterCompletion methods of registered interceptors. if (mappedHandler != null) { if (mappedHandler.getInterceptors() != null) { for (int i = interceptorIndex; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; try { interceptor.afterCompletion(request, response, mappedHandler.getHandler(), ex); } catch (Throwable ex2) { GrailsUtil.deepSanitize(ex2); logger.error("HandlerInterceptor.afterCompletion threw exception", ex2); } } } } } /** * Convert the request into a multipart request. * If no multipart resolver is set, simply use the existing request. * @param request current HTTP request * @return the processed request (multipart wrapper if necessary) */ protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException { MultipartHttpServletRequest mpr = MultipartRequestHolder.getMultipartRequest(); return mpr == null ? request : mpr; } /** * Overrides the default behaviour to establish the handler from the GrailsApplication instance * * @param request The request * @param cache Whether to cache the Handler in the request * @return The HandlerExecutionChain * * @throws Exception */ protected HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception { String uri = urlHelper.getPathWithinApplication(request); if(logger.isDebugEnabled()) { logger.debug("Looking up Grails controller for URI ["+uri+"]"); } GrailsControllerClass controllerClass = (GrailsControllerClass) application.getArtefactForFeature( ControllerArtefactHandler.TYPE, uri); if(controllerClass!=null) { HandlerInterceptor[] interceptors; // if we're in a development environment we want to re-establish interceptors just in case they // have changed at runtime if(GrailsUtil.isDevelopmentEnv()) { interceptors = establishInterceptors(getWebApplicationContext()); } else { interceptors = this.interceptors; } if(grailsController == null) { initGrailsController(getWebApplicationContext()); } return new HandlerExecutionChain(grailsController, interceptors); } return null; } }
false
true
protected void doDispatch(final HttpServletRequest request, HttpServletResponse response) throws Exception { HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; final LocaleResolver localeResolver = (LocaleResolver)request.getAttribute(LOCALE_RESOLVER_ATTRIBUTE); // Expose current LocaleResolver and request as LocaleContext. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); LocaleContextHolder.setLocaleContext(new LocaleContext() { public Locale getLocale() { return localeResolver.resolveLocale(request); } }); // If the request is an include we need to try to use the original wrapped sitemesh // response, otherwise layouts won't work properly if(WebUtils.isIncludeRequest(request)) { response = useWrappedOrOriginalResponse(response); } GrailsWebRequest requestAttributes = null; GrailsWebRequest previousRequestAttributes = null; try { ModelAndView mv = null; try { Object exceptionAttribute = request.getAttribute(EXCEPTION_ATTRIBUTE); // only process multipart requests if an exception hasn't occured if(exceptionAttribute == null) processedRequest = checkMultipart(request); // Expose current RequestAttributes to current thread. previousRequestAttributes = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); requestAttributes = new GrailsWebRequest(processedRequest, response, getServletContext()); copyParamsFromPreviousRequest(previousRequestAttributes, requestAttributes); // Update the current web request. WebUtils.storeGrailsWebRequest(requestAttributes); if (logger.isDebugEnabled()) { logger.debug("Bound request context to thread: " + request); logger.debug("Using response object: " + response.getClass()); } // Determine handler for the current request. mappedHandler = getHandler(processedRequest, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Apply preHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = 0; i < mappedHandler.getInterceptors().length; i++) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i; } } // Actually invoke the handler. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // Apply postHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } } catch (ModelAndViewDefiningException ex) { GrailsUtil.deepSanitize(ex); if (logger.isDebugEnabled()) logger.debug("ModelAndViewDefiningException encountered", ex); mv = ex.getModelAndView(); } catch (Exception ex) { GrailsUtil.deepSanitize(ex); Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, ex); } // Did the handler return a view to render? if (mv != null && !mv.wasCleared()) { // If an exception occurs in here, like a bad closing tag, // we have nothing to render. try { render(mv, processedRequest, response); } catch (Exception e) { mv = super.processHandlerException(processedRequest, response, mappedHandler, e); render(mv, processedRequest, response); } } else { if (logger.isDebugEnabled()) { logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling"); } } // Trigger after-completion for successful outcome. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); } catch (Exception ex) { // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } catch (Error err) { ServletException ex = new NestedServletException("Handler processing failed", err); // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } finally { // Clean up any resources used by a multipart request. if (processedRequest instanceof MultipartHttpServletRequest && processedRequest != request) { if(multipartResolver != null) this.multipartResolver.cleanupMultipart((MultipartHttpServletRequest) processedRequest); } // Reset thread-bound RequestAttributes. if(requestAttributes != null) { requestAttributes.requestCompleted(); WebUtils.storeGrailsWebRequest(previousRequestAttributes); } // Reset thread-bound LocaleContext. LocaleContextHolder.setLocaleContext(previousLocaleContext); if (logger.isDebugEnabled()) { logger.debug("Cleared thread-bound request context: " + request); } } }
protected void doDispatch(final HttpServletRequest request, HttpServletResponse response) throws Exception { HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; final LocaleResolver localeResolver = (LocaleResolver)request.getAttribute(LOCALE_RESOLVER_ATTRIBUTE); // Expose current LocaleResolver and request as LocaleContext. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); LocaleContextHolder.setLocaleContext(new LocaleContext() { public Locale getLocale() { return localeResolver.resolveLocale(request); } }); // If the request is an include we need to try to use the original wrapped sitemesh // response, otherwise layouts won't work properly if(WebUtils.isIncludeRequest(request)) { response = useWrappedOrOriginalResponse(response); } GrailsWebRequest requestAttributes = null; GrailsWebRequest previousRequestAttributes = null; Exception handlerException = null; try { ModelAndView mv = null; try { Object exceptionAttribute = request.getAttribute(EXCEPTION_ATTRIBUTE); // only process multipart requests if an exception hasn't occured if(exceptionAttribute == null) processedRequest = checkMultipart(request); // Expose current RequestAttributes to current thread. previousRequestAttributes = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); requestAttributes = new GrailsWebRequest(processedRequest, response, getServletContext()); copyParamsFromPreviousRequest(previousRequestAttributes, requestAttributes); // Update the current web request. WebUtils.storeGrailsWebRequest(requestAttributes); if (logger.isDebugEnabled()) { logger.debug("Bound request context to thread: " + request); logger.debug("Using response object: " + response.getClass()); } // Determine handler for the current request. mappedHandler = getHandler(processedRequest, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Apply preHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = 0; i < mappedHandler.getInterceptors().length; i++) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i; } } // Actually invoke the handler. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // Apply postHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } } catch (ModelAndViewDefiningException ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; if (logger.isDebugEnabled()) logger.debug("ModelAndViewDefiningException encountered", ex); mv = ex.getModelAndView(); } catch (Exception ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, ex); } // Did the handler return a view to render? if (mv != null && !mv.wasCleared()) { // If an exception occurs in here, like a bad closing tag, // we have nothing to render. try { render(mv, processedRequest, response); } catch (Exception e) { mv = super.processHandlerException(processedRequest, response, mappedHandler, e); handlerException = e; render(mv, processedRequest, response); } } else { if (logger.isDebugEnabled()) { logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling"); } } // Trigger after-completion for successful outcome. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, handlerException); } catch (Exception ex) { // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } catch (Error err) { ServletException ex = new NestedServletException("Handler processing failed", err); // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } finally { // Clean up any resources used by a multipart request. if (processedRequest instanceof MultipartHttpServletRequest && processedRequest != request) { if(multipartResolver != null) this.multipartResolver.cleanupMultipart((MultipartHttpServletRequest) processedRequest); } // Reset thread-bound RequestAttributes. if(requestAttributes != null) { requestAttributes.requestCompleted(); WebUtils.storeGrailsWebRequest(previousRequestAttributes); } // Reset thread-bound LocaleContext. LocaleContextHolder.setLocaleContext(previousLocaleContext); if (logger.isDebugEnabled()) { logger.debug("Cleared thread-bound request context: " + request); } } }
diff --git a/OnlyRoad/src/com/gromsoft/onlyroad/MainActivity.java b/OnlyRoad/src/com/gromsoft/onlyroad/MainActivity.java index b55e2b3..96c6301 100644 --- a/OnlyRoad/src/com/gromsoft/onlyroad/MainActivity.java +++ b/OnlyRoad/src/com/gromsoft/onlyroad/MainActivity.java @@ -1,329 +1,329 @@ package com.gromsoft.onlyroad; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.AudioManager; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.Tab; import com.actionbarsherlock.app.ActionBar.TabListener; import com.actionbarsherlock.app.SherlockMapActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; import com.google.android.maps.OverlayItem; public class MainActivity extends SherlockMapActivity implements TabListener, LocationListener, OnPageChangeListener { MapController mMapController; MapView mMapView; ViewPager mViewPager; com.actionbarsherlock.app.ActionBar mActionBar; LocationManager mLocationManager; List<Overlay> mapOverlays; Drawable startLocationMarker; RouteOverlay mRouteOverlay = null; int latitude, longtitude; GeoPoint myLocationGp; MyLocationOverlay mMyLocationOverlay; Context mContext; AudioManager mAudioManager; boolean isSpeakerOn; boolean isDefaultSpeakerOn; int speakerDefaulValue; public Menu mMenu; // TODO public ��� �����, �� ���� ����� ��-������� ��������. ����� ���� ���������� isToggleButtonChecked ��� ���� �������� � ��� �� �����? final static String LOG = "MyLog"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; - // ��������� ��������� �������� � ��������� + // ��������� ��������� �������� � ��������� mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); isDefaultSpeakerOn = mAudioManager.isSpeakerphoneOn();// ��������� ��������� �� ������� speakerDefaulValue = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); // �� ��������� ����� Window w = this.getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // ---------------- Swipe ------------------------------------------- LayoutInflater inflater = LayoutInflater.from(this); final View pageMap = (MapView) inflater.inflate(R.layout.layout_map, null); final View pagePhone = inflater.inflate(R.layout.layout_phone, null); final View pageVideo = inflater.inflate(R.layout.layout_video, null); List<View> pages = new ArrayList<View>(); pages.add(pageMap); pages.add(pagePhone); pages.add(pageVideo); final MyPagerAdapter mMyPagerAdapter = new MyPagerAdapter(pages); mViewPager = new ViewPager(this); mViewPager.setAdapter(mMyPagerAdapter); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(3); // MapView ��� ���� ���� ������, ����� �� ������ �� �����???? setContentView(mViewPager); mViewPager.setOnPageChangeListener(this); // --------------- ����� ---------------------------------------------------- mMapView = (MapView) pageMap.findViewById(R.id.map); // ������ View ����� � pageMap mMapController = mMapView.getController(); mLocationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); mapOverlays = mMapView.getOverlays();// �������� ����, ����������� � ����� mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMyLocationOverlay.enableMyLocation(); mMyLocationOverlay.disableCompass(); mapOverlays.add(mMyLocationOverlay); mMyLocationOverlay.runOnFirstFix(new Runnable() { @Override public void run() { mMapController.animateTo(mMyLocationOverlay.getMyLocation()); } }); // ---------------- ActionBar ---------------------------------- mActionBar = getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true);// ������ ���������� ��� �������� ����� mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);// �������� mActionBar.setDisplayShowTitleEnabled(false);// �� ���������� �������� ���������� ����� � ������� Tab tab = mActionBar.newTab().setText(R.string.menu_dvr).setTabListener(this); mActionBar.addTab(tab); tab = mActionBar.newTab().setText(R.string.menu_phone).setTabListener(this); mActionBar.addTab(tab); tab = mActionBar.newTab().setText(R.string.menu_videos).setTabListener(this); mActionBar.addTab(tab); } // ============================== ����� onCreate ===================================================== // -------- ��������� ���� -------------------------------------- @Override protected void onPause() { // TODO ���������, ��� ���� �� ����� ������������� ������, �� ����� � ���� ���� ���������� mLocationManager.removeUpdates(this); mMyLocationOverlay.disableMyLocation(); SaveSettings(); super.onPause(); } @Override protected void onResume() { RestoreSettings(); mMyLocationOverlay.enableMyLocation(); super.onResume(); } @Override protected void onDestroy() { // ������������ ��������� �������� � ��������� �� ������� mAudioManager.setSpeakerphoneOn(isDefaultSpeakerOn); mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, speakerDefaulValue, 0); super.onDestroy(); } private void SaveSettings() { SharedPreferences settings = this.getPreferences(0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("SpeakerPhone", isSpeakerOn); editor.putInt("Zoom", mMapView.getZoomLevel()); editor.putInt("Volume", mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC)); editor.commit(); } private void RestoreSettings() { SharedPreferences settings = this.getPreferences(0); isSpeakerOn = settings.getBoolean("SpeakerPhone", false); mAudioManager.setSpeakerphoneOn(isSpeakerOn); mMapController.setZoom(settings.getInt("Zoom", mMapView.getMaxZoomLevel())); mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, settings.getInt("Volume", mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0); String mapvid = settings.getString("pref_map_vid_key", getString(R.string.pref_map_vid_default)); mMapView.setSatellite((mapvid.compareTo("�������") == 0)); } // ============================ @Overrides ==================================================== // ----------------- Action Bar ------------------------------------------ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); // getSupport.. ����� ��� Sherlock inflater.inflate(R.menu.menu_main, menu); mMenu = menu; // ������� MenuItem speakerMenu = mMenu.findItem(R.id.speaker); speakerMenu.setChecked(isSpeakerOn); speakerMenu.setIcon(isSpeakerOn ? R.drawable.speaker_on : R.drawable.speaker_off); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case (R.id.record): if (item.isChecked()) { item.setChecked(false); item.setIcon(R.drawable.record_on); mRouteOverlay.setRecording(false); return true; } else { item.setChecked(true); item.setIcon(R.drawable.record_off); mRouteOverlay.clearItems(); mRouteOverlay.setRecording(true); return true; } case (R.id.speaker): isSpeakerOn = !item.isChecked(); // ����� �������� // ����� ��������� mAudioManager.setSpeakerphoneOn(isSpeakerOn);// ������� item.setChecked(isSpeakerOn);// MenuItem item.setIcon(isSpeakerOn ? R.drawable.speaker_on : R.drawable.speaker_off);// ������ Log.d(LOG, "onOptionMenuSelected"); Log.d(LOG, "���������� isSpeakerOn=" + String.valueOf(isSpeakerOn)); return true; case (R.id.autoanswer): if (item.isChecked()) { item.setChecked(false); item.setIcon(R.drawable.autoanswer_on); return true; } else { item.setChecked(true); item.setIcon(R.drawable.autoanswer_off); return true; } case (R.id.settings_menuitem): Intent intent = new Intent(); intent.setClass(this, SettingsActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } // ------------------ Navigation Tabs---------------- @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { mViewPager.setCurrentItem(tab.getPosition()); if (tab.getPosition() == 0) { mMyLocationOverlay.enableMyLocation(); mMapView.postInvalidate(); } else mMyLocationOverlay.disableMyLocation(); } @Override public void onPageSelected(int position) { mActionBar.setSelectedNavigationItem(position); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } // ---------------------- ����� ------------------------ @Override public void onLocationChanged(Location location) { Log.d(LOG, "LocationChanged lat=" + String.valueOf(latitude) + " long=" + String.valueOf(longtitude)); latitude = (int) (location.getLatitude() * 1e6); longtitude = (int) (location.getLongitude() * 1e6); GeoPoint lastLocation = new GeoPoint(latitude, longtitude); if (mRouteOverlay == null) { mRouteOverlay = new RouteOverlay(getResources().getDrawable(R.drawable.location), Color.BLUE); mapOverlays.add(mRouteOverlay); } OverlayItem cOverlayItem = new OverlayItem(lastLocation, "", "");// ��������� ��������� ����� mRouteOverlay.addOverlay(cOverlayItem);// �������� �� � ���� mMapView.postInvalidate(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override protected boolean isRouteDisplayed() { return false; } // ========================= ��������� ================================================= }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; // ��������� ��������� �������� � ��������� mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); isDefaultSpeakerOn = mAudioManager.isSpeakerphoneOn();// ��������� ��������� �� ������� speakerDefaulValue = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); // �� ��������� ����� Window w = this.getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // ---------------- Swipe ------------------------------------------- LayoutInflater inflater = LayoutInflater.from(this); final View pageMap = (MapView) inflater.inflate(R.layout.layout_map, null); final View pagePhone = inflater.inflate(R.layout.layout_phone, null); final View pageVideo = inflater.inflate(R.layout.layout_video, null); List<View> pages = new ArrayList<View>(); pages.add(pageMap); pages.add(pagePhone); pages.add(pageVideo); final MyPagerAdapter mMyPagerAdapter = new MyPagerAdapter(pages); mViewPager = new ViewPager(this); mViewPager.setAdapter(mMyPagerAdapter); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(3); // MapView ��� ���� ���� ������, ����� �� ������ �� �����???? setContentView(mViewPager); mViewPager.setOnPageChangeListener(this); // --------------- ����� ---------------------------------------------------- mMapView = (MapView) pageMap.findViewById(R.id.map); // ������ View ����� � pageMap mMapController = mMapView.getController(); mLocationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); mapOverlays = mMapView.getOverlays();// �������� ����, ����������� � ����� mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMyLocationOverlay.enableMyLocation(); mMyLocationOverlay.disableCompass(); mapOverlays.add(mMyLocationOverlay); mMyLocationOverlay.runOnFirstFix(new Runnable() { @Override public void run() { mMapController.animateTo(mMyLocationOverlay.getMyLocation()); } }); // ---------------- ActionBar ---------------------------------- mActionBar = getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true);// ������ ���������� ��� �������� ����� mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);// �������� mActionBar.setDisplayShowTitleEnabled(false);// �� ���������� �������� ���������� ����� � ������� Tab tab = mActionBar.newTab().setText(R.string.menu_dvr).setTabListener(this); mActionBar.addTab(tab); tab = mActionBar.newTab().setText(R.string.menu_phone).setTabListener(this); mActionBar.addTab(tab); tab = mActionBar.newTab().setText(R.string.menu_videos).setTabListener(this); mActionBar.addTab(tab); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; // ��������� ��������� �������� � ��������� mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); isDefaultSpeakerOn = mAudioManager.isSpeakerphoneOn();// ��������� ��������� �� ������� speakerDefaulValue = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); // �� ��������� ����� Window w = this.getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // ---------------- Swipe ------------------------------------------- LayoutInflater inflater = LayoutInflater.from(this); final View pageMap = (MapView) inflater.inflate(R.layout.layout_map, null); final View pagePhone = inflater.inflate(R.layout.layout_phone, null); final View pageVideo = inflater.inflate(R.layout.layout_video, null); List<View> pages = new ArrayList<View>(); pages.add(pageMap); pages.add(pagePhone); pages.add(pageVideo); final MyPagerAdapter mMyPagerAdapter = new MyPagerAdapter(pages); mViewPager = new ViewPager(this); mViewPager.setAdapter(mMyPagerAdapter); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(3); // MapView ��� ���� ���� ������, ����� �� ������ �� �����???? setContentView(mViewPager); mViewPager.setOnPageChangeListener(this); // --------------- ����� ---------------------------------------------------- mMapView = (MapView) pageMap.findViewById(R.id.map); // ������ View ����� � pageMap mMapController = mMapView.getController(); mLocationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); mapOverlays = mMapView.getOverlays();// �������� ����, ����������� � ����� mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMyLocationOverlay.enableMyLocation(); mMyLocationOverlay.disableCompass(); mapOverlays.add(mMyLocationOverlay); mMyLocationOverlay.runOnFirstFix(new Runnable() { @Override public void run() { mMapController.animateTo(mMyLocationOverlay.getMyLocation()); } }); // ---------------- ActionBar ---------------------------------- mActionBar = getSupportActionBar(); mActionBar.setDisplayHomeAsUpEnabled(true);// ������ ���������� ��� �������� ����� mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);// �������� mActionBar.setDisplayShowTitleEnabled(false);// �� ���������� �������� ���������� ����� � ������� Tab tab = mActionBar.newTab().setText(R.string.menu_dvr).setTabListener(this); mActionBar.addTab(tab); tab = mActionBar.newTab().setText(R.string.menu_phone).setTabListener(this); mActionBar.addTab(tab); tab = mActionBar.newTab().setText(R.string.menu_videos).setTabListener(this); mActionBar.addTab(tab); }
diff --git a/pixi/src/main/java/org/openpixi/pixi/physics/movement/boundary/HardwallBoundary.java b/pixi/src/main/java/org/openpixi/pixi/physics/movement/boundary/HardwallBoundary.java index baac4e12..f281ff06 100644 --- a/pixi/src/main/java/org/openpixi/pixi/physics/movement/boundary/HardwallBoundary.java +++ b/pixi/src/main/java/org/openpixi/pixi/physics/movement/boundary/HardwallBoundary.java @@ -1,24 +1,30 @@ package org.openpixi.pixi.physics.movement.boundary; import org.openpixi.pixi.physics.Particle; /** * Reflects particle off the wall. * Allows particle to be outside of the simulation area! */ public class HardwallBoundary extends ParticleBoundary { public HardwallBoundary(double xoffset, double yoffset) { super(xoffset, yoffset); } @Override public void apply(Particle p) { - if (xoffset != 0) { - p.setVx(-p.getVx()); + if (xoffset < 0) { + p.setVx(Math.abs(p.getVx())); } - if (yoffset != 0) { - p.setVy(-p.getVy()); + else if (xoffset > 0) { + p.setVx(-Math.abs(p.getVx())); + } + if (yoffset < 0) { + p.setVy(Math.abs(p.getVy())); + } + else if (yoffset > 0) { + p.setVy(-Math.abs(p.getVy())); } } }
false
true
public void apply(Particle p) { if (xoffset != 0) { p.setVx(-p.getVx()); } if (yoffset != 0) { p.setVy(-p.getVy()); } }
public void apply(Particle p) { if (xoffset < 0) { p.setVx(Math.abs(p.getVx())); } else if (xoffset > 0) { p.setVx(-Math.abs(p.getVx())); } if (yoffset < 0) { p.setVy(Math.abs(p.getVy())); } else if (yoffset > 0) { p.setVy(-Math.abs(p.getVy())); } }
diff --git a/testsrc/org/olap4j/ConnectionTest.java b/testsrc/org/olap4j/ConnectionTest.java index 0372ed5..ff27245 100644 --- a/testsrc/org/olap4j/ConnectionTest.java +++ b/testsrc/org/olap4j/ConnectionTest.java @@ -1,980 +1,980 @@ /* // $Id$ // This software is subject to the terms of the Common Public License // Agreement, available at the following URL: // http://www.opensource.org/licenses/cpl.html. // Copyright (C) 2007-2007 Julian Hyde // All Rights Reserved. // You must accept the terms of that agreement to use this software. */ package org.olap4j; import junit.framework.TestCase; import junit.framework.AssertionFailedError; import java.sql.*; import java.sql.Connection; import java.sql.DriverManager; import java.util.*; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.net.URL; import org.olap4j.metadata.*; import org.olap4j.metadata.Cube; import org.olap4j.metadata.Dimension; import org.olap4j.metadata.Schema; import org.olap4j.mdx.SelectNode; import org.olap4j.mdx.ParseTreeWriter; import org.olap4j.mdx.parser.MdxParser; import org.olap4j.test.TestContext; import org.olap4j.type.Type; import org.olap4j.driver.xmla.XmlaOlap4jDriver; import org.xml.sax.SAXException; import mondrian.tui.XmlaSupport; import javax.servlet.ServletException; /** * Unit test for olap4j Driver and Connection classes. * * <p>The system property "org.olap4j.test.helperClassName" determines the * name of the helper class. By default, uses {@link MondrianHelper}, which * runs against mondrian; {@link XmlaHelper} is also available. * * @version $Id$ */ public class ConnectionTest extends TestCase { private final Helper helper = createHelper(); /** * Factory method for the {@link org.olap4j.ConnectionTest.Helper} * object which determines which driver to test. * * @return a new Helper */ private Helper createHelper() { String helperClassName = System.getProperty("org.olap4j.test.helperClassName"); if (helperClassName != null) { try { Class<?> clazz = Class.forName(helperClassName); return (Helper) clazz.newInstance(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } return new MondrianHelper(); } private static final boolean IS_JDK_16 = System.getProperty("java.version").startsWith("1.6."); /** * Driver basics. */ public void testDriver() throws ClassNotFoundException, SQLException { Class clazz = Class.forName(helper.getDriverClassName()); assertNotNull(clazz); assertTrue(Driver.class.isAssignableFrom(clazz)); // driver should have automatically registered itself Driver driver = DriverManager.getDriver(helper.getDriverUrlPrefix()); assertNotNull(driver); // deregister driver DriverManager.deregisterDriver(driver); try { Driver driver2 = DriverManager.getDriver(helper.getDriverUrlPrefix()); fail("expected error, got " + driver2); } catch (SQLException e) { assertEquals("No suitable driver", e.getMessage()); } // register explicitly DriverManager.registerDriver(driver); Driver driver3 = DriverManager.getDriver(helper.getDriverUrlPrefix()); assertNotNull(driver3); // test properties int majorVersion = driver.getMajorVersion(); int minorVersion = driver.getMinorVersion(); assertTrue(majorVersion > 0); assertTrue(minorVersion >= 0); // check that the getPropertyInfo method returns something sensible. // We can't test individual properties in this non-driver-specific test. DriverPropertyInfo[] driverPropertyInfos = driver.getPropertyInfo( helper.getDriverUrlPrefix(), new Properties()); assertTrue(driverPropertyInfos.length > 0); } void assertIsValid(Connection connection, int timeout) { if (!IS_JDK_16) { return; } // assertTrue(connection.isValid(0)); try { java.lang.reflect.Method method = Connection.class.getMethod("isValid", int.class); Boolean b = (Boolean) method.invoke(connection, timeout); assertTrue(b); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } /** * Checks that the <code>isClosed</code> method of a Statement, ResultSet or * Connection object returns the expected result. Uses reflection because * the <code>isClosed</code> method only exists from JDBC 4.0 (JDK 1.6) * onwrds. * * @param o Connection, Statement or ResultSet object * @param b Expected result */ void assertIsClosed(Object o, boolean b) { if (!IS_JDK_16) { return; } // assertTrue(statment.isClosed()); try { Class clazz; if (o instanceof Statement){ clazz = Statement.class; } else if (o instanceof ResultSet) { clazz = ResultSet.class; } else if (o instanceof Connection) { clazz = Connection.class; } else { throw new AssertionFailedError( "not a statement, resultSet or connection"); } java.lang.reflect.Method method = clazz.getMethod("isClosed"); Boolean closed = (Boolean) method.invoke(o); if (b) { assertTrue(closed); } else { assertFalse(closed); } } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } public void testConnection() throws ClassNotFoundException, SQLException { Class.forName(helper.getDriverClassName()); // connect using properties and no username/password Connection connection = helper.createConnection(); assertNotNull(connection); // check isClosed, isValid assertFalse(connection.isClosed()); // check valid with no time limit assertIsValid(connection, 0); // check valid with one minute time limit; should be enough assertIsValid(connection, 60); connection.close(); assertTrue(connection.isClosed()); // it's ok to close twice connection.close(); // connect using username/password connection = helper.createConnectionWithUserPassword(); assertNotNull(connection); connection.close(); assertTrue(connection.isClosed()); // connect with URL only connection = DriverManager.getConnection(helper.getURL()); assertNotNull(connection); connection.close(); assertTrue(connection.isClosed()); } public void testConnectionUnwrap() throws SQLException { java.sql.Connection connection = helper.createConnection(); // Trivial unwrap assertTrue(((OlapWrapper) connection).isWrapperFor(Connection.class)); Connection connection2 = ((OlapWrapper) connection).unwrap(Connection.class); assertEquals(connection2, connection); // Silly unwrap assertTrue(((OlapWrapper) connection).isWrapperFor(Object.class)); Object object = ((OlapWrapper) connection).unwrap(Object.class); assertEquals(object, connection); // Invalid unwrap assertFalse(((OlapWrapper) connection).isWrapperFor(Writer.class)); try { Writer writer = ((OlapWrapper) connection).unwrap(Writer.class); fail("expected exception, got writer" + writer); } catch (SQLException e) { assertTrue(e.getMessage().contains("does not implement")); } // Unwrap the mondrian connection. if (helper.isMondrian()) { final mondrian.olap.Connection mondrianConnection = ((OlapWrapper) connection).unwrap(mondrian.olap.Connection.class); assertNotNull(mondrianConnection); } } public void testDatabaseMetaData() throws SQLException { java.sql.Connection connection = helper.createConnection(); String catalogName = connection.getCatalog(); assertEquals("LOCALDB", catalogName); DatabaseMetaData databaseMetaData = connection.getMetaData(); assertTrue(databaseMetaData.getDatabaseMajorVersion() > 0); assertTrue(databaseMetaData.getDatabaseMinorVersion() >= 0); assertTrue(databaseMetaData.getDatabaseProductName() != null); assertTrue(databaseMetaData.getDatabaseProductVersion() != null); assertTrue(databaseMetaData.getDriverName() != null); assertTrue(databaseMetaData.getDriverVersion() != null); // mondrian-specific assertTrue(databaseMetaData.isReadOnly()); assertNull(databaseMetaData.getUserName()); assertNotNull(databaseMetaData.getURL()); // unwrap connection; may or may not be the same object as connection; // check extended methods OlapConnection olapConnection = ((OlapWrapper) connection).unwrap(OlapConnection.class); OlapDatabaseMetaData olapDatabaseMetaData = olapConnection.getMetaData(); // also unwrap metadata from regular connection assertTrue(((OlapWrapper) databaseMetaData).isWrapperFor(OlapDatabaseMetaData.class)); assertFalse(((OlapWrapper) databaseMetaData).isWrapperFor(OlapStatement.class)); OlapDatabaseMetaData olapDatabaseMetaData1 = ((OlapWrapper) databaseMetaData).unwrap( OlapDatabaseMetaData.class); assertTrue( olapDatabaseMetaData1.getDatabaseProductVersion().equals( olapDatabaseMetaData.getDatabaseProductVersion())); // check schema final Schema schema1 = olapConnection.getSchema(); assertEquals(schema1.getName(), "FoodMart"); checkResultSet(olapDatabaseMetaData.getActions()); String dataSourceName = "xx"; checkResultSet(olapDatabaseMetaData.getDatasources(dataSourceName)); checkResultSet(olapDatabaseMetaData.getLiterals()); checkResultSet(olapDatabaseMetaData.getDatabaseProperties(dataSourceName)); checkResultSet(olapDatabaseMetaData.getProperties()); String keywords = olapDatabaseMetaData.getMdxKeywords(); assertNotNull(keywords); // todo: call getCubes with a pattern for cube name and schema name // todo: call getCubes with a different schema String schemaPattern = "xx"; String cubeNamePattern = "SALES"; checkResultSet( olapDatabaseMetaData.getCubes( catalogName, schemaPattern, cubeNamePattern)); int k = 0; for (Catalog catalog : olapConnection.getCatalogs()) { ++k; assertEquals(catalog.getMetaData(), olapDatabaseMetaData); for (Schema schema : catalog.getSchemas()) { ++k; assertEquals(schema.getCatalog(), catalog); for (Cube cube : schema.getCubes()) { ++k; assertEquals(cube.getSchema(), schema); } for (Dimension dimension : schema.getSharedDimensions()) { ++k; } for (Locale locale : schema.getSupportedLocales()) { ++k; } } } assertTrue(k > 0); checkResultSet( olapDatabaseMetaData.getDatabaseProperties(dataSourceName)); checkResultSet( olapDatabaseMetaData.getDatasources(dataSourceName)); checkResultSet( olapDatabaseMetaData.getDimensions()); checkResultSet( olapDatabaseMetaData.getFunctions()); checkResultSet( olapDatabaseMetaData.getHierarchies()); checkResultSet( olapDatabaseMetaData.getLevels()); checkResultSet( olapDatabaseMetaData.getLiterals()); checkResultSet( olapDatabaseMetaData.getMeasures()); checkResultSet( olapDatabaseMetaData.getMembers()); checkResultSet( olapDatabaseMetaData.getProperties()); checkResultSet( olapDatabaseMetaData.getSets()); // todo: More tests required for other methods on DatabaseMetaData } private void checkResultSet(ResultSet resultSet) throws SQLException { assertNotNull(resultSet); int k = 0; while (resultSet.next()) { ++k; } assertTrue(k >= 0); } public void testStatement() throws SQLException { Connection connection = helper.createConnection(); Statement statement = connection.createStatement(); // Closing a statement is idempotent. assertIsClosed(statement, false); statement.close(); assertIsClosed(statement, true); statement.close(); assertIsClosed(statement, true); // Unwrap the statement to get the olap statement. Depending on the // driver, this may or may not be the same object. statement = connection.createStatement(); OlapStatement olapStatement = ((OlapWrapper) statement).unwrap(OlapStatement.class); assertNotNull(olapStatement); // Execute a simple query. CellSet cellSet = olapStatement.executeOlapQuery( "SELECT FROM [Sales]"); List<CellSetAxis> axesList = cellSet.getAxes(); assertNotNull(axesList); assertEquals(0, axesList.size()); // Executing another query implicitly closes the previous result set. assertIsClosed(statement, false); assertIsClosed(cellSet, false); CellSet cellSet2 = olapStatement.executeOlapQuery( "SELECT FROM [Sales]"); assertIsClosed(statement, false); assertIsClosed(cellSet, true); // Close the statement; this closes the result set. assertIsClosed(cellSet2, false); statement.close(); assertIsClosed(statement, true); assertIsClosed(cellSet2, true); cellSet.close(); assertIsClosed(statement, true); assertIsClosed(cellSet2, true); assertIsClosed(cellSet, true); // Close the connection. connection.close(); } // todo: test statement with no slicer private enum Method { ClassName, Mode, Type, TypeName, OlapType } public void testPreparedStatement() throws SQLException { Connection connection = helper.createConnection(); OlapConnection olapConnection = ((OlapWrapper) connection).unwrap(OlapConnection.class); PreparedOlapStatement pstmt = olapConnection.prepareOlapStatement( "SELECT {\n" + " Parameter(\"P1\", [Store], [Store].[USA].[CA]).Parent,\n" + " ParamRef(\"P1\").Children} ON 0\n" + "FROM [Sales]\n" + "WHERE [Gender].[M]"); OlapParameterMetaData parameterMetaData = pstmt.getParameterMetaData(); int paramCount = parameterMetaData.getParameterCount(); assertEquals(1, paramCount); int[] paramIndexes = {0, 1, 2}; for (int paramIndex : paramIndexes) { for (Method method : Method.values()) { try { switch (method) { case ClassName: String className = parameterMetaData.getParameterClassName(paramIndex); assertEquals("org.olap4j.metadata.Member", className); break; case Mode: int mode = parameterMetaData.getParameterMode(paramIndex); assertEquals(ParameterMetaData.parameterModeIn, mode); break; case Type: int type = parameterMetaData.getParameterType(paramIndex); assertEquals(Types.OTHER, type); break; case TypeName: String typeName = parameterMetaData.getParameterTypeName(paramIndex); assertEquals("MemberType<hierarchy=[Store]>", typeName); break; case OlapType: Type olapType = parameterMetaData.getParameterOlapType(paramIndex); assertEquals( "MemberType<hierarchy=[Store]>", olapType.toString()); break; } if (paramIndex != 1) { fail("expected exception"); } } catch (SQLException e) { if (paramIndex == 1) { throw e; } else { // ok - expecting exception } } } } // Check metadata exists. (Support for this method is optional.) final CellSetMetaData metaData = pstmt.getMetaData(); CellSet cellSet = pstmt.executeQuery(); assertEquals(metaData, cellSet.getMetaData()); String s = TestContext.toString(cellSet); TestContext.assertEqualsVerbose( TestContext.fold("Axis #0:\n" + "{[Gender].[All Gender].[M]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA]}\n" + "{[Store].[All Stores].[USA].[CA].[Alameda]}\n" + "{[Store].[All Stores].[USA].[CA].[Beverly Hills]}\n" + "{[Store].[All Stores].[USA].[CA].[Los Angeles]}\n" + "{[Store].[All Stores].[USA].[CA].[San Diego]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco]}\n" + "Row #0: 135,215\n" + "Row #0: \n" + "Row #0: 10,562\n" + "Row #0: 13,574\n" + "Row #0: 12,800\n" + "Row #0: 1,053\n"), s); // Bind parameter and re-execute. final List<Position> positions = cellSet.getAxes().get(0).getPositions(); final Member member = positions.get(positions.size() - 1).getMembers().get(0); pstmt.setObject(1, member); CellSet cellSet2 = pstmt.executeQuery(); assertIsClosed(cellSet, true); assertIsClosed(cellSet2, false); s = TestContext.toString(cellSet2); TestContext.assertEqualsVerbose( TestContext.fold( "Axis #0:\n" + "{[Gender].[All Gender].[M]}\n" + "Axis #1:\n" + "{[Store].[All Stores].[USA].[CA]}\n" + "{[Store].[All Stores].[USA].[CA].[San Francisco].[Store 14]}\n" + "Row #0: 37,989\n" + "Row #0: 1,053\n"), s); // Re-execute with a new MDX string. CellSet cellSet3 = pstmt.executeOlapQuery("SELECT FROM [Sales] WHERE [Gender]"); TestContext.assertEqualsVerbose( TestContext.fold("Axis #0:\n" + "{[Gender].[All Gender]}\n" + "266,773"), TestContext.toString(cellSet3)); // Number of parameters has changed. OlapParameterMetaData parameterMetaData1 = pstmt.getParameterMetaData(); assertEquals(0, parameterMetaData1.getParameterCount()); // Try to bind non-existent parameter. try { pstmt.setInt(1, 100); fail("expected exception"); } catch (SQLException e) { // ok } // Execute again. CellSet cellSet4 = pstmt.executeQuery(); assertIsClosed(cellSet4, false); assertIsClosed(cellSet3, true); assertEquals(0, cellSet4.getAxes().size()); assertEquals(266773.0, cellSet4.getCell(0).getValue()); // Re-execute with a parse tree. MdxParser mdxParser = olapConnection.getParserFactory().createMdxParser(olapConnection); SelectNode select = mdxParser.parseSelect( "select {[Gender]} on columns from [sales]\n" + "where [Time].[1997].[Q4]"); CellSet cellSet5 = pstmt.executeOlapQuery(select); TestContext.assertEqualsVerbose( TestContext.fold( "Axis #0:\n" + "{[Time].[1997].[Q4]}\n" + "Axis #1:\n" + "{[Gender].[All Gender]}\n" + "Row #0: 72,024\n"), TestContext.toString(cellSet5)); // Execute. CellSet cellSet6 = pstmt.executeQuery(); assertIsClosed(cellSet6, false); assertIsClosed(cellSet5, true); assertEquals(1, cellSet6.getAxes().size()); assertEquals(72024.0, cellSet6.getCell(0).getDoubleValue()); // Close prepared statement. assertIsClosed(pstmt, false); pstmt.close(); assertIsClosed(pstmt, true); assertIsClosed(cellSet, true); assertIsClosed(cellSet2, true); assertIsClosed(cellSet6, true); // todo: test all of the PreparedOlapStatement.setXxx methods } public void testCellSetMetaData() throws SQLException { // Metadata of prepared statement Connection connection = helper.createConnection(); OlapConnection olapConnection = ((OlapWrapper) connection).unwrap(OlapConnection.class); final String mdx = "select {[Gender]} on columns from [sales]\n" + "where [Time].[1997].[Q4]"; PreparedOlapStatement pstmt = olapConnection.prepareOlapStatement(mdx); final CellSetMetaData cellSetMetaData = pstmt.getMetaData(); checkCellSetMetaData(cellSetMetaData); // Metadata of its cellset final CellSet cellSet = pstmt.executeQuery(); checkCellSetMetaData(cellSet.getMetaData()); // Metadata of regular statement executing string. final OlapStatement stmt = olapConnection.createStatement(); final CellSet cellSet1 = stmt.executeOlapQuery(mdx); checkCellSetMetaData(cellSet1.getMetaData()); // Metadata of regular statement executing parse tree. MdxParser mdxParser = olapConnection.getParserFactory().createMdxParser(olapConnection); SelectNode select = mdxParser.parseSelect(mdx); final OlapStatement stmt2 = olapConnection.createStatement(); CellSet cellSet2 = stmt2.executeOlapQuery(select); checkCellSetMetaData(cellSet2.getMetaData()); } private void checkCellSetMetaData(CellSetMetaData cellSetMetaData) { assertNotNull(cellSetMetaData); assertEquals(1, cellSetMetaData.getAxesMetaData().size()); assertEquals("Sales", cellSetMetaData.getCube().getName()); } public void testCellSet() throws SQLException { Connection connection = helper.createConnection(); Statement statement = connection.createStatement(); final OlapStatement olapStatement = ((OlapWrapper) statement).unwrap(OlapStatement.class); final CellSet cellSet = olapStatement.executeOlapQuery( "SELECT\n" + " {[Measures].[Unit Sales],\n" + " [Measures].[Store Sales]} ON COLUMNS\n," + " Crossjoin({[Gender].[M]}, [Product].Children) ON ROWS\n" + "FROM [Sales]\n" + "WHERE [Time].[1997].[Q2]"); String s = TestContext.toString(cellSet); assertEquals( TestContext.fold("Axis #0:\n" + "{[Time].[1997].[Q2]}\n" + "Axis #1:\n" + "{[Measures].[Unit Sales]}\n" + "{[Measures].[Store Sales]}\n" + "Axis #2:\n" + "{[Gender].[All Gender].[M], [Product].[All Products].[Drink]}\n" + "{[Gender].[All Gender].[M], [Product].[All Products].[Food]}\n" + "{[Gender].[All Gender].[M], [Product].[All Products].[Non-Consumable]}\n" + "Row #0: 3,023\n" + "Row #0: 6,004.80\n" + "Row #1: 22,558\n" + "Row #1: 47,869.17\n" + "Row #2: 6,037\n" + "Row #2: 12,935.16\n"), s); } public void testCell() { // todo: test Cell methods /* public CellSet getCellSet() { public int getOrdinal() { public List<Integer> getCoordinateList() { public Object getPropertyValue(Property property) { public boolean isEmpty() { public boolean isError() { public boolean isNull() { public double getDoubleValue() throws OlapException { public String getErrorText() { public Object getValue() { public String getFormattedValue() { public ResultSet drillThrough() { */ // in particular, create a result set with null, empty and error cells, // and make sure they look different // todo: test CellSetAxis methods /* public int getOrdinal() { public CellSet getCellSet() { public CellSetAxisMetaData getAxisMetaData() { public List<Position> getPositions() { public int getPositionCount() { public ListIterator<Position> iterate() { todo: test OlapResultAxisMetaData methods public org.olap4j.Axis getAxis() { public List<Hierarchy> getHierarchies() { public List<Property> getProperties() { */ } public void testProperty() { // todo: submit a query with cell and dimension properties, and make // sure the properties appear in the result set } /** * Tests different scrolling characteristics. * * <p>In one mode, you request that you get all of the positions on an axis. * You can call {@link CellSetAxis#getPositions()} and * {@link CellSetAxis#getPositions()}. * * <p>In another mode, you can iterate over the positions, calling * {@link CellSetAxis#iterate()}. Note that this method returns a * {@link java.util.ListIterator}, which has * {@link java.util.ListIterator#nextIndex()}. We could maybe extend this * interface further, to allow to jump forwards/backwards by N. * * <p>This test should check that queries work correctly when you ask * for axes as lists and iterators. If you open the query as a list, * you can get it as an iterator, but if you open it as an iterator, you * cannot get it as a list. (Or maybe you can, but it is expensive.) * * <p>The existing JDBC method {@link Connection#createStatement(int, int)}, * where the 2nd parameter has values such as * {@link ResultSet#TYPE_FORWARD_ONLY} and * {@link ResultSet#TYPE_SCROLL_INSENSITIVE}, might be the way to invoke * those two modes. * * <p>Note that cell ordinals are not well-defined until axis lengths are * known. Test that cell ordinal property is not available if the statement * is opened in this mode. * * <p>It was proposed that there would be an API to get blocks of cell * values. Not in the spec yet. */ public void testScrolling() { // todo: submit a query where you ask for different scrolling // characteristics. maybe the values int x = ResultSet.TYPE_SCROLL_INSENSITIVE; int y = ResultSet.TYPE_FORWARD_ONLY; // are how to ask for these characteristics. also need to document this // behavior in the API and the spec. in one mode, } /** * Tests creation of an MDX parser, and converting an MDX statement into * a parse tree. * * <p>Also create a set of negative tests. Do we give sensible errors if * the MDX is misformed. * * <p>Also have a set of validator tests, which check that the functions * used exist, are applied to arguments of the correct type, and members * exist. */ public void testParsing() throws SQLException { // parse Connection connection = helper.createConnection(); OlapConnection olapConnection = ((OlapWrapper) connection).unwrap(OlapConnection.class); MdxParser mdxParser = olapConnection.getParserFactory().createMdxParser(olapConnection); SelectNode select = mdxParser.parseSelect( "with member [Measures].[Foo] as ' [Measures].[Bar] ', FORMAT_STRING='xxx'\n" + " select {[Gender]} on columns, {[Store].Children} on rows\n" + "from [sales]\n" + "where [Time].[1997].[Q4]"); // unparse StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); ParseTreeWriter parseTreeWriter = new ParseTreeWriter(pw); select.unparse(parseTreeWriter); pw.flush(); String mdx = sw.toString(); TestContext.assertEqualsVerbose( TestContext.fold("WITH\n" + "MEMBER [Measures].[Foo] AS '[Measures].[Bar]', FORMAT_STRING = \"xxx\"\n" + "SELECT\n" + "{[Gender]} ON COLUMNS,\n" + "{[Store].Children} ON ROWS\n" + "FROM [sales]\n" + "WHERE [Time].[1997].[Q4]"), mdx); // build parse tree (todo) // test that get error if axes do not have unique names (todo) } /** * Tests creation of an MDX query from a parse tree. Build the parse tree * programmatically. */ public void testUnparsing() { } /** * Tests access control. The metadata (e.g. members & hierarchies) should * reflect what the current user/role can see. For example, USA.CA.SF has no children. */ /** * Abstracts the information about specific drivers and database instances * needed by this test. This allows the same test suite to be used for * multiple implementations of olap4j. */ interface Helper { Connection createConnection() throws SQLException; String getDriverUrlPrefix(); String getDriverClassName(); Connection createConnectionWithUserPassword() throws SQLException; String getURL(); boolean isMondrian(); } /** * Implementation of {@link Helper} which speaks to the mondrian olap4j * driver. */ public static class MondrianHelper implements Helper { public Connection createConnection() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } return DriverManager.getConnection( getURL(), new Properties()); } public Connection createConnectionWithUserPassword() throws SQLException { return DriverManager.getConnection( getURL(), USER, PASSWORD); } public String getDriverUrlPrefix() { return DRIVER_URL_PREFIX; } public String getDriverClassName() { return DRIVER_CLASS_NAME; } public String getURL() { return getDefaultConnectString(); } public boolean isMondrian() { return true; } public static String getDefaultConnectString() { if (true) { return "jdbc:mondrian:Jdbc='jdbc:odbc:MondrianFoodMart';Catalog='file://c:/open/mondrian/demo/FoodMart.xml';JdbcDrivers=sun.jdbc.odbc.JdbcOdbcDriver;"; } else { return "jdbc:mondrian:Jdbc=jdbc:oracle:thin:foodmart/foodmart@//marmalade.hydromatic.net:1521/XE;JdbcUser=foodmart;JdbcPassword=foodmart;Catalog=../mondrian/demo/FoodMart.xml;JdbcDrivers=oracle.jdbc.OracleDriver;"; } } public static final String DRIVER_CLASS_NAME = "mondrian.olap4j.MondrianOlap4jDriver"; public static final String DRIVER_URL_PREFIX = "jdbc:mondrian:"; private static final String USER = "user"; private static final String PASSWORD = "password"; } /** * Implementation of {@link Helper} which speaks to the XML/A olap4j * driver. */ public static class XmlaHelper implements Helper { XmlaOlap4jDriver.Proxy proxy = new MondrianInprocProxy(); public Connection createConnection() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } try { XmlaOlap4jDriver.THREAD_PROXY.set(proxy); Properties info = new Properties(); info.setProperty("UseThreadProxy", "true"); return DriverManager.getConnection( getURL(), info); } finally { XmlaOlap4jDriver.THREAD_PROXY.set(null); } } public Connection createConnectionWithUserPassword() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } try { XmlaOlap4jDriver.THREAD_PROXY.set(proxy); Properties info = new Properties(); info.setProperty("UseThreadProxy", "true"); return DriverManager.getConnection( getURL(), USER, PASSWORD); } finally { XmlaOlap4jDriver.THREAD_PROXY.set(null); } } public String getDriverUrlPrefix() { return DRIVER_URL_PREFIX; } public String getDriverClassName() { return DRIVER_CLASS_NAME; } public String getURL() { return "jdbc:xmla:Server=http://foo;UseThreadProxy=true"; } public boolean isMondrian() { return false; } public static final String DRIVER_CLASS_NAME = "org.olap4j.driver.xmla.XmlaOlap4jDriver"; public static final String DRIVER_URL_PREFIX = "jdbc:xmla:"; private static final String USER = "user"; private static final String PASSWORD = "password"; /** * Proxy which implements XMLA requests by talking to mondrian * in-process. This is more convenient to debug than an inter-process * request using HTTP. */ private static class MondrianInprocProxy implements XmlaOlap4jDriver.Proxy { public InputStream get(URL url, String request) throws IOException { try { Map<String, String> map = new HashMap<String, String>(); String urlString = url.toString(); byte[] bytes = XmlaSupport.processSoapXmla( request, urlString, map, null); return new ByteArrayInputStream(bytes); } catch (ServletException e) { - throw new IOException( + throw new RuntimeException( "Error while reading '" + url + "'", e); } catch (SAXException e) { - throw new IOException( + throw new RuntimeException( "Error while reading '" + url + "'", e); } } } } } // End ConnectionTest.java
false
true
public void testCell() { // todo: test Cell methods /* public CellSet getCellSet() { public int getOrdinal() { public List<Integer> getCoordinateList() { public Object getPropertyValue(Property property) { public boolean isEmpty() { public boolean isError() { public boolean isNull() { public double getDoubleValue() throws OlapException { public String getErrorText() { public Object getValue() { public String getFormattedValue() { public ResultSet drillThrough() { */ // in particular, create a result set with null, empty and error cells, // and make sure they look different // todo: test CellSetAxis methods /* public int getOrdinal() { public CellSet getCellSet() { public CellSetAxisMetaData getAxisMetaData() { public List<Position> getPositions() { public int getPositionCount() { public ListIterator<Position> iterate() { todo: test OlapResultAxisMetaData methods public org.olap4j.Axis getAxis() { public List<Hierarchy> getHierarchies() { public List<Property> getProperties() { */ } public void testProperty() { // todo: submit a query with cell and dimension properties, and make // sure the properties appear in the result set } /** * Tests different scrolling characteristics. * * <p>In one mode, you request that you get all of the positions on an axis. * You can call {@link CellSetAxis#getPositions()} and * {@link CellSetAxis#getPositions()}. * * <p>In another mode, you can iterate over the positions, calling * {@link CellSetAxis#iterate()}. Note that this method returns a * {@link java.util.ListIterator}, which has * {@link java.util.ListIterator#nextIndex()}. We could maybe extend this * interface further, to allow to jump forwards/backwards by N. * * <p>This test should check that queries work correctly when you ask * for axes as lists and iterators. If you open the query as a list, * you can get it as an iterator, but if you open it as an iterator, you * cannot get it as a list. (Or maybe you can, but it is expensive.) * * <p>The existing JDBC method {@link Connection#createStatement(int, int)}, * where the 2nd parameter has values such as * {@link ResultSet#TYPE_FORWARD_ONLY} and * {@link ResultSet#TYPE_SCROLL_INSENSITIVE}, might be the way to invoke * those two modes. * * <p>Note that cell ordinals are not well-defined until axis lengths are * known. Test that cell ordinal property is not available if the statement * is opened in this mode. * * <p>It was proposed that there would be an API to get blocks of cell * values. Not in the spec yet. */ public void testScrolling() { // todo: submit a query where you ask for different scrolling // characteristics. maybe the values int x = ResultSet.TYPE_SCROLL_INSENSITIVE; int y = ResultSet.TYPE_FORWARD_ONLY; // are how to ask for these characteristics. also need to document this // behavior in the API and the spec. in one mode, } /** * Tests creation of an MDX parser, and converting an MDX statement into * a parse tree. * * <p>Also create a set of negative tests. Do we give sensible errors if * the MDX is misformed. * * <p>Also have a set of validator tests, which check that the functions * used exist, are applied to arguments of the correct type, and members * exist. */ public void testParsing() throws SQLException { // parse Connection connection = helper.createConnection(); OlapConnection olapConnection = ((OlapWrapper) connection).unwrap(OlapConnection.class); MdxParser mdxParser = olapConnection.getParserFactory().createMdxParser(olapConnection); SelectNode select = mdxParser.parseSelect( "with member [Measures].[Foo] as ' [Measures].[Bar] ', FORMAT_STRING='xxx'\n" + " select {[Gender]} on columns, {[Store].Children} on rows\n" + "from [sales]\n" + "where [Time].[1997].[Q4]"); // unparse StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); ParseTreeWriter parseTreeWriter = new ParseTreeWriter(pw); select.unparse(parseTreeWriter); pw.flush(); String mdx = sw.toString(); TestContext.assertEqualsVerbose( TestContext.fold("WITH\n" + "MEMBER [Measures].[Foo] AS '[Measures].[Bar]', FORMAT_STRING = \"xxx\"\n" + "SELECT\n" + "{[Gender]} ON COLUMNS,\n" + "{[Store].Children} ON ROWS\n" + "FROM [sales]\n" + "WHERE [Time].[1997].[Q4]"), mdx); // build parse tree (todo) // test that get error if axes do not have unique names (todo) } /** * Tests creation of an MDX query from a parse tree. Build the parse tree * programmatically. */ public void testUnparsing() { } /** * Tests access control. The metadata (e.g. members & hierarchies) should * reflect what the current user/role can see. For example, USA.CA.SF has no children. */ /** * Abstracts the information about specific drivers and database instances * needed by this test. This allows the same test suite to be used for * multiple implementations of olap4j. */ interface Helper { Connection createConnection() throws SQLException; String getDriverUrlPrefix(); String getDriverClassName(); Connection createConnectionWithUserPassword() throws SQLException; String getURL(); boolean isMondrian(); } /** * Implementation of {@link Helper} which speaks to the mondrian olap4j * driver. */ public static class MondrianHelper implements Helper { public Connection createConnection() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } return DriverManager.getConnection( getURL(), new Properties()); } public Connection createConnectionWithUserPassword() throws SQLException { return DriverManager.getConnection( getURL(), USER, PASSWORD); } public String getDriverUrlPrefix() { return DRIVER_URL_PREFIX; } public String getDriverClassName() { return DRIVER_CLASS_NAME; } public String getURL() { return getDefaultConnectString(); } public boolean isMondrian() { return true; } public static String getDefaultConnectString() { if (true) { return "jdbc:mondrian:Jdbc='jdbc:odbc:MondrianFoodMart';Catalog='file://c:/open/mondrian/demo/FoodMart.xml';JdbcDrivers=sun.jdbc.odbc.JdbcOdbcDriver;"; } else { return "jdbc:mondrian:Jdbc=jdbc:oracle:thin:foodmart/foodmart@//marmalade.hydromatic.net:1521/XE;JdbcUser=foodmart;JdbcPassword=foodmart;Catalog=../mondrian/demo/FoodMart.xml;JdbcDrivers=oracle.jdbc.OracleDriver;"; } } public static final String DRIVER_CLASS_NAME = "mondrian.olap4j.MondrianOlap4jDriver"; public static final String DRIVER_URL_PREFIX = "jdbc:mondrian:"; private static final String USER = "user"; private static final String PASSWORD = "password"; } /** * Implementation of {@link Helper} which speaks to the XML/A olap4j * driver. */ public static class XmlaHelper implements Helper { XmlaOlap4jDriver.Proxy proxy = new MondrianInprocProxy(); public Connection createConnection() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } try { XmlaOlap4jDriver.THREAD_PROXY.set(proxy); Properties info = new Properties(); info.setProperty("UseThreadProxy", "true"); return DriverManager.getConnection( getURL(), info); } finally { XmlaOlap4jDriver.THREAD_PROXY.set(null); } } public Connection createConnectionWithUserPassword() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } try { XmlaOlap4jDriver.THREAD_PROXY.set(proxy); Properties info = new Properties(); info.setProperty("UseThreadProxy", "true"); return DriverManager.getConnection( getURL(), USER, PASSWORD); } finally { XmlaOlap4jDriver.THREAD_PROXY.set(null); } } public String getDriverUrlPrefix() { return DRIVER_URL_PREFIX; } public String getDriverClassName() { return DRIVER_CLASS_NAME; } public String getURL() { return "jdbc:xmla:Server=http://foo;UseThreadProxy=true"; } public boolean isMondrian() { return false; } public static final String DRIVER_CLASS_NAME = "org.olap4j.driver.xmla.XmlaOlap4jDriver"; public static final String DRIVER_URL_PREFIX = "jdbc:xmla:"; private static final String USER = "user"; private static final String PASSWORD = "password"; /** * Proxy which implements XMLA requests by talking to mondrian * in-process. This is more convenient to debug than an inter-process * request using HTTP. */ private static class MondrianInprocProxy implements XmlaOlap4jDriver.Proxy { public InputStream get(URL url, String request) throws IOException { try { Map<String, String> map = new HashMap<String, String>(); String urlString = url.toString(); byte[] bytes = XmlaSupport.processSoapXmla( request, urlString, map, null); return new ByteArrayInputStream(bytes); } catch (ServletException e) { throw new IOException( "Error while reading '" + url + "'", e); } catch (SAXException e) { throw new IOException( "Error while reading '" + url + "'", e); } } } } } // End ConnectionTest.java
public void testCell() { // todo: test Cell methods /* public CellSet getCellSet() { public int getOrdinal() { public List<Integer> getCoordinateList() { public Object getPropertyValue(Property property) { public boolean isEmpty() { public boolean isError() { public boolean isNull() { public double getDoubleValue() throws OlapException { public String getErrorText() { public Object getValue() { public String getFormattedValue() { public ResultSet drillThrough() { */ // in particular, create a result set with null, empty and error cells, // and make sure they look different // todo: test CellSetAxis methods /* public int getOrdinal() { public CellSet getCellSet() { public CellSetAxisMetaData getAxisMetaData() { public List<Position> getPositions() { public int getPositionCount() { public ListIterator<Position> iterate() { todo: test OlapResultAxisMetaData methods public org.olap4j.Axis getAxis() { public List<Hierarchy> getHierarchies() { public List<Property> getProperties() { */ } public void testProperty() { // todo: submit a query with cell and dimension properties, and make // sure the properties appear in the result set } /** * Tests different scrolling characteristics. * * <p>In one mode, you request that you get all of the positions on an axis. * You can call {@link CellSetAxis#getPositions()} and * {@link CellSetAxis#getPositions()}. * * <p>In another mode, you can iterate over the positions, calling * {@link CellSetAxis#iterate()}. Note that this method returns a * {@link java.util.ListIterator}, which has * {@link java.util.ListIterator#nextIndex()}. We could maybe extend this * interface further, to allow to jump forwards/backwards by N. * * <p>This test should check that queries work correctly when you ask * for axes as lists and iterators. If you open the query as a list, * you can get it as an iterator, but if you open it as an iterator, you * cannot get it as a list. (Or maybe you can, but it is expensive.) * * <p>The existing JDBC method {@link Connection#createStatement(int, int)}, * where the 2nd parameter has values such as * {@link ResultSet#TYPE_FORWARD_ONLY} and * {@link ResultSet#TYPE_SCROLL_INSENSITIVE}, might be the way to invoke * those two modes. * * <p>Note that cell ordinals are not well-defined until axis lengths are * known. Test that cell ordinal property is not available if the statement * is opened in this mode. * * <p>It was proposed that there would be an API to get blocks of cell * values. Not in the spec yet. */ public void testScrolling() { // todo: submit a query where you ask for different scrolling // characteristics. maybe the values int x = ResultSet.TYPE_SCROLL_INSENSITIVE; int y = ResultSet.TYPE_FORWARD_ONLY; // are how to ask for these characteristics. also need to document this // behavior in the API and the spec. in one mode, } /** * Tests creation of an MDX parser, and converting an MDX statement into * a parse tree. * * <p>Also create a set of negative tests. Do we give sensible errors if * the MDX is misformed. * * <p>Also have a set of validator tests, which check that the functions * used exist, are applied to arguments of the correct type, and members * exist. */ public void testParsing() throws SQLException { // parse Connection connection = helper.createConnection(); OlapConnection olapConnection = ((OlapWrapper) connection).unwrap(OlapConnection.class); MdxParser mdxParser = olapConnection.getParserFactory().createMdxParser(olapConnection); SelectNode select = mdxParser.parseSelect( "with member [Measures].[Foo] as ' [Measures].[Bar] ', FORMAT_STRING='xxx'\n" + " select {[Gender]} on columns, {[Store].Children} on rows\n" + "from [sales]\n" + "where [Time].[1997].[Q4]"); // unparse StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); ParseTreeWriter parseTreeWriter = new ParseTreeWriter(pw); select.unparse(parseTreeWriter); pw.flush(); String mdx = sw.toString(); TestContext.assertEqualsVerbose( TestContext.fold("WITH\n" + "MEMBER [Measures].[Foo] AS '[Measures].[Bar]', FORMAT_STRING = \"xxx\"\n" + "SELECT\n" + "{[Gender]} ON COLUMNS,\n" + "{[Store].Children} ON ROWS\n" + "FROM [sales]\n" + "WHERE [Time].[1997].[Q4]"), mdx); // build parse tree (todo) // test that get error if axes do not have unique names (todo) } /** * Tests creation of an MDX query from a parse tree. Build the parse tree * programmatically. */ public void testUnparsing() { } /** * Tests access control. The metadata (e.g. members & hierarchies) should * reflect what the current user/role can see. For example, USA.CA.SF has no children. */ /** * Abstracts the information about specific drivers and database instances * needed by this test. This allows the same test suite to be used for * multiple implementations of olap4j. */ interface Helper { Connection createConnection() throws SQLException; String getDriverUrlPrefix(); String getDriverClassName(); Connection createConnectionWithUserPassword() throws SQLException; String getURL(); boolean isMondrian(); } /** * Implementation of {@link Helper} which speaks to the mondrian olap4j * driver. */ public static class MondrianHelper implements Helper { public Connection createConnection() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } return DriverManager.getConnection( getURL(), new Properties()); } public Connection createConnectionWithUserPassword() throws SQLException { return DriverManager.getConnection( getURL(), USER, PASSWORD); } public String getDriverUrlPrefix() { return DRIVER_URL_PREFIX; } public String getDriverClassName() { return DRIVER_CLASS_NAME; } public String getURL() { return getDefaultConnectString(); } public boolean isMondrian() { return true; } public static String getDefaultConnectString() { if (true) { return "jdbc:mondrian:Jdbc='jdbc:odbc:MondrianFoodMart';Catalog='file://c:/open/mondrian/demo/FoodMart.xml';JdbcDrivers=sun.jdbc.odbc.JdbcOdbcDriver;"; } else { return "jdbc:mondrian:Jdbc=jdbc:oracle:thin:foodmart/foodmart@//marmalade.hydromatic.net:1521/XE;JdbcUser=foodmart;JdbcPassword=foodmart;Catalog=../mondrian/demo/FoodMart.xml;JdbcDrivers=oracle.jdbc.OracleDriver;"; } } public static final String DRIVER_CLASS_NAME = "mondrian.olap4j.MondrianOlap4jDriver"; public static final String DRIVER_URL_PREFIX = "jdbc:mondrian:"; private static final String USER = "user"; private static final String PASSWORD = "password"; } /** * Implementation of {@link Helper} which speaks to the XML/A olap4j * driver. */ public static class XmlaHelper implements Helper { XmlaOlap4jDriver.Proxy proxy = new MondrianInprocProxy(); public Connection createConnection() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } try { XmlaOlap4jDriver.THREAD_PROXY.set(proxy); Properties info = new Properties(); info.setProperty("UseThreadProxy", "true"); return DriverManager.getConnection( getURL(), info); } finally { XmlaOlap4jDriver.THREAD_PROXY.set(null); } } public Connection createConnectionWithUserPassword() throws SQLException { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new RuntimeException("oops", e); } try { XmlaOlap4jDriver.THREAD_PROXY.set(proxy); Properties info = new Properties(); info.setProperty("UseThreadProxy", "true"); return DriverManager.getConnection( getURL(), USER, PASSWORD); } finally { XmlaOlap4jDriver.THREAD_PROXY.set(null); } } public String getDriverUrlPrefix() { return DRIVER_URL_PREFIX; } public String getDriverClassName() { return DRIVER_CLASS_NAME; } public String getURL() { return "jdbc:xmla:Server=http://foo;UseThreadProxy=true"; } public boolean isMondrian() { return false; } public static final String DRIVER_CLASS_NAME = "org.olap4j.driver.xmla.XmlaOlap4jDriver"; public static final String DRIVER_URL_PREFIX = "jdbc:xmla:"; private static final String USER = "user"; private static final String PASSWORD = "password"; /** * Proxy which implements XMLA requests by talking to mondrian * in-process. This is more convenient to debug than an inter-process * request using HTTP. */ private static class MondrianInprocProxy implements XmlaOlap4jDriver.Proxy { public InputStream get(URL url, String request) throws IOException { try { Map<String, String> map = new HashMap<String, String>(); String urlString = url.toString(); byte[] bytes = XmlaSupport.processSoapXmla( request, urlString, map, null); return new ByteArrayInputStream(bytes); } catch (ServletException e) { throw new RuntimeException( "Error while reading '" + url + "'", e); } catch (SAXException e) { throw new RuntimeException( "Error while reading '" + url + "'", e); } } } } } // End ConnectionTest.java
diff --git a/jsf/plugins/org.jboss.tools.jsf.ui/src/org/jboss/tools/jsf/ui/wizard/project/ImportProjectFoldersPage.java b/jsf/plugins/org.jboss.tools.jsf.ui/src/org/jboss/tools/jsf/ui/wizard/project/ImportProjectFoldersPage.java index aae5cc831..8958d0723 100644 --- a/jsf/plugins/org.jboss.tools.jsf.ui/src/org/jboss/tools/jsf/ui/wizard/project/ImportProjectFoldersPage.java +++ b/jsf/plugins/org.jboss.tools.jsf.ui/src/org/jboss/tools/jsf/ui/wizard/project/ImportProjectFoldersPage.java @@ -1,260 +1,261 @@ /******************************************************************************* * 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.jsf.ui.wizard.project; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.jboss.tools.common.model.ui.attribute.XAttributeSupport; import org.jboss.tools.common.model.ui.attribute.adapter.IModelPropertyEditorAdapter; import org.jboss.tools.common.model.ui.attribute.editor.DirectoryFieldEditorEx; import org.jboss.tools.jsf.JSFPreference; import org.jboss.tools.jsf.web.JSFTemplate; import org.jboss.tools.jsf.web.helpers.context.ImportProjectWizardContext; import org.jboss.tools.jst.web.context.IImportWebProjectContext; import org.jboss.tools.jst.web.context.ImportWebProjectContext; import org.jboss.tools.jst.web.ui.wizards.appregister.AppRegisterComponent; import org.jboss.tools.common.model.ui.util.ModelUtilities; import org.eclipse.jface.preference.FieldEditor; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.jboss.tools.common.meta.action.*; import org.jboss.tools.common.meta.action.impl.XEntityDataImpl; import org.jboss.tools.common.meta.action.impl.handlers.DefaultCreateHandler; import org.jboss.tools.common.meta.action.impl.handlers.HUtil; public class ImportProjectFoldersPage extends WizardPage { static String[] ATTRIBUTES = { ImportProjectWizardContext.ATTR_CLASSES, ImportProjectWizardContext.ATTR_LIB, ImportProjectWizardContext.ATTR_ADD_LIB, ImportProjectWizardContext.ATTR_VERSION, ImportProjectWizardContext.ATTR_SERVLET_VERSION }; private ImportWebProjectContext context; private XAttributeSupport support; private IModelPropertyEditorAdapter webrootLocationAdapter; private IModelPropertyEditorAdapter srcLocationAdapter; private IModelPropertyEditorAdapter classesLocationAdapter; private IModelPropertyEditorAdapter libLocationAdapter; private IModelPropertyEditorAdapter addLibAdapter; private IModelPropertyEditorAdapter versionAdapter; private IModelPropertyEditorAdapter servletVersionAdapter; private PropertyChangeListener updateDataListener; AppRegisterComponent appRegister = new AppRegisterComponent(); Composite supportControl; protected ImportProjectFoldersPage(ImportWebProjectContext context) { super("Import Project Folders"); this.context = context; appRegister.setContext(context.getRegisterServerContext()); appRegister.setLayoutForSupport(getLayoutForSupport()); appRegister.setEnabling(false); XEntityData entityData = XEntityDataImpl.create( new String[][] { {ImportProjectWizardContext.PAGE_FOLDERS, ""}, //$NON-NLS-1$ {"web root", "yes"}, //$NON-NLS-1$ //$NON-NLS-2$ {"src", ""}, //$NON-NLS-1$ //$NON-NLS-2$ {ATTRIBUTES[0], ""}, //$NON-NLS-1$ {ATTRIBUTES[1], ""}, //$NON-NLS-1$ {ATTRIBUTES[2], ""}, //$NON-NLS-1$ {ATTRIBUTES[3], ""}, //$NON-NLS-1$ {ATTRIBUTES[4], ""} //$NON-NLS-1$ } ); + appRegister.setDisableContextRoot(true); XAttributeData[] ad = entityData.getAttributeData(); for (int i = 0; i < ad.length; i++) ad[i].setValue(""); //$NON-NLS-1$ if(context.getServletVersion() == null) { context.setServletVersion(JSFPreference.DEFAULT_JSF_IMPORT_SERVLET_VERSION.getValue()); } JSFTemplate t = new JSFTemplate(); String[] versions = t.getVersionList(); HUtil.hackAttributeConstraintList(new XEntityData[]{entityData}, 0, ATTRIBUTES[3], versions); if(versions.length > 0) { context.setTemplateVersion(versions[0]); entityData.setValue(ATTRIBUTES[3], versions[0]); } support = new XAttributeSupport(ModelUtilities.getPreferenceModel().getRoot(), entityData); support.setLayout(getLayoutForSupport()); webrootLocationAdapter = support.getPropertyEditorAdapterByName("web root"); //$NON-NLS-1$ srcLocationAdapter = support.getPropertyEditorAdapterByName("src"); //$NON-NLS-1$ classesLocationAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_CLASSES); libLocationAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_LIB); addLibAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_ADD_LIB); versionAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_VERSION); servletVersionAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_SERVLET_VERSION); appRegister.init(); initListeners(); } public void dispose() { super.dispose(); if (support!=null) support.dispose(); support = null; updateDataListener = null; if (supportControl!=null && !supportControl.isDisposed()) supportControl.dispose(); supportControl = null; if (appRegister!=null) appRegister.dispose(); appRegister = null; webrootLocationAdapter = null; srcLocationAdapter = null; classesLocationAdapter = null; libLocationAdapter = null; addLibAdapter = null; versionAdapter = null; servletVersionAdapter = null; } private Layout getLayoutForSupport() { GridLayout gridLayout = new GridLayout(2, false); gridLayout.marginHeight = 4; gridLayout.marginWidth = 4; gridLayout.horizontalSpacing = 10; gridLayout.verticalSpacing = 10; return gridLayout; } public void createControl(Composite parent) { initializeDialogUnits(parent); Composite c = new Composite(parent, SWT.NONE); c.setLayout(new GridLayout()); supportControl = support.createControl(c); supportControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Label label = new Label(c, SWT.SEPARATOR | SWT.HORIZONTAL); label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Control ch = appRegister.createControl(c); ch.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); setControl(c); validate(); } public void setVisible(boolean visible) { if (visible) { lock = true; webrootLocationAdapter.setValue(context.getWebRootPath()); srcLocationAdapter.setValue(context.getModules()[0].getAttributeValue("java src")); //$NON-NLS-1$ classesLocationAdapter.setValue(context.getClassesLocation()); libLocationAdapter.setValue(context.getLibLocation()); addLibAdapter.setValue("" + context.getAddLibraries()); //$NON-NLS-1$ versionAdapter.setValue(context.getTemplateVersion()); servletVersionAdapter.setValue(context.getServletVersion()); for (int i = 0; i < ATTRIBUTES.length; i++) { FieldEditor f = support.getPropertyEditorByName(ATTRIBUTES[i]).getFieldEditor(getControl().getParent()); if(f instanceof DirectoryFieldEditorEx) ((DirectoryFieldEditorEx)f).setLastPath(context.getWebInfLocation()); } appRegister.loadApplicationName(); lock = false; } validate(); super.setVisible(visible); } public void setDialogSize() { Shell shell = getShell(); getShell().setSize(shell.getSize().x,shell.getSize().y); } boolean lock = false; private void initListeners() { updateDataListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if(!lock) { updateContext(); setDependencies(); validateSrcLastPath(); validate(); } } }; support.addPropertyChangeListener(updateDataListener); appRegister.addPropertyChangeListener(inputListener); } private void updateContext() { context.getModules()[0].setAttributeValue("root", webrootLocationAdapter.getStringValue(false)); //$NON-NLS-1$ context.getModules()[0].setAttributeValue("java src", srcLocationAdapter.getStringValue(false)); //$NON-NLS-1$ context.setClassesLocation(classesLocationAdapter.getStringValue(false)); context.setLibLocation(libLocationAdapter.getStringValue(false)); context.setAddLibraries("true".equals(addLibAdapter.getStringValue(true))); //$NON-NLS-1$ context.setTemplateVersion(versionAdapter.getStringValue(true)); context.setServletVersion(servletVersionAdapter.getStringValue(true)); context.setBuildXmlLocation(""/*buildXmlLocationAdapter.getStringValue(false)*/); //$NON-NLS-1$ } public void validate() { setDependencies(); String message = appRegister.getErrorMessage(); if(message == null) { if(context.getWebRootPath() == null || context.getWebRootPath().length() == 0) { message = DefaultCreateHandler.getReguiredMessage(webrootLocationAdapter.getAttribute().getName()); } } setPageComplete(message == null); setErrorMessage(message); if(message == null && !context.isServletVersionConsistentToWebXML()) { String warning = IImportWebProjectContext.SERVLET_VERSION_WARNING; setMessage(warning, WARNING); } else { setMessage(null, 0); } validateSrcLastPath(); } void validateSrcLastPath() { String srcLocation = srcLocationAdapter.getStringValue(true); if(srcLocation.length() == 0) { String webRootLocation = webrootLocationAdapter.getStringValue(true); DirectoryFieldEditorEx srcField = (DirectoryFieldEditorEx)support.getFieldEditorByName("src"); //$NON-NLS-1$ if(webRootLocation.length() > 0 && srcField != null) { srcField.setLastPath(webRootLocation); } } } InputChangeListener inputListener = new InputChangeListener(); class InputChangeListener implements java.beans.PropertyChangeListener { public void propertyChange(java.beans.PropertyChangeEvent evt) { validate(); if(!lock) { String an = appRegister.getApplicationName(); if(an.length() > 0 && !an.equals(context.getProjectName())) { context.setApplicationName(an); } } } } protected void setDependencies() { boolean b = "true".equals(addLibAdapter.getStringValue(true)); //$NON-NLS-1$ FieldEditor f = support.getFieldEditorByName("version"); //$NON-NLS-1$ f.setEnabled(b, supportControl); } }
true
true
protected ImportProjectFoldersPage(ImportWebProjectContext context) { super("Import Project Folders"); this.context = context; appRegister.setContext(context.getRegisterServerContext()); appRegister.setLayoutForSupport(getLayoutForSupport()); appRegister.setEnabling(false); XEntityData entityData = XEntityDataImpl.create( new String[][] { {ImportProjectWizardContext.PAGE_FOLDERS, ""}, //$NON-NLS-1$ {"web root", "yes"}, //$NON-NLS-1$ //$NON-NLS-2$ {"src", ""}, //$NON-NLS-1$ //$NON-NLS-2$ {ATTRIBUTES[0], ""}, //$NON-NLS-1$ {ATTRIBUTES[1], ""}, //$NON-NLS-1$ {ATTRIBUTES[2], ""}, //$NON-NLS-1$ {ATTRIBUTES[3], ""}, //$NON-NLS-1$ {ATTRIBUTES[4], ""} //$NON-NLS-1$ } ); XAttributeData[] ad = entityData.getAttributeData(); for (int i = 0; i < ad.length; i++) ad[i].setValue(""); //$NON-NLS-1$ if(context.getServletVersion() == null) { context.setServletVersion(JSFPreference.DEFAULT_JSF_IMPORT_SERVLET_VERSION.getValue()); } JSFTemplate t = new JSFTemplate(); String[] versions = t.getVersionList(); HUtil.hackAttributeConstraintList(new XEntityData[]{entityData}, 0, ATTRIBUTES[3], versions); if(versions.length > 0) { context.setTemplateVersion(versions[0]); entityData.setValue(ATTRIBUTES[3], versions[0]); } support = new XAttributeSupport(ModelUtilities.getPreferenceModel().getRoot(), entityData); support.setLayout(getLayoutForSupport()); webrootLocationAdapter = support.getPropertyEditorAdapterByName("web root"); //$NON-NLS-1$ srcLocationAdapter = support.getPropertyEditorAdapterByName("src"); //$NON-NLS-1$ classesLocationAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_CLASSES); libLocationAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_LIB); addLibAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_ADD_LIB); versionAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_VERSION); servletVersionAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_SERVLET_VERSION); appRegister.init(); initListeners(); }
protected ImportProjectFoldersPage(ImportWebProjectContext context) { super("Import Project Folders"); this.context = context; appRegister.setContext(context.getRegisterServerContext()); appRegister.setLayoutForSupport(getLayoutForSupport()); appRegister.setEnabling(false); XEntityData entityData = XEntityDataImpl.create( new String[][] { {ImportProjectWizardContext.PAGE_FOLDERS, ""}, //$NON-NLS-1$ {"web root", "yes"}, //$NON-NLS-1$ //$NON-NLS-2$ {"src", ""}, //$NON-NLS-1$ //$NON-NLS-2$ {ATTRIBUTES[0], ""}, //$NON-NLS-1$ {ATTRIBUTES[1], ""}, //$NON-NLS-1$ {ATTRIBUTES[2], ""}, //$NON-NLS-1$ {ATTRIBUTES[3], ""}, //$NON-NLS-1$ {ATTRIBUTES[4], ""} //$NON-NLS-1$ } ); appRegister.setDisableContextRoot(true); XAttributeData[] ad = entityData.getAttributeData(); for (int i = 0; i < ad.length; i++) ad[i].setValue(""); //$NON-NLS-1$ if(context.getServletVersion() == null) { context.setServletVersion(JSFPreference.DEFAULT_JSF_IMPORT_SERVLET_VERSION.getValue()); } JSFTemplate t = new JSFTemplate(); String[] versions = t.getVersionList(); HUtil.hackAttributeConstraintList(new XEntityData[]{entityData}, 0, ATTRIBUTES[3], versions); if(versions.length > 0) { context.setTemplateVersion(versions[0]); entityData.setValue(ATTRIBUTES[3], versions[0]); } support = new XAttributeSupport(ModelUtilities.getPreferenceModel().getRoot(), entityData); support.setLayout(getLayoutForSupport()); webrootLocationAdapter = support.getPropertyEditorAdapterByName("web root"); //$NON-NLS-1$ srcLocationAdapter = support.getPropertyEditorAdapterByName("src"); //$NON-NLS-1$ classesLocationAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_CLASSES); libLocationAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_LIB); addLibAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_ADD_LIB); versionAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_VERSION); servletVersionAdapter = support.getPropertyEditorAdapterByName(ImportProjectWizardContext.ATTR_SERVLET_VERSION); appRegister.init(); initListeners(); }
diff --git a/i18nchecker/test/org/i18nchecker/I18NTest.java b/i18nchecker/test/org/i18nchecker/I18NTest.java index e3132ba..46cbb37 100644 --- a/i18nchecker/test/org/i18nchecker/I18NTest.java +++ b/i18nchecker/test/org/i18nchecker/I18NTest.java @@ -1,82 +1,82 @@ /* * Copyright (c) 2005-2010 ChemAxon Ltd. and Informatics Matters Ltd. * All Rights Reserved. * * This software is the confidential and proprietary information of * ChemAxon and Informatics Matters. You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the agreements * you entered into with ChemAxon or Informatics Matters. * * CopyrightVersion 1.2 */ package org.i18nchecker; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; import java.util.Properties; import junit.framework.TestCase; /** * Unit test for keeping project sources/resource bundles clean and fully localized. * * @author Petr */ public class I18NTest extends TestCase { public I18NTest(java.lang.String testName) { super(testName); } public void testI18N() throws Exception { File suiteDir = new File(System.getProperty("user.dir")); // Should suiteDir = suiteDir.getCanonicalFile(); File rootDir = suiteDir.getParentFile(); URLClassLoader loader = new URLClassLoader(urlToLibs(suiteDir, new String[] { "/dist/i18nchecker.jar", "/lib/antlr-runtime-3.2.jar", "/lib/SuperCSV-1.52.jar" })); Class<?> c = loader.loadClass("org.i18nchecker.I18nChecker"); Method runAsTestMethod = c.getMethod("runAsTest", File.class, String.class, Map.class); Map<String,Integer> unfinishedModules = getUnfinishedI18NModules(); - String result = (String) runAsTestMethod.invoke(null, rootDir, "i18nchecker/playground", unfinishedModules); + String result = (String) runAsTestMethod.invoke(null, rootDir, "i18nchecker/playground,i18nchecker/playground/PaintApp", unfinishedModules); if (!result.isEmpty()) { fail(result); } } private URL[] urlToLibs(File suiteDir, String[] paths) throws Exception { URL[] urls = new URL[paths.length]; for (int i = 0; i < paths.length; i++) { File jar = new File(suiteDir.getAbsolutePath() + paths[i]); assertTrue("Library not found: "+jar, jar.exists()); urls[i] = jar.toURI().toURL(); } return urls; } private Map<String,Integer> getUnfinishedI18NModules() throws IOException { Properties props = new Properties(); InputStream is = getClass().getResourceAsStream("i18n_known_errors.properties"); try { props.load(is); } finally { is.close(); } Map<String,Integer> result = new HashMap<String,Integer>(); for (String key: props.stringPropertyNames()) { int val = Integer.parseInt(props.getProperty(key, "0")); result.put(key, val); } return result; } }
true
true
public void testI18N() throws Exception { File suiteDir = new File(System.getProperty("user.dir")); // Should suiteDir = suiteDir.getCanonicalFile(); File rootDir = suiteDir.getParentFile(); URLClassLoader loader = new URLClassLoader(urlToLibs(suiteDir, new String[] { "/dist/i18nchecker.jar", "/lib/antlr-runtime-3.2.jar", "/lib/SuperCSV-1.52.jar" })); Class<?> c = loader.loadClass("org.i18nchecker.I18nChecker"); Method runAsTestMethod = c.getMethod("runAsTest", File.class, String.class, Map.class); Map<String,Integer> unfinishedModules = getUnfinishedI18NModules(); String result = (String) runAsTestMethod.invoke(null, rootDir, "i18nchecker/playground", unfinishedModules); if (!result.isEmpty()) { fail(result); } }
public void testI18N() throws Exception { File suiteDir = new File(System.getProperty("user.dir")); // Should suiteDir = suiteDir.getCanonicalFile(); File rootDir = suiteDir.getParentFile(); URLClassLoader loader = new URLClassLoader(urlToLibs(suiteDir, new String[] { "/dist/i18nchecker.jar", "/lib/antlr-runtime-3.2.jar", "/lib/SuperCSV-1.52.jar" })); Class<?> c = loader.loadClass("org.i18nchecker.I18nChecker"); Method runAsTestMethod = c.getMethod("runAsTest", File.class, String.class, Map.class); Map<String,Integer> unfinishedModules = getUnfinishedI18NModules(); String result = (String) runAsTestMethod.invoke(null, rootDir, "i18nchecker/playground,i18nchecker/playground/PaintApp", unfinishedModules); if (!result.isEmpty()) { fail(result); } }
diff --git a/src/main/java/edu/ucsd/crbs/confluence/plugins/latex/CachedLaTeXMacro.java b/src/main/java/edu/ucsd/crbs/confluence/plugins/latex/CachedLaTeXMacro.java index 70a7346..3bb368f 100644 --- a/src/main/java/edu/ucsd/crbs/confluence/plugins/latex/CachedLaTeXMacro.java +++ b/src/main/java/edu/ucsd/crbs/confluence/plugins/latex/CachedLaTeXMacro.java @@ -1,290 +1,290 @@ package edu.ucsd.crbs.confluence.plugins.latex; import com.atlassian.confluence.content.render.xhtml.ConversionContext; import com.atlassian.confluence.content.render.xhtml.ConversionContextOutputType; import com.atlassian.confluence.content.render.xhtml.DefaultConversionContext; import com.atlassian.confluence.core.ContentEntityObject; import com.atlassian.confluence.macro.Macro; import com.atlassian.confluence.macro.MacroExecutionException; import com.atlassian.confluence.pages.Attachment; import com.atlassian.confluence.pages.AttachmentManager; import com.atlassian.confluence.pages.Comment; import com.atlassian.confluence.pages.Draft; import com.atlassian.confluence.pages.PageManager; import com.atlassian.confluence.renderer.PageContext; import com.atlassian.confluence.setup.settings.SettingsManager; import com.atlassian.renderer.RenderContext; import com.atlassian.renderer.v2.RenderMode; import com.atlassian.renderer.v2.macro.BaseMacro; import com.atlassian.renderer.v2.macro.MacroException; import java.awt.Graphics2D; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.StringBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.JLabel; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.StringUtils; import org.scilab.forge.jlatexmath.TeXConstants; import org.scilab.forge.jlatexmath.TeXFormula; import org.scilab.forge.jlatexmath.TeXIcon; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CachedLaTeXMacro extends BaseMacro implements Macro { @Override public boolean hasBody() { return true; } @Override public RenderMode getBodyRenderMode() { return RenderMode.NO_RENDER; } private static final String DOT = "."; private static final String ATTACHMENT_EXT = "png"; private static final int ATTACHMENT_COMMENT_MAX_LENGTH = 254; private static final String ATTACHMENT_COMMENT_SUFFIX = "..."; private static final String ATTACHMENT_MIMETYPE = "image/png"; private final AttachmentManager attachmentManager; private final SettingsManager settingsManager; private final PageManager pageManager; private static final Logger log = LoggerFactory.getLogger(CachedLaTeXMacro.class); public CachedLaTeXMacro(AttachmentManager attachmentManager, SettingsManager settingsManager, PageManager pageManager) { this.attachmentManager = attachmentManager; this.settingsManager = settingsManager; this.pageManager = pageManager; } // Confluence < 4.0 @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public String execute(Map parameters, String body, RenderContext renderContext) throws MacroException { try { return execute(parameters, body, new DefaultConversionContext(renderContext)); } catch (MacroExecutionException e) { throw new MacroException(e); } } /** * Process a request to render a {latex} macro */ @Override public String execute(Map<String, String> parameters, String body, ConversionContext conversionContext) throws MacroExecutionException { String pageTitle = parameters.get("page"); - ContentEntityObject contentObject; + ContentEntityObject pageObject; PageContext pageContext; if (StringUtils.isNotBlank(pageTitle)) { - contentObject = getPage(conversionContext.getPageContext(), pageTitle); - pageContext = new PageContext(contentObject); - if (contentObject == null) + pageObject = getPage(conversionContext.getPageContext(), pageTitle); + pageContext = new PageContext(pageObject); + if (pageObject == null) { return null; } } else { // retrieve a reference to the body object this macro is in - contentObject = conversionContext.getEntity(); + pageObject = conversionContext.getEntity(); pageContext = conversionContext.getPageContext(); } String sortBy = null; String sortOrder = null; // CONF-9989: if this macro is run from within a comment, use the underlying page to find the attachments - if (contentObject instanceof Comment) - contentObject = ((Comment) contentObject).getOwner(); + if (pageObject instanceof Comment) + pageObject = ((Comment) pageObject).getOwner(); - boolean isPreview = (contentObject.getClass() == Draft.class); - if (isPreview) + boolean shouldUseBase64Image = ((pageObject.getClass() == Draft.class) || !pageObject.isLatestVersion()); + if (shouldUseBase64Image) { - log.debug("IS PREVIEW"); + log.debug("using base64'd inline image"); } body = body.trim(); if (body.length() < 1) { return ""; } String latexHash = SHA1(body); String attachmentFileName = latexHash + DOT + ATTACHMENT_EXT; - log.debug("{} - Attachment Filename: {}", contentObject.toString(), attachmentFileName); + log.debug("{} - Attachment Filename: {}", pageObject.toString(), attachmentFileName); - Attachment attachment = attachmentManager.getAttachment(contentObject, attachmentFileName); + Attachment attachment = attachmentManager.getAttachment(pageObject, attachmentFileName); String attachmentURL = null; if (attachment == null) { StringBuffer logString = new StringBuffer("Attachment was NULL, need to create new.\nCurrent Attachments:\n"); - List<Attachment> attachments = attachmentManager.getLatestVersionsOfAttachments(contentObject); + List<Attachment> attachments = attachmentManager.getLatestVersionsOfAttachments(pageObject); for (Attachment att : attachments) { logString.append(" - "); logString.append(att.toString()); logString.append("\n"); } log.debug(logString.toString()); // need to generate image TeXFormula formula = new TeXFormula(body); TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20); BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); JLabel jl = new JLabel(); jl.setForeground(new Color(0, 0, 0)); icon.paintIcon(jl, g2, 0, 0); final ByteArrayOutputStream output = new ByteArrayOutputStream() { @Override public synchronized byte[] toByteArray() { return this.buf; } }; try { ImageIO.write(image, "png", output); } catch (IOException e) { e.printStackTrace(); return null; } byte[] attachmentDataByteArray = output.toByteArray(); // If we're previewing, then we don't want to create the attachment yet, we just want to // create a base64 URL to show the preview. - if (isPreview) + if (shouldUseBase64Image) { attachmentURL = getBase64StringOfPNGData(attachmentDataByteArray); } // otherwise, we want to save the attachment to the page for caching else { InputStream attachmentData = new ByteArrayInputStream(attachmentDataByteArray, 0, output.size()); String attachmentComment = body; if (attachmentComment.length() > ATTACHMENT_COMMENT_MAX_LENGTH) { attachmentComment = attachmentComment.substring(0, ATTACHMENT_COMMENT_MAX_LENGTH - ATTACHMENT_COMMENT_SUFFIX.length()) + ATTACHMENT_COMMENT_SUFFIX; } attachment = new Attachment(attachmentFileName, ATTACHMENT_MIMETYPE, output.size(), attachmentComment); - attachment.setContent(contentObject); + attachment.setContent(pageObject); try { attachmentManager.saveAttachment(attachment, null, attachmentData); } catch (IOException e) { e.printStackTrace(); return null; } } } else { log.debug("Attachment was NOT NULL: {}", attachment.toString()); } if (attachmentURL == null) { attachmentURL = settingsManager.getGlobalSettings().getBaseUrl() + attachment.getDownloadPath(); } log.debug("Attachment URL: {}", attachmentURL); return (attachmentURL == null) ? null : "<div class=\"latex_img\"><img src=\"" + attachmentURL + "\" /></div>"; } private ContentEntityObject getPage(PageContext context, String pageTitleToRetrieve) { if (StringUtils.isBlank(pageTitleToRetrieve)) return context.getEntity(); String spaceKey = context.getSpaceKey(); String pageTitle = pageTitleToRetrieve; int colonIndex = pageTitleToRetrieve.indexOf(":"); if (colonIndex != -1 && colonIndex != pageTitleToRetrieve.length() - 1) { spaceKey = pageTitleToRetrieve.substring(0, colonIndex); pageTitle = pageTitleToRetrieve.substring(colonIndex + 1); } return pageManager.getPage(spaceKey, pageTitle); } @Override public BodyType getBodyType() { return BodyType.PLAIN_TEXT; } @Override public OutputType getOutputType() { return OutputType.BLOCK; } private static String SHA1(String input) { String result = null; MessageDigest crypt; try { crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(input.getBytes("utf8")); result = new String(Hex.encodeHex(crypt.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } private static String getBase64StringOfPNGData(byte[] pngData) { StringBuffer output = new StringBuffer("data:image/png;base64,"); output.append(Base64.encodeBase64String(pngData).replaceAll("(\\r|\\n)", "")); return output.toString(); } }
false
true
public String execute(Map<String, String> parameters, String body, ConversionContext conversionContext) throws MacroExecutionException { String pageTitle = parameters.get("page"); ContentEntityObject contentObject; PageContext pageContext; if (StringUtils.isNotBlank(pageTitle)) { contentObject = getPage(conversionContext.getPageContext(), pageTitle); pageContext = new PageContext(contentObject); if (contentObject == null) { return null; } } else { // retrieve a reference to the body object this macro is in contentObject = conversionContext.getEntity(); pageContext = conversionContext.getPageContext(); } String sortBy = null; String sortOrder = null; // CONF-9989: if this macro is run from within a comment, use the underlying page to find the attachments if (contentObject instanceof Comment) contentObject = ((Comment) contentObject).getOwner(); boolean isPreview = (contentObject.getClass() == Draft.class); if (isPreview) { log.debug("IS PREVIEW"); } body = body.trim(); if (body.length() < 1) { return ""; } String latexHash = SHA1(body); String attachmentFileName = latexHash + DOT + ATTACHMENT_EXT; log.debug("{} - Attachment Filename: {}", contentObject.toString(), attachmentFileName); Attachment attachment = attachmentManager.getAttachment(contentObject, attachmentFileName); String attachmentURL = null; if (attachment == null) { StringBuffer logString = new StringBuffer("Attachment was NULL, need to create new.\nCurrent Attachments:\n"); List<Attachment> attachments = attachmentManager.getLatestVersionsOfAttachments(contentObject); for (Attachment att : attachments) { logString.append(" - "); logString.append(att.toString()); logString.append("\n"); } log.debug(logString.toString()); // need to generate image TeXFormula formula = new TeXFormula(body); TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20); BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); JLabel jl = new JLabel(); jl.setForeground(new Color(0, 0, 0)); icon.paintIcon(jl, g2, 0, 0); final ByteArrayOutputStream output = new ByteArrayOutputStream() { @Override public synchronized byte[] toByteArray() { return this.buf; } }; try { ImageIO.write(image, "png", output); } catch (IOException e) { e.printStackTrace(); return null; } byte[] attachmentDataByteArray = output.toByteArray(); // If we're previewing, then we don't want to create the attachment yet, we just want to // create a base64 URL to show the preview. if (isPreview) { attachmentURL = getBase64StringOfPNGData(attachmentDataByteArray); } // otherwise, we want to save the attachment to the page for caching else { InputStream attachmentData = new ByteArrayInputStream(attachmentDataByteArray, 0, output.size()); String attachmentComment = body; if (attachmentComment.length() > ATTACHMENT_COMMENT_MAX_LENGTH) { attachmentComment = attachmentComment.substring(0, ATTACHMENT_COMMENT_MAX_LENGTH - ATTACHMENT_COMMENT_SUFFIX.length()) + ATTACHMENT_COMMENT_SUFFIX; } attachment = new Attachment(attachmentFileName, ATTACHMENT_MIMETYPE, output.size(), attachmentComment); attachment.setContent(contentObject); try { attachmentManager.saveAttachment(attachment, null, attachmentData); } catch (IOException e) { e.printStackTrace(); return null; } } } else { log.debug("Attachment was NOT NULL: {}", attachment.toString()); } if (attachmentURL == null) { attachmentURL = settingsManager.getGlobalSettings().getBaseUrl() + attachment.getDownloadPath(); } log.debug("Attachment URL: {}", attachmentURL); return (attachmentURL == null) ? null : "<div class=\"latex_img\"><img src=\"" + attachmentURL + "\" /></div>"; }
public String execute(Map<String, String> parameters, String body, ConversionContext conversionContext) throws MacroExecutionException { String pageTitle = parameters.get("page"); ContentEntityObject pageObject; PageContext pageContext; if (StringUtils.isNotBlank(pageTitle)) { pageObject = getPage(conversionContext.getPageContext(), pageTitle); pageContext = new PageContext(pageObject); if (pageObject == null) { return null; } } else { // retrieve a reference to the body object this macro is in pageObject = conversionContext.getEntity(); pageContext = conversionContext.getPageContext(); } String sortBy = null; String sortOrder = null; // CONF-9989: if this macro is run from within a comment, use the underlying page to find the attachments if (pageObject instanceof Comment) pageObject = ((Comment) pageObject).getOwner(); boolean shouldUseBase64Image = ((pageObject.getClass() == Draft.class) || !pageObject.isLatestVersion()); if (shouldUseBase64Image) { log.debug("using base64'd inline image"); } body = body.trim(); if (body.length() < 1) { return ""; } String latexHash = SHA1(body); String attachmentFileName = latexHash + DOT + ATTACHMENT_EXT; log.debug("{} - Attachment Filename: {}", pageObject.toString(), attachmentFileName); Attachment attachment = attachmentManager.getAttachment(pageObject, attachmentFileName); String attachmentURL = null; if (attachment == null) { StringBuffer logString = new StringBuffer("Attachment was NULL, need to create new.\nCurrent Attachments:\n"); List<Attachment> attachments = attachmentManager.getLatestVersionsOfAttachments(pageObject); for (Attachment att : attachments) { logString.append(" - "); logString.append(att.toString()); logString.append("\n"); } log.debug(logString.toString()); // need to generate image TeXFormula formula = new TeXFormula(body); TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20); BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); JLabel jl = new JLabel(); jl.setForeground(new Color(0, 0, 0)); icon.paintIcon(jl, g2, 0, 0); final ByteArrayOutputStream output = new ByteArrayOutputStream() { @Override public synchronized byte[] toByteArray() { return this.buf; } }; try { ImageIO.write(image, "png", output); } catch (IOException e) { e.printStackTrace(); return null; } byte[] attachmentDataByteArray = output.toByteArray(); // If we're previewing, then we don't want to create the attachment yet, we just want to // create a base64 URL to show the preview. if (shouldUseBase64Image) { attachmentURL = getBase64StringOfPNGData(attachmentDataByteArray); } // otherwise, we want to save the attachment to the page for caching else { InputStream attachmentData = new ByteArrayInputStream(attachmentDataByteArray, 0, output.size()); String attachmentComment = body; if (attachmentComment.length() > ATTACHMENT_COMMENT_MAX_LENGTH) { attachmentComment = attachmentComment.substring(0, ATTACHMENT_COMMENT_MAX_LENGTH - ATTACHMENT_COMMENT_SUFFIX.length()) + ATTACHMENT_COMMENT_SUFFIX; } attachment = new Attachment(attachmentFileName, ATTACHMENT_MIMETYPE, output.size(), attachmentComment); attachment.setContent(pageObject); try { attachmentManager.saveAttachment(attachment, null, attachmentData); } catch (IOException e) { e.printStackTrace(); return null; } } } else { log.debug("Attachment was NOT NULL: {}", attachment.toString()); } if (attachmentURL == null) { attachmentURL = settingsManager.getGlobalSettings().getBaseUrl() + attachment.getDownloadPath(); } log.debug("Attachment URL: {}", attachmentURL); return (attachmentURL == null) ? null : "<div class=\"latex_img\"><img src=\"" + attachmentURL + "\" /></div>"; }
diff --git a/sslr-impl/src/main/java/com/sonar/sslr/impl/matcher/StrictOrMatcher.java b/sslr-impl/src/main/java/com/sonar/sslr/impl/matcher/StrictOrMatcher.java index dd1fdcc2..a6e90f63 100644 --- a/sslr-impl/src/main/java/com/sonar/sslr/impl/matcher/StrictOrMatcher.java +++ b/sslr-impl/src/main/java/com/sonar/sslr/impl/matcher/StrictOrMatcher.java @@ -1,57 +1,57 @@ /* * Copyright (C) 2010 SonarSource SA * All rights reserved * mailto:contact AT sonarsource DOT com */ package com.sonar.sslr.impl.matcher; import com.sonar.sslr.api.AstNode; import com.sonar.sslr.impl.ParsingState; import com.sonar.sslr.impl.RecognitionExceptionImpl; public class StrictOrMatcher extends OrMatcher { private Matcher[] matchers; public StrictOrMatcher(Matcher... matchers) { this.matchers = matchers; } public AstNode match(ParsingState parsingState) { Matcher matchingMatcher = null; int matchingMatchers = 0; for (Matcher matcher : matchers) { if (matcher.isMatching(parsingState)) { matchingMatchers++; matchingMatcher = matcher; } } if (matchingMatchers == 1 && matchingMatcher != null) { return matchingMatcher.match(parsingState); } else if (matchingMatchers > 1) { - throw new IllegalStateException("There are two possible ways."); + throw new IllegalStateException("There are two possible ways on rule " + getRule()); } throw RecognitionExceptionImpl.create(); } @Override public void setParentRule(RuleImpl parentRule) { this.parentRule = parentRule; for (Matcher matcher : matchers) { matcher.setParentRule(parentRule); } } public String toString() { StringBuilder expr = new StringBuilder("("); for (int i = 0; i < matchers.length; i++) { expr.append(matchers[i]); if (i < matchers.length - 1) { expr.append(" | "); } } expr.append(")"); return expr.toString(); } }
true
true
public AstNode match(ParsingState parsingState) { Matcher matchingMatcher = null; int matchingMatchers = 0; for (Matcher matcher : matchers) { if (matcher.isMatching(parsingState)) { matchingMatchers++; matchingMatcher = matcher; } } if (matchingMatchers == 1 && matchingMatcher != null) { return matchingMatcher.match(parsingState); } else if (matchingMatchers > 1) { throw new IllegalStateException("There are two possible ways."); } throw RecognitionExceptionImpl.create(); }
public AstNode match(ParsingState parsingState) { Matcher matchingMatcher = null; int matchingMatchers = 0; for (Matcher matcher : matchers) { if (matcher.isMatching(parsingState)) { matchingMatchers++; matchingMatcher = matcher; } } if (matchingMatchers == 1 && matchingMatcher != null) { return matchingMatcher.match(parsingState); } else if (matchingMatchers > 1) { throw new IllegalStateException("There are two possible ways on rule " + getRule()); } throw RecognitionExceptionImpl.create(); }
diff --git a/servicemix-components/src/main/java/org/apache/servicemix/components/jms/JmsInUsingJCABinding.java b/servicemix-components/src/main/java/org/apache/servicemix/components/jms/JmsInUsingJCABinding.java index c70612982..acfee9630 100644 --- a/servicemix-components/src/main/java/org/apache/servicemix/components/jms/JmsInUsingJCABinding.java +++ b/servicemix-components/src/main/java/org/apache/servicemix/components/jms/JmsInUsingJCABinding.java @@ -1,89 +1,90 @@ /* * 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.servicemix.components.jms; import javax.jbi.JBIException; import javax.resource.spi.ActivationSpec; import javax.transaction.TransactionManager; import org.jencks.JCAConnector; import org.jencks.JCAContainer; import org.jencks.SingletonEndpointFactory; /** * Uses the JCA Container for better inbound subscription. * * @version $Revision$ */ public class JmsInUsingJCABinding extends JmsInBinding { private JCAContainer jcaContainer; private ActivationSpec activationSpec; private TransactionManager transactionManager; private JCAConnector jcaConnector; protected void init() throws JBIException { if (jcaContainer == null) { throw new IllegalArgumentException("Must specify a jcaContainer property"); } if (activationSpec == null) { throw new IllegalArgumentException("Must specify an activationSpec property"); } jcaConnector = jcaContainer.addConnector(); jcaConnector.setActivationSpec(activationSpec); if (transactionManager == null) { transactionManager = (TransactionManager) getContext().getTransactionManager(); } if (transactionManager != null) { jcaConnector.setTransactionManager(transactionManager); } jcaConnector.setEndpointFactory(new SingletonEndpointFactory(this, transactionManager)); try { jcaConnector.afterPropertiesSet(); + jcaConnector.start(); } catch (Exception e) { throw new JBIException("Unable to start jca connector", e); } } public JCAContainer getJcaContainer() { return jcaContainer; } public void setJcaContainer(JCAContainer jcaContainer) { this.jcaContainer = jcaContainer; } public ActivationSpec getActivationSpec() { return activationSpec; } public void setActivationSpec(ActivationSpec activationSpec) { this.activationSpec = activationSpec; } public TransactionManager getTransactionManager() { return transactionManager; } public void setTransactionManager(TransactionManager transactionManager) { this.transactionManager = transactionManager; } public JCAConnector getJcaConnector() { return jcaConnector; } }
true
true
protected void init() throws JBIException { if (jcaContainer == null) { throw new IllegalArgumentException("Must specify a jcaContainer property"); } if (activationSpec == null) { throw new IllegalArgumentException("Must specify an activationSpec property"); } jcaConnector = jcaContainer.addConnector(); jcaConnector.setActivationSpec(activationSpec); if (transactionManager == null) { transactionManager = (TransactionManager) getContext().getTransactionManager(); } if (transactionManager != null) { jcaConnector.setTransactionManager(transactionManager); } jcaConnector.setEndpointFactory(new SingletonEndpointFactory(this, transactionManager)); try { jcaConnector.afterPropertiesSet(); } catch (Exception e) { throw new JBIException("Unable to start jca connector", e); } }
protected void init() throws JBIException { if (jcaContainer == null) { throw new IllegalArgumentException("Must specify a jcaContainer property"); } if (activationSpec == null) { throw new IllegalArgumentException("Must specify an activationSpec property"); } jcaConnector = jcaContainer.addConnector(); jcaConnector.setActivationSpec(activationSpec); if (transactionManager == null) { transactionManager = (TransactionManager) getContext().getTransactionManager(); } if (transactionManager != null) { jcaConnector.setTransactionManager(transactionManager); } jcaConnector.setEndpointFactory(new SingletonEndpointFactory(this, transactionManager)); try { jcaConnector.afterPropertiesSet(); jcaConnector.start(); } catch (Exception e) { throw new JBIException("Unable to start jca connector", e); } }
diff --git a/javasdk-test/oauth-test/src/test/java/com/force/sdk/oauth/mock/MockTokenRetrievalService.java b/javasdk-test/oauth-test/src/test/java/com/force/sdk/oauth/mock/MockTokenRetrievalService.java index a5bf554..4eb7c5b 100644 --- a/javasdk-test/oauth-test/src/test/java/com/force/sdk/oauth/mock/MockTokenRetrievalService.java +++ b/javasdk-test/oauth-test/src/test/java/com/force/sdk/oauth/mock/MockTokenRetrievalService.java @@ -1,96 +1,98 @@ /** * Copyright (c) 2011, salesforce.com, 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 salesforce.com, 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 com.force.sdk.oauth.mock; import java.io.IOException; import org.testng.Assert; import com.force.sdk.oauth.connector.ForceOAuthConnectionInfo; import com.force.sdk.oauth.connector.TokenRetrievalService; /** * * This is a mock of the token retrieval service. Used for testing without * making API calls. The values passed in for oauth key and secret will * also be veriefied by this class. * * @author John Simone */ public class MockTokenRetrievalService implements TokenRetrievalService { private static final String CORRECT_RESPONSE = "{\"id\":\"%1$s\"," + "\"issued_at\":\"1306442444753\"," + "\"refresh_token\":\"%2$s\"," + "\"instance_url\":\"%3$s\"," + "\"signature\":\"9sR2+n0Yy06NPhWg5ll5WbEY26vcTX6hsaRmIQNXRME=\"," + "\"access_token\":\"%4$s\"}"; private String endpoint; private String refreshToken; private String instanceUrl; private String accessToken; private String oauthKey; private String oauthSecret; public MockTokenRetrievalService( String endpoint, String accessToken, String instanceUrl, String refreshToken, String oauthKey, String oauthSecret) { this.endpoint = endpoint; this.refreshToken = refreshToken; this.instanceUrl = instanceUrl; this.accessToken = accessToken; this.oauthKey = oauthKey; this.oauthSecret = oauthSecret; } @Override public String retrieveToken(String hostAndPort, String params, String refreshTok, ForceOAuthConnectionInfo connInfo) throws IOException { String[] paramArray = params.split("&"); boolean foundKey = false; boolean foundSecret = false; for (int i = 0; i < paramArray.length; i++) { if (paramArray[i].startsWith("client_id")) { - Assert.assertEquals(paramArray[i].substring("client_id=".length()), oauthKey, "Wrong OAuth key used when attempting connection"); + Assert.assertEquals(paramArray[i].substring("client_id=".length()), oauthKey, + "Wrong OAuth key used when attempting connection"); foundKey = true; } if (paramArray[i].startsWith("client_secret")) { - Assert.assertEquals(paramArray[i].substring("client_secret=".length()), oauthSecret, "Wrong OAuth key used when attempting connection"); + Assert.assertEquals(paramArray[i].substring("client_secret=".length()), oauthSecret, + "Wrong OAuth key used when attempting connection"); foundSecret = true; } } Assert.assertTrue(foundKey, "No OAuth key in url parameters"); Assert.assertTrue(foundSecret, "No OAuth secret in url parameters"); return String.format(CORRECT_RESPONSE, endpoint, refreshToken, instanceUrl, accessToken); } }
false
true
public String retrieveToken(String hostAndPort, String params, String refreshTok, ForceOAuthConnectionInfo connInfo) throws IOException { String[] paramArray = params.split("&"); boolean foundKey = false; boolean foundSecret = false; for (int i = 0; i < paramArray.length; i++) { if (paramArray[i].startsWith("client_id")) { Assert.assertEquals(paramArray[i].substring("client_id=".length()), oauthKey, "Wrong OAuth key used when attempting connection"); foundKey = true; } if (paramArray[i].startsWith("client_secret")) { Assert.assertEquals(paramArray[i].substring("client_secret=".length()), oauthSecret, "Wrong OAuth key used when attempting connection"); foundSecret = true; } } Assert.assertTrue(foundKey, "No OAuth key in url parameters"); Assert.assertTrue(foundSecret, "No OAuth secret in url parameters"); return String.format(CORRECT_RESPONSE, endpoint, refreshToken, instanceUrl, accessToken); }
public String retrieveToken(String hostAndPort, String params, String refreshTok, ForceOAuthConnectionInfo connInfo) throws IOException { String[] paramArray = params.split("&"); boolean foundKey = false; boolean foundSecret = false; for (int i = 0; i < paramArray.length; i++) { if (paramArray[i].startsWith("client_id")) { Assert.assertEquals(paramArray[i].substring("client_id=".length()), oauthKey, "Wrong OAuth key used when attempting connection"); foundKey = true; } if (paramArray[i].startsWith("client_secret")) { Assert.assertEquals(paramArray[i].substring("client_secret=".length()), oauthSecret, "Wrong OAuth key used when attempting connection"); foundSecret = true; } } Assert.assertTrue(foundKey, "No OAuth key in url parameters"); Assert.assertTrue(foundSecret, "No OAuth secret in url parameters"); return String.format(CORRECT_RESPONSE, endpoint, refreshToken, instanceUrl, accessToken); }
diff --git a/vufind/import/src/org/vufind/AlphaBrowseProcessor.java b/vufind/import/src/org/vufind/AlphaBrowseProcessor.java index 4c382022..ab9a72fd 100644 --- a/vufind/import/src/org/vufind/AlphaBrowseProcessor.java +++ b/vufind/import/src/org/vufind/AlphaBrowseProcessor.java @@ -1,170 +1,170 @@ package org.vufind; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.log4j.Logger; import org.ini4j.Ini; public class AlphaBrowseProcessor implements IResourceProcessor, IRecordProcessor { private Logger logger; private Connection vufindConn; private ProcessorResults results = new ProcessorResults("Alpha Browse Table Update"); @Override public boolean processResource(ResultSet resource) { //For alpha browse processing, everything is handled in the finish method results.incResourcesProcessed(); return true; } @Override public boolean init(Ini configIni, String serverName, Connection vufindConn, Connection econtentConn, Logger logger) { this.logger = logger; this.vufindConn = vufindConn; return true; } @Override public void finish() { logger.info("Building Alphabetic Browse tables"); //Run queries to create alphabetic browse tables from resources table try { //Clear the current browse table logger.info("Truncating title table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE title_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading titles for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(id) as numResults, title, title_sort FROM `resource` WHERE (deleted = 0 OR deleted IS NULL) GROUP BY title_sort ORDER BY title_sort"); ResultSet resourcesByTitleRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving titles to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO title_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (resourcesByTitleRS.next()){ String titleSort = resourcesByTitleRS.getString("title_sort"); if (titleSort != null && titleSort.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, resourcesByTitleRS.getLong("numResults")); insertBrowseRow.setString(3, resourcesByTitleRS.getString("title")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to title browse table"); results.addNote("Added " + (curRow -1) + " rows to title browse table"); } catch (SQLException e) { logger.error("Error creating title browse table", e); results.addNote("Error creating title browse table " + e.toString()); } try { //Clear the current browse table logger.info("Truncating author table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE author_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading authors for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(id) as numResults, author FROM `resource` WHERE (deleted = 0 OR deleted IS NULL) GROUP BY lower(author) ORDER BY lower(author)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving authors to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO author_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("author"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("author")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to author browse table"); results.addNote("Added " + (curRow -1) + " rows to author browse table"); } catch (SQLException e) { logger.error("Error creating author browse table", e); results.addNote("Error creating author browse table " + e.toString()); } //Setup subject browse try { //Clear the subject browse table logger.info("Truncating subject table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE subject_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading subjects for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(resource.id) as numResults, subject from resource inner join resource_subject on resource.id = resource_subject.resourceId inner join subject on subjectId = subject.id WHERE (deleted = 0 OR deleted is NULL) group by subjectId ORDER BY lower(subject)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving subjects to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO subject_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("subject"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("subject")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to subject browse table"); results.addNote("Added " + (curRow -1) + " rows to subject browse table"); } catch (SQLException e) { logger.error("Error creating subject browse table", e); results.addNote("Error creating subject browse table " + e.toString()); } //Setup call number browse try { //Clear the call number browse table logger.info("Truncating callnumber_browse table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE callnumber_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading call numbers for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(resource.id) as numResults, callnumber from resource inner join (select resourceId, callnumber FROM resource_callnumber group by resourceId, callnumber) titleCallNumber on resource.id = resourceId where (deleted = 0 OR deleted is NULL) group by callnumber ORDER BY lower(callnumber)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving call numbers to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO callnumber_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("callnumber"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); - insertBrowseRow.setString(3, groupedSortedRS.getString("subject")); + insertBrowseRow.setString(3, groupedSortedRS.getString("callnumber")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to call number browse table"); results.addNote("Added " + (curRow -1) + " rows to call number browse table"); } catch (SQLException e) { logger.error("Error creating callnumber browse table", e); results.addNote("Error creating call number browse table " + e.toString()); } } @Override public ProcessorResults getResults() { // TODO Auto-generated method stub return null; } }
true
true
public void finish() { logger.info("Building Alphabetic Browse tables"); //Run queries to create alphabetic browse tables from resources table try { //Clear the current browse table logger.info("Truncating title table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE title_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading titles for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(id) as numResults, title, title_sort FROM `resource` WHERE (deleted = 0 OR deleted IS NULL) GROUP BY title_sort ORDER BY title_sort"); ResultSet resourcesByTitleRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving titles to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO title_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (resourcesByTitleRS.next()){ String titleSort = resourcesByTitleRS.getString("title_sort"); if (titleSort != null && titleSort.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, resourcesByTitleRS.getLong("numResults")); insertBrowseRow.setString(3, resourcesByTitleRS.getString("title")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to title browse table"); results.addNote("Added " + (curRow -1) + " rows to title browse table"); } catch (SQLException e) { logger.error("Error creating title browse table", e); results.addNote("Error creating title browse table " + e.toString()); } try { //Clear the current browse table logger.info("Truncating author table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE author_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading authors for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(id) as numResults, author FROM `resource` WHERE (deleted = 0 OR deleted IS NULL) GROUP BY lower(author) ORDER BY lower(author)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving authors to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO author_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("author"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("author")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to author browse table"); results.addNote("Added " + (curRow -1) + " rows to author browse table"); } catch (SQLException e) { logger.error("Error creating author browse table", e); results.addNote("Error creating author browse table " + e.toString()); } //Setup subject browse try { //Clear the subject browse table logger.info("Truncating subject table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE subject_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading subjects for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(resource.id) as numResults, subject from resource inner join resource_subject on resource.id = resource_subject.resourceId inner join subject on subjectId = subject.id WHERE (deleted = 0 OR deleted is NULL) group by subjectId ORDER BY lower(subject)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving subjects to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO subject_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("subject"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("subject")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to subject browse table"); results.addNote("Added " + (curRow -1) + " rows to subject browse table"); } catch (SQLException e) { logger.error("Error creating subject browse table", e); results.addNote("Error creating subject browse table " + e.toString()); } //Setup call number browse try { //Clear the call number browse table logger.info("Truncating callnumber_browse table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE callnumber_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading call numbers for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(resource.id) as numResults, callnumber from resource inner join (select resourceId, callnumber FROM resource_callnumber group by resourceId, callnumber) titleCallNumber on resource.id = resourceId where (deleted = 0 OR deleted is NULL) group by callnumber ORDER BY lower(callnumber)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving call numbers to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO callnumber_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("callnumber"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("subject")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to call number browse table"); results.addNote("Added " + (curRow -1) + " rows to call number browse table"); } catch (SQLException e) { logger.error("Error creating callnumber browse table", e); results.addNote("Error creating call number browse table " + e.toString()); } }
public void finish() { logger.info("Building Alphabetic Browse tables"); //Run queries to create alphabetic browse tables from resources table try { //Clear the current browse table logger.info("Truncating title table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE title_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading titles for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(id) as numResults, title, title_sort FROM `resource` WHERE (deleted = 0 OR deleted IS NULL) GROUP BY title_sort ORDER BY title_sort"); ResultSet resourcesByTitleRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving titles to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO title_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (resourcesByTitleRS.next()){ String titleSort = resourcesByTitleRS.getString("title_sort"); if (titleSort != null && titleSort.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, resourcesByTitleRS.getLong("numResults")); insertBrowseRow.setString(3, resourcesByTitleRS.getString("title")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to title browse table"); results.addNote("Added " + (curRow -1) + " rows to title browse table"); } catch (SQLException e) { logger.error("Error creating title browse table", e); results.addNote("Error creating title browse table " + e.toString()); } try { //Clear the current browse table logger.info("Truncating author table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE author_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading authors for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(id) as numResults, author FROM `resource` WHERE (deleted = 0 OR deleted IS NULL) GROUP BY lower(author) ORDER BY lower(author)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving authors to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO author_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("author"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("author")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to author browse table"); results.addNote("Added " + (curRow -1) + " rows to author browse table"); } catch (SQLException e) { logger.error("Error creating author browse table", e); results.addNote("Error creating author browse table " + e.toString()); } //Setup subject browse try { //Clear the subject browse table logger.info("Truncating subject table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE subject_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading subjects for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(resource.id) as numResults, subject from resource inner join resource_subject on resource.id = resource_subject.resourceId inner join subject on subjectId = subject.id WHERE (deleted = 0 OR deleted is NULL) group by subjectId ORDER BY lower(subject)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving subjects to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO subject_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("subject"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("subject")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to subject browse table"); results.addNote("Added " + (curRow -1) + " rows to subject browse table"); } catch (SQLException e) { logger.error("Error creating subject browse table", e); results.addNote("Error creating subject browse table " + e.toString()); } //Setup call number browse try { //Clear the call number browse table logger.info("Truncating callnumber_browse table"); PreparedStatement truncateTable = vufindConn.prepareStatement("TRUNCATE callnumber_browse"); truncateTable.executeUpdate(); //Get all resources logger.info("Loading call numbers for browsing"); PreparedStatement resourcesByTitleStmt = vufindConn.prepareStatement("SELECT count(resource.id) as numResults, callnumber from resource inner join (select resourceId, callnumber FROM resource_callnumber group by resourceId, callnumber) titleCallNumber on resource.id = resourceId where (deleted = 0 OR deleted is NULL) group by callnumber ORDER BY lower(callnumber)"); ResultSet groupedSortedRS = resourcesByTitleStmt.executeQuery(); logger.info("Saving call numbers to database"); PreparedStatement insertBrowseRow = vufindConn.prepareStatement("INSERT INTO callnumber_browse (id, numResults, value) VALUES (?, ?, ?)"); int curRow = 1; while (groupedSortedRS.next()){ String sortKey = groupedSortedRS.getString("callnumber"); if (sortKey != null && sortKey.length() > 0){ insertBrowseRow.setLong(1, curRow++); insertBrowseRow.setLong(2, groupedSortedRS.getLong("numResults")); insertBrowseRow.setString(3, groupedSortedRS.getString("callnumber")); insertBrowseRow.executeUpdate(); //System.out.print("."); } } logger.info("Added " + (curRow -1) + " rows to call number browse table"); results.addNote("Added " + (curRow -1) + " rows to call number browse table"); } catch (SQLException e) { logger.error("Error creating callnumber browse table", e); results.addNote("Error creating call number browse table " + e.toString()); } }
diff --git a/experiments/src/main/java/eu/monnetproject/bliss/experiments/ExportSortFormat.java b/experiments/src/main/java/eu/monnetproject/bliss/experiments/ExportSortFormat.java index 9037b8b..89e17b5 100644 --- a/experiments/src/main/java/eu/monnetproject/bliss/experiments/ExportSortFormat.java +++ b/experiments/src/main/java/eu/monnetproject/bliss/experiments/ExportSortFormat.java @@ -1,49 +1,50 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eu.monnetproject.bliss.experiments; import eu.monnetproject.bliss.CLIOpts; import eu.monnetproject.bliss.WordMap; import java.io.File; import java.io.PrintStream; import java.util.Scanner; /** * * @author jmccrae */ public class ExportSortFormat { public static void main(String[] args) throws Exception { final CLIOpts opts = new CLIOpts(args); final File wordMapFile = opts.roFile("wordMap", "The word map"); final File corpusFile = opts.roFile("corpus", "The corpus"); final PrintStream out = opts.outFileOrStdout(); if(!opts.verify(ExportSortFormat.class)) { return; } final int W = WordMap.calcW(wordMapFile); final String[] wordMap = WordMap.inverseFromFile(wordMapFile, W, true); final Scanner in = new Scanner(CLIOpts.openInputAsMaybeZipped(corpusFile)); while(in.hasNextLine()) { final String line = in.nextLine(); final String[] ss = line.split(":"); - if(ss.length != 2) { - System.err.println("Bad line: " + line); + if(ss[ss.length-1].length() == 0) { continue; } - out.print(ss[0]); - out.print(":"); - final String[] tkIds = ss[1].split(" "); + for(int i = 0; i < ss.length - 1; i++) { + out.print(ss[0]); + out.print(":"); + } + final String[] tkIds = ss[ss.length-1].split(" "); for(String tkId : tkIds) { out.print(wordMap[Integer.parseInt(tkId)]); out.print(" "); } out.println(); } out.flush(); out.close(); in.close(); } }
false
true
public static void main(String[] args) throws Exception { final CLIOpts opts = new CLIOpts(args); final File wordMapFile = opts.roFile("wordMap", "The word map"); final File corpusFile = opts.roFile("corpus", "The corpus"); final PrintStream out = opts.outFileOrStdout(); if(!opts.verify(ExportSortFormat.class)) { return; } final int W = WordMap.calcW(wordMapFile); final String[] wordMap = WordMap.inverseFromFile(wordMapFile, W, true); final Scanner in = new Scanner(CLIOpts.openInputAsMaybeZipped(corpusFile)); while(in.hasNextLine()) { final String line = in.nextLine(); final String[] ss = line.split(":"); if(ss.length != 2) { System.err.println("Bad line: " + line); continue; } out.print(ss[0]); out.print(":"); final String[] tkIds = ss[1].split(" "); for(String tkId : tkIds) { out.print(wordMap[Integer.parseInt(tkId)]); out.print(" "); } out.println(); } out.flush(); out.close(); in.close(); }
public static void main(String[] args) throws Exception { final CLIOpts opts = new CLIOpts(args); final File wordMapFile = opts.roFile("wordMap", "The word map"); final File corpusFile = opts.roFile("corpus", "The corpus"); final PrintStream out = opts.outFileOrStdout(); if(!opts.verify(ExportSortFormat.class)) { return; } final int W = WordMap.calcW(wordMapFile); final String[] wordMap = WordMap.inverseFromFile(wordMapFile, W, true); final Scanner in = new Scanner(CLIOpts.openInputAsMaybeZipped(corpusFile)); while(in.hasNextLine()) { final String line = in.nextLine(); final String[] ss = line.split(":"); if(ss[ss.length-1].length() == 0) { continue; } for(int i = 0; i < ss.length - 1; i++) { out.print(ss[0]); out.print(":"); } final String[] tkIds = ss[ss.length-1].split(" "); for(String tkId : tkIds) { out.print(wordMap[Integer.parseInt(tkId)]); out.print(" "); } out.println(); } out.flush(); out.close(); in.close(); }
diff --git a/BitmoneyService/src/main/java/org/zeroglitch/mqtt/listener/BTListener.java b/BitmoneyService/src/main/java/org/zeroglitch/mqtt/listener/BTListener.java index 4b5d9e8..b202eed 100644 --- a/BitmoneyService/src/main/java/org/zeroglitch/mqtt/listener/BTListener.java +++ b/BitmoneyService/src/main/java/org/zeroglitch/mqtt/listener/BTListener.java @@ -1,271 +1,273 @@ package org.zeroglitch.mqtt.listener; import java.io.StringReader; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.fusesource.mqtt.client.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; //import org.zeroglitch.mqtt.data.User; import org.zeroglitch.mqtt.data.DataManager; import org.zeroglitch.mqtt.data.Transaction; import org.zeroglitch.mqtt.data.User; public class BTListener { private static final Logger log = Logger.getLogger(BTListener.class.getName()); final MQTT mqtt = new MQTT(); public BTListener() { log.info(" I am bt listener"); } public String onMessage(String body) { log.info("xxxxxxxxxxxx HFUDK FDKL:JL:SDFKJDF xxxxxxxxxxxxxxxxxxxxxxxxx"); log.info("from camel: " + body); try { Document doc = loadXMLFromString(body.toString()); NodeList n = doc.getElementsByTagName("Register"); log.info("nodeList length: " + n.getLength()); if (n.getLength() > 0) { Node node = n.item(0); Element eElement = (Element)node; log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: " + eElement.getElementsByTagName("Username").item(0).getTextContent()); log.info( eElement.getElementsByTagName("Region").item(0).getTextContent()); DataManager dm = new DataManager(); User user = dm.getUser(eElement.getElementsByTagName("Username").item(0).getTextContent()); String responseMessage = ""; if (user == null) { try { dm.insertUser(eElement.getElementsByTagName("Username").item(0).getTextContent(), eElement.getElementsByTagName("Region").item(0).getTextContent(), 5); responseMessage = "SUCCESS"; } catch (Exception e) { e.printStackTrace(); responseMessage = "FAILEDINSERT"; } } else responseMessage = "USERALREADYEXISTS"; BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderuseradd"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Username").item(0).getTextContent() + "response", responseMessage.getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Rates"); if (n.getLength() > 0){ log.info("rates: "); log.info("body: " + body); n = doc.getElementsByTagName("Rates"); Node node = n.item(0); Element eElement = (Element)node; StringBuffer ratesMessage = new StringBuffer(); ratesMessage.append("<BitmoneyExchange>"); ratesMessage.append("<Rates>"); - ratesMessage.append("<East>356.00</East>"); - ratesMessage.append("<West>256.00</West>"); + ratesMessage.append("<NA>356.00</NA>"); + ratesMessage.append("<LTAM>256.00</LTAM>"); + ratesMessage.append("<EMEA>456.00</EMEA>"); + ratesMessage.append("<APAC>556.00</APAC>"); ratesMessage.append("</Rates>"); ratesMessage.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderRates"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Username").item(0).getTextContent(), ratesMessage.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Balance"); if (n.getLength() > 0){ log.info("balance: "); log.info("body: " + body); n = doc.getElementsByTagName("Balance"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); User user = dm.getUser(eElement.getElementsByTagName("Username").item(0).getTextContent()); StringBuffer ratesMessage = new StringBuffer(); ratesMessage.append("<BitmoneyExchange>"); ratesMessage.append("<Balance>"); ratesMessage.append("<UserId>" + user.getId() + "</UserId>"); ratesMessage.append("<BalanceAmount>" + user.getBalance() + "</BalanceAmount>"); ratesMessage.append("</Balance>"); ratesMessage.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderBalance"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Callback").item(0).getTextContent(), ratesMessage.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Buy"); if (n.getLength() > 0){ log.info("buy: "); log.info("body: " + body); n = doc.getElementsByTagName("Buy"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); String userId = eElement.getElementsByTagName("UserId").item(0).getTextContent(); String credit = eElement.getElementsByTagName("Amount").item(0).getTextContent(); String debit = "0"; dm.insertTransaction(userId, credit, debit); StringBuffer message = new StringBuffer(); message.append("<BitmoneyExchange>"); message.append("<Buy>"); message.append("<Result>SUCCESS</Result>"); message.append("</Buy>"); message.append("</BitmoneyExchange>"); sendCallBack(eElement.getElementsByTagName("Callback").item(0).getTextContent() + "responseSenderBalance", eElement.getElementsByTagName("Callback").item(0).getTextContent(), message); } n = doc.getElementsByTagName("Sell"); if (n.getLength() > 0){ log.info("Sell: "); log.info("body: " + body); n = doc.getElementsByTagName("Sell"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); String userId = eElement.getElementsByTagName("UserId").item(0).getTextContent(); String debit = eElement.getElementsByTagName("Amount").item(0).getTextContent(); String credit = "0"; dm.insertTransaction(userId, credit, debit); StringBuffer message = new StringBuffer(); message.append("<BitmoneyExchange>"); message.append("<Sell>"); message.append("<Result>SUCCESS</Result>"); message.append("</Sell>"); message.append("</BitmoneyExchange>"); sendCallBack(eElement.getElementsByTagName("Callback").item(0).getTextContent() + "responseSenderBalance", eElement.getElementsByTagName("Callback").item(0).getTextContent(), message); } n = doc.getElementsByTagName("Transactions"); if (n.getLength() > 0){ log.info("Transactions: "); log.info("body: " + body); n = doc.getElementsByTagName("Transactions"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); ArrayList<Transaction> elements = dm.getTransactions(eElement.getElementsByTagName("Username").item(0).getTextContent()); StringBuffer returnData = new StringBuffer(); returnData.append("<BitmoneyExchange>"); returnData.append("<Transactions>"); for (Transaction t: elements) { returnData.append("<Transaction>"); returnData.append("<TranDate>" + t.getTrandate() + "</TranDate>"); returnData.append("<Credit>" + t.getCredit() + "</Credit>"); returnData.append("<Debit>" + t.getDebit() + "</Debit>"); returnData.append("</Transaction>"); } returnData.append("</Transactions>"); returnData.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderBalance"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Callback").item(0).getTextContent(), returnData.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } } catch (Exception ex) { Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex); } return "blah"; } private void sendCallBack(String callBackId, String callBackChanel, StringBuffer message) throws Exception { BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(callBackId); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(callBackChanel, message.toString().getBytes(), QoS.AT_LEAST_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } public static Document loadXMLFromString(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); return builder.parse(is); } public static void main(String args[]) { new BTListener(); } }
true
true
public String onMessage(String body) { log.info("xxxxxxxxxxxx HFUDK FDKL:JL:SDFKJDF xxxxxxxxxxxxxxxxxxxxxxxxx"); log.info("from camel: " + body); try { Document doc = loadXMLFromString(body.toString()); NodeList n = doc.getElementsByTagName("Register"); log.info("nodeList length: " + n.getLength()); if (n.getLength() > 0) { Node node = n.item(0); Element eElement = (Element)node; log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: " + eElement.getElementsByTagName("Username").item(0).getTextContent()); log.info( eElement.getElementsByTagName("Region").item(0).getTextContent()); DataManager dm = new DataManager(); User user = dm.getUser(eElement.getElementsByTagName("Username").item(0).getTextContent()); String responseMessage = ""; if (user == null) { try { dm.insertUser(eElement.getElementsByTagName("Username").item(0).getTextContent(), eElement.getElementsByTagName("Region").item(0).getTextContent(), 5); responseMessage = "SUCCESS"; } catch (Exception e) { e.printStackTrace(); responseMessage = "FAILEDINSERT"; } } else responseMessage = "USERALREADYEXISTS"; BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderuseradd"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Username").item(0).getTextContent() + "response", responseMessage.getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Rates"); if (n.getLength() > 0){ log.info("rates: "); log.info("body: " + body); n = doc.getElementsByTagName("Rates"); Node node = n.item(0); Element eElement = (Element)node; StringBuffer ratesMessage = new StringBuffer(); ratesMessage.append("<BitmoneyExchange>"); ratesMessage.append("<Rates>"); ratesMessage.append("<East>356.00</East>"); ratesMessage.append("<West>256.00</West>"); ratesMessage.append("</Rates>"); ratesMessage.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderRates"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Username").item(0).getTextContent(), ratesMessage.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Balance"); if (n.getLength() > 0){ log.info("balance: "); log.info("body: " + body); n = doc.getElementsByTagName("Balance"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); User user = dm.getUser(eElement.getElementsByTagName("Username").item(0).getTextContent()); StringBuffer ratesMessage = new StringBuffer(); ratesMessage.append("<BitmoneyExchange>"); ratesMessage.append("<Balance>"); ratesMessage.append("<UserId>" + user.getId() + "</UserId>"); ratesMessage.append("<BalanceAmount>" + user.getBalance() + "</BalanceAmount>"); ratesMessage.append("</Balance>"); ratesMessage.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderBalance"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Callback").item(0).getTextContent(), ratesMessage.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Buy"); if (n.getLength() > 0){ log.info("buy: "); log.info("body: " + body); n = doc.getElementsByTagName("Buy"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); String userId = eElement.getElementsByTagName("UserId").item(0).getTextContent(); String credit = eElement.getElementsByTagName("Amount").item(0).getTextContent(); String debit = "0"; dm.insertTransaction(userId, credit, debit); StringBuffer message = new StringBuffer(); message.append("<BitmoneyExchange>"); message.append("<Buy>"); message.append("<Result>SUCCESS</Result>"); message.append("</Buy>"); message.append("</BitmoneyExchange>"); sendCallBack(eElement.getElementsByTagName("Callback").item(0).getTextContent() + "responseSenderBalance", eElement.getElementsByTagName("Callback").item(0).getTextContent(), message); } n = doc.getElementsByTagName("Sell"); if (n.getLength() > 0){ log.info("Sell: "); log.info("body: " + body); n = doc.getElementsByTagName("Sell"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); String userId = eElement.getElementsByTagName("UserId").item(0).getTextContent(); String debit = eElement.getElementsByTagName("Amount").item(0).getTextContent(); String credit = "0"; dm.insertTransaction(userId, credit, debit); StringBuffer message = new StringBuffer(); message.append("<BitmoneyExchange>"); message.append("<Sell>"); message.append("<Result>SUCCESS</Result>"); message.append("</Sell>"); message.append("</BitmoneyExchange>"); sendCallBack(eElement.getElementsByTagName("Callback").item(0).getTextContent() + "responseSenderBalance", eElement.getElementsByTagName("Callback").item(0).getTextContent(), message); } n = doc.getElementsByTagName("Transactions"); if (n.getLength() > 0){ log.info("Transactions: "); log.info("body: " + body); n = doc.getElementsByTagName("Transactions"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); ArrayList<Transaction> elements = dm.getTransactions(eElement.getElementsByTagName("Username").item(0).getTextContent()); StringBuffer returnData = new StringBuffer(); returnData.append("<BitmoneyExchange>"); returnData.append("<Transactions>"); for (Transaction t: elements) { returnData.append("<Transaction>"); returnData.append("<TranDate>" + t.getTrandate() + "</TranDate>"); returnData.append("<Credit>" + t.getCredit() + "</Credit>"); returnData.append("<Debit>" + t.getDebit() + "</Debit>"); returnData.append("</Transaction>"); } returnData.append("</Transactions>"); returnData.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderBalance"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Callback").item(0).getTextContent(), returnData.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } } catch (Exception ex) { Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex); } return "blah"; }
public String onMessage(String body) { log.info("xxxxxxxxxxxx HFUDK FDKL:JL:SDFKJDF xxxxxxxxxxxxxxxxxxxxxxxxx"); log.info("from camel: " + body); try { Document doc = loadXMLFromString(body.toString()); NodeList n = doc.getElementsByTagName("Register"); log.info("nodeList length: " + n.getLength()); if (n.getLength() > 0) { Node node = n.item(0); Element eElement = (Element)node; log.info("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx: " + eElement.getElementsByTagName("Username").item(0).getTextContent()); log.info( eElement.getElementsByTagName("Region").item(0).getTextContent()); DataManager dm = new DataManager(); User user = dm.getUser(eElement.getElementsByTagName("Username").item(0).getTextContent()); String responseMessage = ""; if (user == null) { try { dm.insertUser(eElement.getElementsByTagName("Username").item(0).getTextContent(), eElement.getElementsByTagName("Region").item(0).getTextContent(), 5); responseMessage = "SUCCESS"; } catch (Exception e) { e.printStackTrace(); responseMessage = "FAILEDINSERT"; } } else responseMessage = "USERALREADYEXISTS"; BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderuseradd"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Username").item(0).getTextContent() + "response", responseMessage.getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Rates"); if (n.getLength() > 0){ log.info("rates: "); log.info("body: " + body); n = doc.getElementsByTagName("Rates"); Node node = n.item(0); Element eElement = (Element)node; StringBuffer ratesMessage = new StringBuffer(); ratesMessage.append("<BitmoneyExchange>"); ratesMessage.append("<Rates>"); ratesMessage.append("<NA>356.00</NA>"); ratesMessage.append("<LTAM>256.00</LTAM>"); ratesMessage.append("<EMEA>456.00</EMEA>"); ratesMessage.append("<APAC>556.00</APAC>"); ratesMessage.append("</Rates>"); ratesMessage.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderRates"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Username").item(0).getTextContent(), ratesMessage.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Balance"); if (n.getLength() > 0){ log.info("balance: "); log.info("body: " + body); n = doc.getElementsByTagName("Balance"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); User user = dm.getUser(eElement.getElementsByTagName("Username").item(0).getTextContent()); StringBuffer ratesMessage = new StringBuffer(); ratesMessage.append("<BitmoneyExchange>"); ratesMessage.append("<Balance>"); ratesMessage.append("<UserId>" + user.getId() + "</UserId>"); ratesMessage.append("<BalanceAmount>" + user.getBalance() + "</BalanceAmount>"); ratesMessage.append("</Balance>"); ratesMessage.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderBalance"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Callback").item(0).getTextContent(), ratesMessage.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } n = doc.getElementsByTagName("Buy"); if (n.getLength() > 0){ log.info("buy: "); log.info("body: " + body); n = doc.getElementsByTagName("Buy"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); String userId = eElement.getElementsByTagName("UserId").item(0).getTextContent(); String credit = eElement.getElementsByTagName("Amount").item(0).getTextContent(); String debit = "0"; dm.insertTransaction(userId, credit, debit); StringBuffer message = new StringBuffer(); message.append("<BitmoneyExchange>"); message.append("<Buy>"); message.append("<Result>SUCCESS</Result>"); message.append("</Buy>"); message.append("</BitmoneyExchange>"); sendCallBack(eElement.getElementsByTagName("Callback").item(0).getTextContent() + "responseSenderBalance", eElement.getElementsByTagName("Callback").item(0).getTextContent(), message); } n = doc.getElementsByTagName("Sell"); if (n.getLength() > 0){ log.info("Sell: "); log.info("body: " + body); n = doc.getElementsByTagName("Sell"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); String userId = eElement.getElementsByTagName("UserId").item(0).getTextContent(); String debit = eElement.getElementsByTagName("Amount").item(0).getTextContent(); String credit = "0"; dm.insertTransaction(userId, credit, debit); StringBuffer message = new StringBuffer(); message.append("<BitmoneyExchange>"); message.append("<Sell>"); message.append("<Result>SUCCESS</Result>"); message.append("</Sell>"); message.append("</BitmoneyExchange>"); sendCallBack(eElement.getElementsByTagName("Callback").item(0).getTextContent() + "responseSenderBalance", eElement.getElementsByTagName("Callback").item(0).getTextContent(), message); } n = doc.getElementsByTagName("Transactions"); if (n.getLength() > 0){ log.info("Transactions: "); log.info("body: " + body); n = doc.getElementsByTagName("Transactions"); Node node = n.item(0); Element eElement = (Element)node; DataManager dm = new DataManager(); ArrayList<Transaction> elements = dm.getTransactions(eElement.getElementsByTagName("Username").item(0).getTextContent()); StringBuffer returnData = new StringBuffer(); returnData.append("<BitmoneyExchange>"); returnData.append("<Transactions>"); for (Transaction t: elements) { returnData.append("<Transaction>"); returnData.append("<TranDate>" + t.getTrandate() + "</TranDate>"); returnData.append("<Credit>" + t.getCredit() + "</Credit>"); returnData.append("<Debit>" + t.getDebit() + "</Debit>"); returnData.append("</Transaction>"); } returnData.append("</Transactions>"); returnData.append("</BitmoneyExchange>"); BlockingConnection respCon = mqtt.blockingConnection(); mqtt.setClientId(eElement.getElementsByTagName("Username").item(0).getTextContent() + "responseSenderBalance"); respCon.connect(); //Publish messages to a topic using the publish method: respCon.publish(eElement.getElementsByTagName("Callback").item(0).getTextContent(), returnData.toString().getBytes(), QoS.EXACTLY_ONCE, false); //Message m = respCon.receive(); //log.info(m.getPayload().toString()); log.info("responded"); respCon.disconnect(); } } catch (Exception ex) { Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex); } return "blah"; }
diff --git a/src/main/java/nl/topicus/onderwijs/dashboard/web/components/JsonResourceBehavior.java b/src/main/java/nl/topicus/onderwijs/dashboard/web/components/JsonResourceBehavior.java index 7369547..cce6722 100644 --- a/src/main/java/nl/topicus/onderwijs/dashboard/web/components/JsonResourceBehavior.java +++ b/src/main/java/nl/topicus/onderwijs/dashboard/web/components/JsonResourceBehavior.java @@ -1,72 +1,72 @@ package nl.topicus.onderwijs.dashboard.web.components; import java.io.IOException; import org.apache.wicket.Application; import org.apache.wicket.Component; import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.model.IModel; import org.apache.wicket.request.IRequestCycle; import org.apache.wicket.request.IRequestHandler; import org.apache.wicket.request.cycle.RequestCycle; import org.apache.wicket.request.http.WebResponse; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JsonResourceBehavior<T> extends AbstractDefaultAjaxBehavior { private static final long serialVersionUID = 1L; private static final Logger log = LoggerFactory .getLogger(JsonResourceBehavior.class); private IModel<T> model; public JsonResourceBehavior(IModel<T> model) { this.model = model; } @Override protected void respond(AjaxRequestTarget target) { RequestCycle cycle = RequestCycle.get(); cycle.scheduleRequestHandlerAfterCurrent(new IRequestHandler() { @Override public void detach(IRequestCycle requestCycle) { } @Override public void respond(IRequestCycle requestCycle) { WebResponse r = (WebResponse) requestCycle.getResponse(); // Determine encoding final String encoding = Application.get() .getRequestCycleSettings().getResponseRequestEncoding(); r.setContentType("application/json; charset=" + encoding); // Make sure it is not cached by a r.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); r.setHeader("Cache-Control", "no-cache, must-revalidate"); r.setHeader("Pragma", "no-cache"); ObjectMapper mapper = new ObjectMapper(); try { - mapper.writeValue(r.getOutputStream(), model.getObject()); + r.write(mapper.writeValueAsString(model.getObject())); } catch (JsonGenerationException e) { log.error("Unable to serialize value", e); } catch (JsonMappingException e) { log.error("Unable to serialize value", e); } catch (IOException e) { log.error("Unable to serialize value", e); } } }); } @Override public void detach(Component component) { super.detach(component); model.detach(); } }
true
true
protected void respond(AjaxRequestTarget target) { RequestCycle cycle = RequestCycle.get(); cycle.scheduleRequestHandlerAfterCurrent(new IRequestHandler() { @Override public void detach(IRequestCycle requestCycle) { } @Override public void respond(IRequestCycle requestCycle) { WebResponse r = (WebResponse) requestCycle.getResponse(); // Determine encoding final String encoding = Application.get() .getRequestCycleSettings().getResponseRequestEncoding(); r.setContentType("application/json; charset=" + encoding); // Make sure it is not cached by a r.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); r.setHeader("Cache-Control", "no-cache, must-revalidate"); r.setHeader("Pragma", "no-cache"); ObjectMapper mapper = new ObjectMapper(); try { mapper.writeValue(r.getOutputStream(), model.getObject()); } catch (JsonGenerationException e) { log.error("Unable to serialize value", e); } catch (JsonMappingException e) { log.error("Unable to serialize value", e); } catch (IOException e) { log.error("Unable to serialize value", e); } } }); }
protected void respond(AjaxRequestTarget target) { RequestCycle cycle = RequestCycle.get(); cycle.scheduleRequestHandlerAfterCurrent(new IRequestHandler() { @Override public void detach(IRequestCycle requestCycle) { } @Override public void respond(IRequestCycle requestCycle) { WebResponse r = (WebResponse) requestCycle.getResponse(); // Determine encoding final String encoding = Application.get() .getRequestCycleSettings().getResponseRequestEncoding(); r.setContentType("application/json; charset=" + encoding); // Make sure it is not cached by a r.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); r.setHeader("Cache-Control", "no-cache, must-revalidate"); r.setHeader("Pragma", "no-cache"); ObjectMapper mapper = new ObjectMapper(); try { r.write(mapper.writeValueAsString(model.getObject())); } catch (JsonGenerationException e) { log.error("Unable to serialize value", e); } catch (JsonMappingException e) { log.error("Unable to serialize value", e); } catch (IOException e) { log.error("Unable to serialize value", e); } } }); }
diff --git a/src/com/nadmm/airports/SearchActivity.java b/src/com/nadmm/airports/SearchActivity.java index e44e9916..f69e6537 100644 --- a/src/com/nadmm/airports/SearchActivity.java +++ b/src/com/nadmm/airports/SearchActivity.java @@ -1,180 +1,182 @@ /* * FlightIntel for Pilots * * Copyright 2011 Nadeem Hasan <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nadmm.airports; import java.util.ArrayList; import android.app.SearchManager; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import com.nadmm.airports.DatabaseManager.Airports; import com.nadmm.airports.utils.AirportsCursorAdapter; public class SearchActivity extends ActivityBase { private TextView mHeader; private ListView mListView; private ArrayList<String> mFavorites; private CursorAdapter mListAdapter = null; @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); requestWindowFeature( Window.FEATURE_INDETERMINATE_PROGRESS ); setContentView( R.layout.airport_list_view ); mListView = (ListView) findViewById( R.id.list_view ); registerForContextMenu( mListView ); mHeader = (TextView) getLayoutInflater().inflate( R.layout.list_header, null ); mListView.addHeaderView( mHeader ); mListView.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { Cursor c = mListAdapter.getCursor(); - // Subtract 1 from position to account for header item - c.moveToPosition( position-1 ); - String siteNumber = c.getString( c.getColumnIndex( Airports.SITE_NUMBER ) ); - Intent intent = new Intent( SearchActivity.this, AirportDetailsActivity.class ); - intent.putExtra( Airports.SITE_NUMBER, siteNumber ); - startActivity( intent ); + if ( position > 0 ) { + // Subtract 1 from position to account for header item + c.moveToPosition( position-1 ); + String siteNumber = c.getString( c.getColumnIndex( Airports.SITE_NUMBER ) ); + Intent intent = new Intent( SearchActivity.this, AirportDetailsActivity.class ); + intent.putExtra( Airports.SITE_NUMBER, siteNumber ); + startActivity( intent ); + } } } ); handleIntent( getIntent() ); } @Override protected void onResume() { super.onResume(); mFavorites = mDbManager.getFavorites(); } @Override protected void onNewIntent( Intent intent ) { setIntent( intent ); handleIntent( intent ); } private void handleIntent( Intent intent ) { if ( Intent.ACTION_SEARCH.equals( intent.getAction() ) ) { // Perform the search using user provided query string String query = intent.getStringExtra( SearchManager.QUERY ); showResults( query ); } else if ( Intent.ACTION_VIEW.equals( intent.getAction() ) ) { // User clicked on a suggestion Bundle extra = intent.getExtras(); String siteNumber = extra.getString( SearchManager.EXTRA_DATA_KEY ); Intent view = new Intent( this, AirportDetailsActivity.class ); view.putExtra( Airports.SITE_NUMBER, siteNumber ); startActivity( view ); finish(); } } private void showResults( String query ) { Cursor c = managedQuery( AirportsProvider.CONTENT_URI, null, null, new String[] { query }, null ); startManagingCursor( c ); int count = c.getCount(); mListAdapter = new AirportsCursorAdapter( this, c ); mListView.setAdapter( mListAdapter ); TextView tv = (TextView) findViewById( android.R.id.empty ); tv.setVisibility( View.GONE ); mListView.setVisibility( View.VISIBLE ); mHeader.setText( getResources().getQuantityString( R.plurals.search_entry_found, count, new Object[] { count, query } ) ); } @Override public void onCreateContextMenu( ContextMenu menu, View v, ContextMenuInfo menuInfo ) { super.onCreateContextMenu( menu, v, menuInfo ); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Cursor c = mListAdapter.getCursor(); int pos = c.getPosition(); c.moveToPosition( info.position ); String siteNumber = c.getString( c.getColumnIndex( Airports.SITE_NUMBER ) ); String code = c.getString( c.getColumnIndex( Airports.ICAO_CODE ) ); if ( code == null || code.length() == 0 ) { code = c.getString( c.getColumnIndex( Airports.FAA_CODE ) ); } String facilityName = c.getString( c.getColumnIndex( Airports.FACILITY_NAME ) ); c.moveToPosition( pos ); MenuInflater inflater = getMenuInflater(); inflater.inflate( R.menu.airport_list_context_menu, menu ); menu.setHeaderTitle( code+" - "+facilityName ); // Show either "Add" or "Remove" entry depending on the context if ( mFavorites.contains( siteNumber ) ) { menu.removeItem( R.id.menu_add_favorites ); } else { menu.removeItem( R.id.menu_remove_favorites ); } } @Override public boolean onContextItemSelected( MenuItem item ) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); Cursor c = mListAdapter.getCursor(); int pos = c.getPosition(); c.moveToPosition( info.position ); String siteNumber = c.getString( c.getColumnIndex( Airports.SITE_NUMBER ) ); c.moveToPosition( pos ); switch ( item.getItemId() ) { case R.id.menu_add_favorites: mDbManager.addToFavorites( siteNumber ); mFavorites.add( siteNumber ); break; case R.id.menu_remove_favorites: mDbManager.removeFromFavorites( siteNumber ); mFavorites.remove( siteNumber ); break; case R.id.menu_view_details: Intent intent = new Intent( this, AirportDetailsActivity.class ); intent.putExtra( Airports.SITE_NUMBER, siteNumber ); startActivity( intent ); break; default: } return super.onContextItemSelected( item ); } }
true
true
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); requestWindowFeature( Window.FEATURE_INDETERMINATE_PROGRESS ); setContentView( R.layout.airport_list_view ); mListView = (ListView) findViewById( R.id.list_view ); registerForContextMenu( mListView ); mHeader = (TextView) getLayoutInflater().inflate( R.layout.list_header, null ); mListView.addHeaderView( mHeader ); mListView.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { Cursor c = mListAdapter.getCursor(); // Subtract 1 from position to account for header item c.moveToPosition( position-1 ); String siteNumber = c.getString( c.getColumnIndex( Airports.SITE_NUMBER ) ); Intent intent = new Intent( SearchActivity.this, AirportDetailsActivity.class ); intent.putExtra( Airports.SITE_NUMBER, siteNumber ); startActivity( intent ); } } ); handleIntent( getIntent() ); }
public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); requestWindowFeature( Window.FEATURE_INDETERMINATE_PROGRESS ); setContentView( R.layout.airport_list_view ); mListView = (ListView) findViewById( R.id.list_view ); registerForContextMenu( mListView ); mHeader = (TextView) getLayoutInflater().inflate( R.layout.list_header, null ); mListView.addHeaderView( mHeader ); mListView.setOnItemClickListener( new OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { Cursor c = mListAdapter.getCursor(); if ( position > 0 ) { // Subtract 1 from position to account for header item c.moveToPosition( position-1 ); String siteNumber = c.getString( c.getColumnIndex( Airports.SITE_NUMBER ) ); Intent intent = new Intent( SearchActivity.this, AirportDetailsActivity.class ); intent.putExtra( Airports.SITE_NUMBER, siteNumber ); startActivity( intent ); } } } ); handleIntent( getIntent() ); }
diff --git a/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/markers/EditIssueMarkerResolver.java b/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/markers/EditIssueMarkerResolver.java index d060bf07..3dfcf46e 100644 --- a/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/markers/EditIssueMarkerResolver.java +++ b/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/markers/EditIssueMarkerResolver.java @@ -1,77 +1,78 @@ /* * Sonar Eclipse * Copyright (C) 2010-2013 SonarSource * [email protected] * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.ide.eclipse.ui.internal.markers; import org.apache.commons.lang.ObjectUtils; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.ui.PlatformUI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.ide.eclipse.core.internal.markers.MarkerUtils; import org.sonar.ide.eclipse.ui.ISonarResolver; import org.sonar.ide.eclipse.ui.internal.Messages; import org.sonar.ide.eclipse.ui.internal.views.IssueEditorWebView; import java.text.MessageFormat; /** * @author Jérémie Lagarde */ public class EditIssueMarkerResolver implements ISonarResolver { private static final Logger LOG = LoggerFactory.getLogger(EditIssueMarkerResolver.class); private String label; private String description; public boolean canResolve(final IMarker marker) { try { final Object ruleName = marker.getAttribute(MarkerUtils.SONAR_MARKER_RULE_NAME_ATTR); label = MessageFormat.format(Messages.EditIssueMarkerResolver_label, ruleName); description = Messages.EditIssueMarkerResolver_description; final Object issueId = marker.getAttribute(MarkerUtils.SONAR_MARKER_ISSUE_ID_ATTR); - return issueId != null; + final boolean isNew = Boolean.TRUE.equals(marker.getAttribute(MarkerUtils.SONAR_MARKER_IS_NEW_ATTR)); + return issueId != null && !isNew; } catch (final CoreException e) { return false; } } public String getDescription() { return description; } public String getLabel() { return label; } public boolean resolve(final IMarker marker, final IFile cu) { try { final String issueId = ObjectUtils.toString(marker.getAttribute(MarkerUtils.SONAR_MARKER_ISSUE_ID_ATTR)); IssueEditorWebView view = (IssueEditorWebView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(IssueEditorWebView.ID); view.open(issueId, marker.getResource()); } catch (Exception e) { LOG.error("Unable to open Issue Editor Web View", e); } return false; } }
true
true
public boolean canResolve(final IMarker marker) { try { final Object ruleName = marker.getAttribute(MarkerUtils.SONAR_MARKER_RULE_NAME_ATTR); label = MessageFormat.format(Messages.EditIssueMarkerResolver_label, ruleName); description = Messages.EditIssueMarkerResolver_description; final Object issueId = marker.getAttribute(MarkerUtils.SONAR_MARKER_ISSUE_ID_ATTR); return issueId != null; } catch (final CoreException e) { return false; } }
public boolean canResolve(final IMarker marker) { try { final Object ruleName = marker.getAttribute(MarkerUtils.SONAR_MARKER_RULE_NAME_ATTR); label = MessageFormat.format(Messages.EditIssueMarkerResolver_label, ruleName); description = Messages.EditIssueMarkerResolver_description; final Object issueId = marker.getAttribute(MarkerUtils.SONAR_MARKER_ISSUE_ID_ATTR); final boolean isNew = Boolean.TRUE.equals(marker.getAttribute(MarkerUtils.SONAR_MARKER_IS_NEW_ATTR)); return issueId != null && !isNew; } catch (final CoreException e) { return false; } }
diff --git a/freeplane_plugin_latex/src/org/freeplane/plugin/latex/LatexNodeHook.java b/freeplane_plugin_latex/src/org/freeplane/plugin/latex/LatexNodeHook.java index 56cd27f7b..a45f5a6e1 100644 --- a/freeplane_plugin_latex/src/org/freeplane/plugin/latex/LatexNodeHook.java +++ b/freeplane_plugin_latex/src/org/freeplane/plugin/latex/LatexNodeHook.java @@ -1,207 +1,207 @@ /* * Freeplane - mind map editor * Copyright (C) 2008 Dimitry Polivaev * * This file author is Dimitry Polivaev * * 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.plugin.latex; import java.awt.Container; import java.util.Set; import org.freeplane.core.extension.IExtension; import org.freeplane.core.undo.IActor; import org.freeplane.features.map.INodeView; import org.freeplane.features.map.MapModel; import org.freeplane.features.map.NodeModel; import org.freeplane.features.mode.Controller; import org.freeplane.features.mode.ModeController; import org.freeplane.features.mode.NodeHookDescriptor; import org.freeplane.features.mode.PersistentNodeHook; import org.freeplane.features.ui.INodeViewLifeCycleListener; import org.freeplane.n3.nanoxml.XMLElement; import org.freeplane.view.swing.map.NodeView; /** * @author Dimitry Polivaev * @file LatexNodeHook.java * @package freeplane.modes.mindmapmode */ @NodeHookDescriptor(hookName = "plugins/latex/LatexNodeHook.properties", // onceForMap = false) class LatexNodeHook extends PersistentNodeHook implements INodeViewLifeCycleListener { static final int VIEWER_POSITION = 4; /** */ public LatexNodeHook() { super(); final ModeController modeController = Controller.getCurrentModeController(); modeController.addINodeViewLifeCycleListener(this); } @Override public void add(final NodeModel node, final IExtension extension) { final LatexExtension latexExtension = (LatexExtension) extension; for (final INodeView iNodeView : node.getViewers()) { final NodeView view = (NodeView) iNodeView; createViewer(latexExtension, view); } super.add(node, extension); } @Override protected IExtension createExtension(final NodeModel node, final XMLElement element) { final LatexExtension latexExtension = new LatexExtension(); if (element != null) { final String equation = element.getAttribute("EQUATION", null); if (equation == null) { // error: do not create anything return null; } latexExtension.setEquation(equation); Controller.getCurrentModeController().getMapController() .nodeChanged(node, NodeModel.UNKNOWN_PROPERTY, null, null); } return latexExtension; } @Override protected HookAction createHookAction() { return null; } void createViewer(final LatexExtension model, final NodeView view) { final LatexViewer comp = new LatexViewer(this, model); final Set<NodeView> viewers = model.getViewers(); viewers.add(view); view.addContent(comp, VIEWER_POSITION); } void deleteViewer(final LatexExtension model, final NodeView nodeView) { final Set<NodeView> viewers = model.getViewers(); if (!viewers.contains(nodeView)) { return; } nodeView.removeContent(VIEWER_POSITION); viewers.remove(nodeView); } @Override protected Class<LatexExtension> getExtensionClass() { return LatexExtension.class; } public void onViewCreated(final Container container) { final NodeView nodeView = (NodeView) container; final LatexExtension latexExtension = (LatexExtension) nodeView.getModel().getExtension(LatexExtension.class); if (latexExtension == null) { return; } createViewer(latexExtension, nodeView); } public void onViewRemoved(final Container container) { final NodeView nodeView = (NodeView) container; final LatexExtension latexExtension = (LatexExtension) nodeView.getModel().getExtension(LatexExtension.class); if (latexExtension == null) { return; } deleteViewer(latexExtension, nodeView); } @Override protected void remove(final NodeModel node, final IExtension extension) { final LatexExtension latexExtension = (LatexExtension) extension; latexExtension.removeViewers(); super.remove(node, extension); } @Override protected void saveExtension(final IExtension extension, final XMLElement element) { final LatexExtension latexExtension = (LatexExtension) extension; element.setAttribute("EQUATION", latexExtension.getEquation()); super.saveExtension(extension, element); } void setEquationUndoable(final LatexExtension model, final String newEquation) { final String equation = model.getEquation(); if (equation.equals(newEquation)) { return; } final IActor actor = new IActor() { private final String oldEquation = equation; public void act() { model.setEquation(newEquation); final MapModel map = Controller.getCurrentModeController().getController().getMap(); Controller.getCurrentModeController().getMapController().setSaved(map, false); } public String getDescription() { return "setLatexEquationUndoable"; } public void undo() { model.setEquation(oldEquation); } }; Controller.getCurrentModeController().execute(actor, Controller.getCurrentModeController().getController().getMap()); } @Override public void undoableToggleHook(final NodeModel node, final IExtension extension) { if (extension != null) { super.undoableToggleHook(node, extension); return; } final String equation = LatexEditor.editLatex("", node); if (equation == null || "".equals(equation.trim())) { return; } super.undoableToggleHook(node, null); final LatexExtension latexExtension = (LatexExtension) node.getExtension(LatexExtension.class); setEquationUndoable(latexExtension, equation); } void editLatexInEditor(final NodeModel node) { LatexExtension latexExtension = (LatexExtension) node.getExtension(LatexExtension.class); final String equation; //if no LaTeX is attached, create one if (latexExtension == null) { equation = LatexEditor.editLatex("", node); } //if LaTeX is present edit it else { equation = LatexEditor.editLatex(latexExtension.getEquation(), node); } // return on cancel if (equation == null) { return; } if (!"".equals(equation.trim())) { if (latexExtension == null) { latexExtension = new LatexExtension(); - add(node, latexExtension); + undoableActivateHook(node, latexExtension); } setEquationUndoable(latexExtension, equation); } else if (latexExtension != null) { undoableDeactivateHook(node); } } }
true
true
void editLatexInEditor(final NodeModel node) { LatexExtension latexExtension = (LatexExtension) node.getExtension(LatexExtension.class); final String equation; //if no LaTeX is attached, create one if (latexExtension == null) { equation = LatexEditor.editLatex("", node); } //if LaTeX is present edit it else { equation = LatexEditor.editLatex(latexExtension.getEquation(), node); } // return on cancel if (equation == null) { return; } if (!"".equals(equation.trim())) { if (latexExtension == null) { latexExtension = new LatexExtension(); add(node, latexExtension); } setEquationUndoable(latexExtension, equation); } else if (latexExtension != null) { undoableDeactivateHook(node); } }
void editLatexInEditor(final NodeModel node) { LatexExtension latexExtension = (LatexExtension) node.getExtension(LatexExtension.class); final String equation; //if no LaTeX is attached, create one if (latexExtension == null) { equation = LatexEditor.editLatex("", node); } //if LaTeX is present edit it else { equation = LatexEditor.editLatex(latexExtension.getEquation(), node); } // return on cancel if (equation == null) { return; } if (!"".equals(equation.trim())) { if (latexExtension == null) { latexExtension = new LatexExtension(); undoableActivateHook(node, latexExtension); } setEquationUndoable(latexExtension, equation); } else if (latexExtension != null) { undoableDeactivateHook(node); } }
diff --git a/src/net/sf/freecol/common/networking/BuildColonyMessage.java b/src/net/sf/freecol/common/networking/BuildColonyMessage.java index 5cf46d59e..edc55910d 100644 --- a/src/net/sf/freecol/common/networking/BuildColonyMessage.java +++ b/src/net/sf/freecol/common/networking/BuildColonyMessage.java @@ -1,135 +1,136 @@ /** * Copyright (C) 2002-2012 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.networking; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.server.FreeColServer; import net.sf.freecol.server.model.ServerPlayer; import org.w3c.dom.Element; /** * The message sent when the client requests building of a colony. */ public class BuildColonyMessage extends DOMMessage { /** * The name of the new colony. **/ String colonyName; /** * The unit that is building the colony. */ String builderId; /** * Create a new <code>BuildColonyMessage</code> with the supplied name * and building unit. * * @param colonyName The name for the new colony. * @param builder The <code>Unit</code> to do the building. */ public BuildColonyMessage(String colonyName, Unit builder) { this.colonyName = colonyName; this.builderId = builder.getId(); } /** * Create a new <code>BuildColonyMessage</code> from a supplied element. * * @param game The <code>Game</code> this message belongs to. * @param element The <code>Element</code> to use to create the message. */ public BuildColonyMessage(Game game, Element element) { this.colonyName = element.getAttribute("name"); this.builderId = element.getAttribute("unit"); } /** * Handle a "buildColony"-message. * * @param server The <code>FreeColServer</code> handling the request. * @param player The <code>Player</code> building the colony. * @param connection The <code>Connection</code> the message is from. * @return An update <code>Element</code> defining the new colony * and updating its surrounding tiles, or an error * <code>Element</code> on failure. */ public Element handle(FreeColServer server, Player player, Connection connection) { + Game game = server.getGame(); ServerPlayer serverPlayer = server.getPlayer(connection); Unit unit; try { unit = player.getFreeColGameObject(builderId, Unit.class); } catch (Exception e) { return DOMMessage.clientError(e.getMessage()); } if (!unit.canBuildColony()) { return DOMMessage.clientError("Unit " + builderId + " can not build colony."); } if (colonyName == null) { return DOMMessage.clientError("Null colony name"); } else if (Player.ASSIGN_SETTLEMENT_NAME.equals(colonyName)) { ; // ok - } else if (player.getColony(colonyName) != null) { + } else if (game.getSettlement(colonyName) != null) { return DOMMessage.clientError("Non-unique colony name " + colonyName); } Tile tile = unit.getTile(); if (!player.canClaimToFoundSettlement(tile)) { return DOMMessage.clientError("Can not build colony on tile: " + tile); } // Build can proceed. return server.getInGameController() .buildSettlement(serverPlayer, unit, colonyName); } /** * Convert this BuildColonyMessage to XML. * * @return The XML representation of this message. */ public Element toXMLElement() { return createMessage(getXMLElementTagName(), "name", colonyName, "unit", builderId); } /** * The tag name of the root element representing this object. * * @return "buildColony". */ public static String getXMLElementTagName() { return "buildColony"; } }
false
true
public Element handle(FreeColServer server, Player player, Connection connection) { ServerPlayer serverPlayer = server.getPlayer(connection); Unit unit; try { unit = player.getFreeColGameObject(builderId, Unit.class); } catch (Exception e) { return DOMMessage.clientError(e.getMessage()); } if (!unit.canBuildColony()) { return DOMMessage.clientError("Unit " + builderId + " can not build colony."); } if (colonyName == null) { return DOMMessage.clientError("Null colony name"); } else if (Player.ASSIGN_SETTLEMENT_NAME.equals(colonyName)) { ; // ok } else if (player.getColony(colonyName) != null) { return DOMMessage.clientError("Non-unique colony name " + colonyName); } Tile tile = unit.getTile(); if (!player.canClaimToFoundSettlement(tile)) { return DOMMessage.clientError("Can not build colony on tile: " + tile); } // Build can proceed. return server.getInGameController() .buildSettlement(serverPlayer, unit, colonyName); }
public Element handle(FreeColServer server, Player player, Connection connection) { Game game = server.getGame(); ServerPlayer serverPlayer = server.getPlayer(connection); Unit unit; try { unit = player.getFreeColGameObject(builderId, Unit.class); } catch (Exception e) { return DOMMessage.clientError(e.getMessage()); } if (!unit.canBuildColony()) { return DOMMessage.clientError("Unit " + builderId + " can not build colony."); } if (colonyName == null) { return DOMMessage.clientError("Null colony name"); } else if (Player.ASSIGN_SETTLEMENT_NAME.equals(colonyName)) { ; // ok } else if (game.getSettlement(colonyName) != null) { return DOMMessage.clientError("Non-unique colony name " + colonyName); } Tile tile = unit.getTile(); if (!player.canClaimToFoundSettlement(tile)) { return DOMMessage.clientError("Can not build colony on tile: " + tile); } // Build can proceed. return server.getInGameController() .buildSettlement(serverPlayer, unit, colonyName); }
diff --git a/src/main/java/be/vodelee/belote/controller/RunController.java b/src/main/java/be/vodelee/belote/controller/RunController.java index f033991..e6042c9 100644 --- a/src/main/java/be/vodelee/belote/controller/RunController.java +++ b/src/main/java/be/vodelee/belote/controller/RunController.java @@ -1,105 +1,106 @@ package be.vodelee.belote.controller; import java.util.ArrayList; import java.util.List; import java.util.Random; import be.vodelee.belote.entity.Game; import be.vodelee.belote.entity.Run; import be.vodelee.belote.entity.Team; public class RunController { public Run buildRun(List<Team> teamList, List<Run> runList) { Run run = new Run(); run.setGames(new ArrayList<Game>()); // # of game in a run = # team /2 // int numberOfGames = (Integer) teamList.size() / 2; List<TeamWithAlreadyPlayedTeamList> teamWithAlreadyPlayedTeamList = buildAlreadyPlayedList(teamList, runList); int plantage = 0; boolean isEveryTeamAssigned = false; label : while (!isEveryTeamAssigned) { try { Game game = new Game(); boolean isGameValid = false; game.setTeam1(teamWithAlreadyPlayedTeamList.remove(0).getTeam()); Random r = new Random(); int i = r.nextInt(teamWithAlreadyPlayedTeamList.size()); while (!isGameValid) { if (!teamWithAlreadyPlayedTeamList.get(i).getAlreadyPlayedList().contains(game.getTeam1())) { game.setTeam2(teamWithAlreadyPlayedTeamList.remove(i).getTeam()); isGameValid = true; } else { i++; } } run.getGames().add(game); if (teamWithAlreadyPlayedTeamList.isEmpty()) { isEveryTeamAssigned = true; } } catch (Exception e) { System.err.println(plantage++); //TODO Fix this with a proper while loop teamWithAlreadyPlayedTeamList = buildAlreadyPlayedList(teamList, runList); + // TODO bug : reset the game list continue label; } } return run; } private List<TeamWithAlreadyPlayedTeamList> buildAlreadyPlayedList(List<Team> teamList, List<Run> runList) { List<TeamWithAlreadyPlayedTeamList> teamWithAlreadyPlayedTeamList = new ArrayList<TeamWithAlreadyPlayedTeamList>(); for (Team t : teamList) { TeamWithAlreadyPlayedTeamList couple = new TeamWithAlreadyPlayedTeamList(); couple.setTeam(t); List<Team> alreadyPlayedList = new ArrayList<Team>(); for (Run r : runList) { for (Game g : r.getGames()) { // For this game, if the team 1 is the team. if (g.getTeam1().equals(t)) { alreadyPlayedList.add(g.getTeam2()); } if (g.getTeam2().equals(t)) { alreadyPlayedList.add(g.getTeam1()); } } } couple.setAlreadyPlayedList(alreadyPlayedList); teamWithAlreadyPlayedTeamList.add(couple); } return teamWithAlreadyPlayedTeamList; } private class TeamWithAlreadyPlayedTeamList { private Team team; private List<Team> alreadyPlayedList; public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } public List<Team> getAlreadyPlayedList() { return alreadyPlayedList; } public void setAlreadyPlayedList(List<Team> alreadyPlayedList) { this.alreadyPlayedList = alreadyPlayedList; } @Override public String toString() { return "TeamWithAlreadyPlayedTeamList [team=" + team + ", alreadyPlayedList=" + alreadyPlayedList + "]"; } } }
true
true
public Run buildRun(List<Team> teamList, List<Run> runList) { Run run = new Run(); run.setGames(new ArrayList<Game>()); // # of game in a run = # team /2 // int numberOfGames = (Integer) teamList.size() / 2; List<TeamWithAlreadyPlayedTeamList> teamWithAlreadyPlayedTeamList = buildAlreadyPlayedList(teamList, runList); int plantage = 0; boolean isEveryTeamAssigned = false; label : while (!isEveryTeamAssigned) { try { Game game = new Game(); boolean isGameValid = false; game.setTeam1(teamWithAlreadyPlayedTeamList.remove(0).getTeam()); Random r = new Random(); int i = r.nextInt(teamWithAlreadyPlayedTeamList.size()); while (!isGameValid) { if (!teamWithAlreadyPlayedTeamList.get(i).getAlreadyPlayedList().contains(game.getTeam1())) { game.setTeam2(teamWithAlreadyPlayedTeamList.remove(i).getTeam()); isGameValid = true; } else { i++; } } run.getGames().add(game); if (teamWithAlreadyPlayedTeamList.isEmpty()) { isEveryTeamAssigned = true; } } catch (Exception e) { System.err.println(plantage++); //TODO Fix this with a proper while loop teamWithAlreadyPlayedTeamList = buildAlreadyPlayedList(teamList, runList); continue label; } } return run; }
public Run buildRun(List<Team> teamList, List<Run> runList) { Run run = new Run(); run.setGames(new ArrayList<Game>()); // # of game in a run = # team /2 // int numberOfGames = (Integer) teamList.size() / 2; List<TeamWithAlreadyPlayedTeamList> teamWithAlreadyPlayedTeamList = buildAlreadyPlayedList(teamList, runList); int plantage = 0; boolean isEveryTeamAssigned = false; label : while (!isEveryTeamAssigned) { try { Game game = new Game(); boolean isGameValid = false; game.setTeam1(teamWithAlreadyPlayedTeamList.remove(0).getTeam()); Random r = new Random(); int i = r.nextInt(teamWithAlreadyPlayedTeamList.size()); while (!isGameValid) { if (!teamWithAlreadyPlayedTeamList.get(i).getAlreadyPlayedList().contains(game.getTeam1())) { game.setTeam2(teamWithAlreadyPlayedTeamList.remove(i).getTeam()); isGameValid = true; } else { i++; } } run.getGames().add(game); if (teamWithAlreadyPlayedTeamList.isEmpty()) { isEveryTeamAssigned = true; } } catch (Exception e) { System.err.println(plantage++); //TODO Fix this with a proper while loop teamWithAlreadyPlayedTeamList = buildAlreadyPlayedList(teamList, runList); // TODO bug : reset the game list continue label; } } return run; }
diff --git a/power-tools-parent/power-tools-web/src/main/java/org/powertools/web/WebDriverLibrary.java b/power-tools-parent/power-tools-web/src/main/java/org/powertools/web/WebDriverLibrary.java index 3d90938..434afd1 100644 --- a/power-tools-parent/power-tools-web/src/main/java/org/powertools/web/WebDriverLibrary.java +++ b/power-tools-parent/power-tools-web/src/main/java/org/powertools/web/WebDriverLibrary.java @@ -1,56 +1,55 @@ /* Copyright 2014 by Martin Gijsen (www.DeAnalist.nl) * * This file is part of the PowerTools engine. * * The PowerTools engine 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. * * The PowerTools engine 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 the PowerTools engine. If not, see <http://www.gnu.org/licenses/>. */ package org.powertools.web; import org.powertools.engine.KeywordName; import org.powertools.engine.RunTime; import org.powertools.engine.TestRunResultPublisher; import org.powertools.engine.reports.TestResultSubscriber; public final class WebDriverLibrary extends WebLibrary { public WebDriverLibrary (RunTime runTime) { super (runTime); TestRunResultPublisher mPublisher = runTime.getPublisher (); TestResultSubscriber subscriber = new TestResultSubscriberMakeScreenshotByError (this); mPublisher.subscribeToTestResults (subscriber); runTime.addSharedObject ("WebDriverLibrary", this); } @KeywordName ("OpenBrowser") public boolean OpenBrowser_At_ (String typeString, String url) { return OpenBrowser_Version_At_OnGrid_(typeString, null, url, null); } public boolean OpenBrowser_Version_At_OnGrid_ (String typeString, String browserVersion, String url, String hubUrl) { if (mBrowser != null) { - mRunTime.reportError ("browser is already open"); return false; } else { - BrowserType browserType = getBrowserType (typeString); - String urlToOpen = url.isEmpty () ? "about:blank" : completeUrl (url); - WebDriverBrowser myBrowser = new WebDriverBrowser (mRunTime); - mBrowser = myBrowser; - return myBrowser.open (browserType, browserVersion, urlToOpen, mRunTime.getContext ().getResultsDirectory (), hubUrl); + BrowserType browserType = getBrowserType (typeString); + String urlToOpen = url.isEmpty () ? "about:blank" : completeUrl (url); + WebDriverBrowser browser = new WebDriverBrowser (mRunTime); + mBrowser = browser; + return browser.open (browserType, browserVersion, urlToOpen, mRunTime.getContext ().getResultsDirectory (), hubUrl); } } }
false
true
public boolean OpenBrowser_Version_At_OnGrid_ (String typeString, String browserVersion, String url, String hubUrl) { if (mBrowser != null) { mRunTime.reportError ("browser is already open"); return false; } else { BrowserType browserType = getBrowserType (typeString); String urlToOpen = url.isEmpty () ? "about:blank" : completeUrl (url); WebDriverBrowser myBrowser = new WebDriverBrowser (mRunTime); mBrowser = myBrowser; return myBrowser.open (browserType, browserVersion, urlToOpen, mRunTime.getContext ().getResultsDirectory (), hubUrl); } }
public boolean OpenBrowser_Version_At_OnGrid_ (String typeString, String browserVersion, String url, String hubUrl) { if (mBrowser != null) { return false; } else { BrowserType browserType = getBrowserType (typeString); String urlToOpen = url.isEmpty () ? "about:blank" : completeUrl (url); WebDriverBrowser browser = new WebDriverBrowser (mRunTime); mBrowser = browser; return browser.open (browserType, browserVersion, urlToOpen, mRunTime.getContext ().getResultsDirectory (), hubUrl); } }
diff --git a/riot/src/org/riotfamily/riot/list/command/core/EditCommand.java b/riot/src/org/riotfamily/riot/list/command/core/EditCommand.java index cc069b7d2..58431be56 100755 --- a/riot/src/org/riotfamily/riot/list/command/core/EditCommand.java +++ b/riot/src/org/riotfamily/riot/list/command/core/EditCommand.java @@ -1,52 +1,52 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Riot. * * The Initial Developer of the Original Code is * Neteye GmbH. * Portions created by the Initial Developer are Copyright (C) 2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Felix Gnass [fgnass at neteye dot de] * * ***** END LICENSE BLOCK ***** */ package org.riotfamily.riot.list.command.core; import org.riotfamily.riot.editor.EditorDefinition; import org.riotfamily.riot.list.command.CommandContext; import org.riotfamily.riot.list.command.CommandResult; import org.riotfamily.riot.list.command.result.GotoUrlResult; import org.springframework.util.Assert; /** * Command that displays the editor associated with the current list. */ public class EditCommand extends AbstractCommand { public static final String ACTION_EDIT = "edit"; public static final String ACTION_ADD = "add"; protected String getAction(CommandContext context) { return context.getBean() != null ? ACTION_EDIT : ACTION_ADD; } public CommandResult execute(CommandContext context) { EditorDefinition def = context.getListDefinition().getDisplayDefinition(); - Assert.notNull(def, "A DisplayDefinition must be set"); + Assert.notNull(def, "A DisplayDefinition must be set in order to use the EditCommand."); return new GotoUrlResult(context, def.getEditorUrl( context.getObjectId(), context.getParentId())); } }
true
true
public CommandResult execute(CommandContext context) { EditorDefinition def = context.getListDefinition().getDisplayDefinition(); Assert.notNull(def, "A DisplayDefinition must be set"); return new GotoUrlResult(context, def.getEditorUrl( context.getObjectId(), context.getParentId())); }
public CommandResult execute(CommandContext context) { EditorDefinition def = context.getListDefinition().getDisplayDefinition(); Assert.notNull(def, "A DisplayDefinition must be set in order to use the EditCommand."); return new GotoUrlResult(context, def.getEditorUrl( context.getObjectId(), context.getParentId())); }
diff --git a/ds_common/com/madpcgaming/ds/handlers/ConfigurationHandler.java b/ds_common/com/madpcgaming/ds/handlers/ConfigurationHandler.java index 0f06274..6d6b592 100644 --- a/ds_common/com/madpcgaming/ds/handlers/ConfigurationHandler.java +++ b/ds_common/com/madpcgaming/ds/handlers/ConfigurationHandler.java @@ -1,77 +1,77 @@ package com.madpcgaming.ds.handlers; import java.io.File; import java.util.logging.Level; import com.madpcgaming.ds.lib.BlockIds; import com.madpcgaming.ds.lib.Reference; import com.madpcgaming.ds.lib.Strings; import cpw.mods.fml.common.FMLLog; import net.minecraftforge.common.Configuration; public class ConfigurationHandler { public static Configuration configuration; public static final String CATEGORY_BLOCK = "Blocks"; public static final String CATERGORY_ITEM = "Items"; // Mobs Spawn public static boolean spawnReaperz = true; public static boolean spawnAngel = true; public static boolean spawnGolems = true; // Boss Spawns public static boolean spawnBrann = true; public static boolean spawnLuft = true; public static boolean spawnJorden = true; public static boolean spawnVann = true; public static boolean spawnGrim = true; public static boolean spawnMico = true; public static void init(File configFile) { configuration = new Configuration(configFile); try { configuration.load(); /* Block ID Configuration */ BlockIds.SHADOW_STONE = configuration.getBlock( - Strings.SHADOW_STONE_NAME, BlockIds.SHADOW_STONE).getInt( + Strings.SHADOW_STONE_NAME, BlockIds.SHADOW_STONE_DEFAULT).getInt( BlockIds.SHADOW_STONE_DEFAULT); BlockIds.SHADOW_PORTAL = configuration.getBlock( - Strings.SHADOW_PORTAL_NAME, BlockIds.SHADOW_PORTAL).getInt( + Strings.SHADOW_PORTAL_NAME, BlockIds.SHADOW_PORTAL_DEFAULT).getInt( BlockIds.SHADOW_STONE_DEFAULT); BlockIds.BRIGHT_STONE = configuration.getBlock( - Strings.BRIGHT_STONE_NAME, BlockIds.BRIGHT_STONE).getInt( + Strings.BRIGHT_STONE_NAME, BlockIds.BRIGHT_STONE_DEFAULT).getInt( BlockIds.BRIGHT_STONE_DEFAULT); BlockIds.BRIGHT_PORTAL = configuration.getBlock( - Strings.BRIGHT_PORTAL_NAME, BlockIds.BRIGHT_PORTAL).getInt( + Strings.BRIGHT_PORTAL_NAME, BlockIds.BRIGHT_PORTAL_DEFAULT).getInt( BlockIds.BRIGHT_PORTAL_DEFAULT); /* Item ID Configuration */ /* GUI ID Configuration */ } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Whoops!" + Reference.MOD_NAME + " goofed loading the configuraiton file"); } finally { configuration.save(); } } public static void set(String catergoryName, String propertyName, String newValue) { configuration.load(); if (configuration.getCategoryNames().contains(catergoryName)) { if (configuration.getCategory(propertyName).containsKey( propertyName)) { configuration.getCategory(catergoryName).get(propertyName) .set(newValue); } } configuration.save(); } }
false
true
public static void init(File configFile) { configuration = new Configuration(configFile); try { configuration.load(); /* Block ID Configuration */ BlockIds.SHADOW_STONE = configuration.getBlock( Strings.SHADOW_STONE_NAME, BlockIds.SHADOW_STONE).getInt( BlockIds.SHADOW_STONE_DEFAULT); BlockIds.SHADOW_PORTAL = configuration.getBlock( Strings.SHADOW_PORTAL_NAME, BlockIds.SHADOW_PORTAL).getInt( BlockIds.SHADOW_STONE_DEFAULT); BlockIds.BRIGHT_STONE = configuration.getBlock( Strings.BRIGHT_STONE_NAME, BlockIds.BRIGHT_STONE).getInt( BlockIds.BRIGHT_STONE_DEFAULT); BlockIds.BRIGHT_PORTAL = configuration.getBlock( Strings.BRIGHT_PORTAL_NAME, BlockIds.BRIGHT_PORTAL).getInt( BlockIds.BRIGHT_PORTAL_DEFAULT); /* Item ID Configuration */ /* GUI ID Configuration */ } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Whoops!" + Reference.MOD_NAME + " goofed loading the configuraiton file"); } finally { configuration.save(); } }
public static void init(File configFile) { configuration = new Configuration(configFile); try { configuration.load(); /* Block ID Configuration */ BlockIds.SHADOW_STONE = configuration.getBlock( Strings.SHADOW_STONE_NAME, BlockIds.SHADOW_STONE_DEFAULT).getInt( BlockIds.SHADOW_STONE_DEFAULT); BlockIds.SHADOW_PORTAL = configuration.getBlock( Strings.SHADOW_PORTAL_NAME, BlockIds.SHADOW_PORTAL_DEFAULT).getInt( BlockIds.SHADOW_STONE_DEFAULT); BlockIds.BRIGHT_STONE = configuration.getBlock( Strings.BRIGHT_STONE_NAME, BlockIds.BRIGHT_STONE_DEFAULT).getInt( BlockIds.BRIGHT_STONE_DEFAULT); BlockIds.BRIGHT_PORTAL = configuration.getBlock( Strings.BRIGHT_PORTAL_NAME, BlockIds.BRIGHT_PORTAL_DEFAULT).getInt( BlockIds.BRIGHT_PORTAL_DEFAULT); /* Item ID Configuration */ /* GUI ID Configuration */ } catch (Exception e) { FMLLog.log(Level.SEVERE, e, "Whoops!" + Reference.MOD_NAME + " goofed loading the configuraiton file"); } finally { configuration.save(); } }
diff --git a/src/main/java/hs/mediasystem/screens/Navigator.java b/src/main/java/hs/mediasystem/screens/Navigator.java index 0b5b7ad5..04840c35 100644 --- a/src/main/java/hs/mediasystem/screens/Navigator.java +++ b/src/main/java/hs/mediasystem/screens/Navigator.java @@ -1,176 +1,176 @@ package hs.mediasystem.screens; import java.util.ArrayList; import java.util.List; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; public class Navigator { private final Navigator parentNavigator; private Destination current; public Navigator(final Navigator parent) { this.parentNavigator = parent; } public Navigator() { this(null); } public synchronized List<Destination> getTrail() { List<Destination> trail = new ArrayList<>(); Destination dest = current; while(dest != null) { trail.add(0, dest); dest = dest.previous; } if(current.childNavigator != null) { List<Destination> childTrail = current.childNavigator.getTrail(); trail.addAll(childTrail.subList(1, childTrail.size())); } return trail; } public synchronized void back() { System.out.println("[INFO] Navigator.back() - From: " + current); if(current != null) { if(current.previous != null) { current.doOutro(); if(current.modal) { current = current.previous; } else { current = current.previous; current.doIntro(); current.doExecute(); } fireActionEvent(); } else if(parentNavigator != null) { - current.childNavigator = null; - current.childNavigator.onNavigation.set(null); + parentNavigator.current.childNavigator.onNavigation.set(null); + parentNavigator.current.childNavigator = null; parentNavigator.back(); } } } public synchronized void navigateTo(Destination destination) { System.out.println("[INFO] Navigator.navigateTo() - " + destination); destination.modal = false; navigate(destination); } public synchronized void navigateToModal(Destination destination) { System.out.println("[INFO] Navigator.navigateToModal() - " + destination); destination.modal = true; navigate(destination); } private void navigate(Destination destination) { if(!destination.modal) { if(current != null) { current.doOutro(); } } if(parentNavigator != null && current == null) { parentNavigator.current.childNavigator = this; onNavigation.set(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { parentNavigator.fireActionEvent(); } }); } destination.previous = current; current = destination; destination.doIntro(); destination.doExecute(); fireActionEvent(); } private void fireActionEvent() { EventHandler<ActionEvent> eventHandler = onNavigation.get(); if(eventHandler != null) { eventHandler.handle(new ActionEvent(this, null)); } } private final ObjectProperty<EventHandler<ActionEvent>> onNavigation = new SimpleObjectProperty<>(); public ObjectProperty<EventHandler<ActionEvent>> onNavigation() { return onNavigation; } public static abstract class Destination { private final String description; private Navigator childNavigator; private Destination previous; //private Destination next; private boolean modal; private boolean initialised; public Destination(String description) { this.description = description; } public String getDescription() { return description; } public Destination getPrevious() { return previous; } private void doInit() { if(!initialised) { initialised = true; init(); } } private void doIntro() { doInit(); intro(); } private void doExecute() { doInit(); execute(); } private void doOutro() { doInit(); outro(); } protected void init() { } protected abstract void execute(); protected void intro() { } protected void outro() { } @Override public String toString() { return "Destination('" + description + "'; modal=" + modal + ")"; } } }
true
true
public synchronized void back() { System.out.println("[INFO] Navigator.back() - From: " + current); if(current != null) { if(current.previous != null) { current.doOutro(); if(current.modal) { current = current.previous; } else { current = current.previous; current.doIntro(); current.doExecute(); } fireActionEvent(); } else if(parentNavigator != null) { current.childNavigator = null; current.childNavigator.onNavigation.set(null); parentNavigator.back(); } } }
public synchronized void back() { System.out.println("[INFO] Navigator.back() - From: " + current); if(current != null) { if(current.previous != null) { current.doOutro(); if(current.modal) { current = current.previous; } else { current = current.previous; current.doIntro(); current.doExecute(); } fireActionEvent(); } else if(parentNavigator != null) { parentNavigator.current.childNavigator.onNavigation.set(null); parentNavigator.current.childNavigator = null; parentNavigator.back(); } } }
diff --git a/src/uk/org/smithfamily/mslogger/activity/MSLoggerActivity.java b/src/uk/org/smithfamily/mslogger/activity/MSLoggerActivity.java index 0c0155d..bb1e208 100644 --- a/src/uk/org/smithfamily/mslogger/activity/MSLoggerActivity.java +++ b/src/uk/org/smithfamily/mslogger/activity/MSLoggerActivity.java @@ -1,1234 +1,1234 @@ package uk.org.smithfamily.mslogger.activity; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import uk.org.smithfamily.mslogger.ApplicationSettings; import uk.org.smithfamily.mslogger.GPSLocationManager; import uk.org.smithfamily.mslogger.MSLoggerApplication; import uk.org.smithfamily.mslogger.R; import uk.org.smithfamily.mslogger.ecuDef.Megasquirt; import uk.org.smithfamily.mslogger.log.DatalogManager; import uk.org.smithfamily.mslogger.log.DebugLogManager; import uk.org.smithfamily.mslogger.log.EmailManager; import uk.org.smithfamily.mslogger.log.FRDLogManager; import uk.org.smithfamily.mslogger.widgets.BarGraph; import uk.org.smithfamily.mslogger.widgets.Gauge; import uk.org.smithfamily.mslogger.widgets.GaugeDetails; import uk.org.smithfamily.mslogger.widgets.GaugeRegister; import uk.org.smithfamily.mslogger.widgets.Histogram; import uk.org.smithfamily.mslogger.widgets.Indicator; import uk.org.smithfamily.mslogger.widgets.IndicatorManager; import uk.org.smithfamily.mslogger.widgets.NumericIndicator; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.GestureDetector; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; /** * Main activity class where the main window (gauges) are and where the bottom menu is handled */ public class MSLoggerActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener, OnClickListener { private BroadcastReceiver updateReceiver = new Reciever(); private IndicatorManager indicatorManager; private TextView messages; private TextView rps; static private Boolean ready = null; private Indicator[] indicators = new Indicator[5]; private boolean gaugeEditEnabled; boolean scrolling; private LinearLayout layout; private static final int SHOW_PREFS = 124230; private boolean registered; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkSDCard(); DebugLogManager.INSTANCE.log(getPackageName(),Log.ASSERT); try { String app_ver = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName; DebugLogManager.INSTANCE.log(app_ver,Log.ASSERT); } catch (NameNotFoundException e) { DebugLogManager.INSTANCE.logException(e); } dumpPreferences(); setContentView(R.layout.displaygauge); messages = (TextView) findViewById(R.id.messages); rps = (TextView) findViewById(R.id.RPS); /* * Get status message from saved instance, for example when * switching from landscape to portrait mode */ if (savedInstanceState != null) { if (!savedInstanceState.getString("status_message").equals("")) { messages.setText(savedInstanceState.getString("status_message")); } if (!savedInstanceState.getString("rps_message").equals("")) { rps.setText(savedInstanceState.getString("rps_message")); } } findGauges(); SharedPreferences prefsManager = PreferenceManager.getDefaultSharedPreferences(MSLoggerActivity.this); prefsManager.registerOnSharedPreferenceChangeListener(MSLoggerActivity.this); indicatorManager = IndicatorManager.INSTANCE; indicatorManager.setDisabled(true); ApplicationSettings.INSTANCE.setDefaultAdapter(BluetoothAdapter.getDefaultAdapter()); GPSLocationManager.INSTANCE.start(); ApplicationSettings.INSTANCE.setAutoConnectOverride(null); registerMessages(); Intent serverIntent = new Intent(this, StartupActivity.class); startActivityForResult(serverIntent, MSLoggerApplication.PROBE_ECU); } /** * Save the bottom text views content so they can keep their state while device is rotated */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("status_message", messages.getText().toString()); outState.putString("rps_message", rps.getText().toString()); } /** * Dump the user preference into the log file for easier debugging */ private void dumpPreferences() { SharedPreferences prefsManager = PreferenceManager.getDefaultSharedPreferences(MSLoggerActivity.this); Map<String, ?> prefs = prefsManager.getAll(); for(Entry<String, ?> entry : prefs.entrySet()) { DebugLogManager.INSTANCE.log("Preference:"+entry.getKey()+":"+entry.getValue(), Log.ASSERT); } } /** * Complete the initialisation and load/init the gauges */ private void completeCreate() { if (ready == null) { new InitTask().execute((Void) null); } else { finaliseInit(); } } /** * Finilise the initialisation of the application by initialising the gauges, checking bluetooth, SD card and starting connection to the Megasquirt */ private void finaliseInit() { initGauges(); checkBTDeviceSet(); checkSDCard(); Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecu != null) { ecu.start(); } } /** * Check if the SD card is present */ private void checkSDCard() { boolean cardOK = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); ApplicationSettings.INSTANCE.setWritable(cardOK); if (!cardOK) { showDialog(2); } } /** * Clean up messages and GPS when the app is stopped */ @Override protected void onDestroy() { deRegisterMessages(); GPSLocationManager.INSTANCE.stop(); super.onDestroy(); } /** * Save the gauges when the app is stopped */ @Override public void onStop() { super.onStop(); saveGauges(); } /** * Ask to select a Bluetooth device is none is selected */ private void checkBTDeviceSet() { if (!ApplicationSettings.INSTANCE.btDeviceSelected()) { messages.setText(R.string.please_select); } } /** * Save current selected gauges in preferences */ private void saveGauges() { if (!(indicators[0] != null && indicators[1] != null && indicators[2] != null && indicators[3] != null)) { findGauges(); } if (indicators[0] != null && indicators[1] != null && indicators[2] != null && indicators[3] != null) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Editor editor = prefs.edit(); if (!indicators[0].getName().equals(Gauge.DEAD_GAUGE_NAME)) { editor.putString("gauge1", indicators[0].getName()); } if (!indicators[1].getName().equals(Gauge.DEAD_GAUGE_NAME)) { editor.putString("gauge2", indicators[1].getName()); } if (!indicators[2].getName().equals(Gauge.DEAD_GAUGE_NAME)) { editor.putString("gauge3", indicators[2].getName()); } if (!indicators[3].getName().equals(Gauge.DEAD_GAUGE_NAME)) { editor.putString("gauge4", indicators[3].getName()); } if (indicators[4] != null && !indicators[4].getName().equals(Gauge.DEAD_GAUGE_NAME)) { editor.putString("gauge5", indicators[4].getName()); } editor.commit(); } } /** * Load the gauges */ private void loadGauges() { Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); GaugeRegister.INSTANCE.flush(); ecu.initGauges(); } /** * Init the gauges with the proper gauge saved in preference, default to firmware defined gauge if preference are empty */ private void initGauges() { layout = (LinearLayout) (findViewById(R.id.layout)); findGauges(); Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); String[] defaultGauges = ecu.defaultGauges(); indicators[0].initFromName(ApplicationSettings.INSTANCE.getOrSetPref("gauge1", defaultGauges[0])); indicators[1].initFromName(ApplicationSettings.INSTANCE.getOrSetPref("gauge2", defaultGauges[1])); indicators[2].initFromName(ApplicationSettings.INSTANCE.getOrSetPref("gauge3", defaultGauges[2])); indicators[3].initFromName(ApplicationSettings.INSTANCE.getOrSetPref("gauge4", defaultGauges[3])); if (indicators[4] != null) { indicators[4].initFromName(ApplicationSettings.INSTANCE.getOrSetPref("gauge5", defaultGauges[4])); } applyWidgetTypeToIndicators(); if (gaugeEditEnabled) { bindIndicatorsEditEvents(); } else { MarkListener l = new MarkListener(layout); setTouchListeners(l); } for (int i = 0; i < indicators.length; i++) { if (indicators[i] != null) { indicators[i].invalidate(); } } } /** * Scan all indicators and make sure they are the type they should be */ public void applyWidgetTypeToIndicators() { // Look at all indicators and make sure they are the right type for (int i = 0; i < indicators.length; i++) { if (indicators[i] != null) { boolean wasWrongType = false; String name = indicators[i].getName(); int id = indicators[i].getId(); GaugeDetails gd = GaugeRegister.INSTANCE.getGaugeDetails(name); if (gd.getType().equals(getString(R.string.gauge)) && !(indicators[i] instanceof Gauge)) { indicators[i] = new Gauge(this); wasWrongType = true; } else if (gd.getType().equals(getString(R.string.bargraph)) && !(indicators[i] instanceof BarGraph)) { indicators[i] = new BarGraph(this); wasWrongType = true; } else if (gd.getType().equals(getString(R.string.numeric_indicator)) && !(indicators[i] instanceof NumericIndicator)) { indicators[i] = new NumericIndicator(this); wasWrongType = true; } else if (gd.getType().equals(getString(R.string.histogram)) && !(indicators[i] instanceof Histogram)) { indicators[i] = new Histogram(this); wasWrongType = true; } if (wasWrongType) { View indicator = findViewById(id); // Remove indicator with wrong type ViewGroup parentView = (ViewGroup) indicator.getParent(); int index = parentView.indexOfChild(indicator); parentView.removeView(indicator); // Add new indicator back in place parentView.addView(indicators[i], index); indicators[i].setId(id); indicators[i].initFromName(name); LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f); indicators[i].setLayoutParams(params); indicators[i].setFocusable(true); indicators[i].setFocusableInTouchMode(true); bindIndicatorsEditEventsToIndex(i); } } } } /** * Replace the instance of an indicator, used in EditGaugeDialog, after modifying indicator details * * @param indicator * @param indicatorIndex */ public void replaceIndicator(Indicator indicator, int indicatorIndex) { indicators[indicatorIndex] = indicator; } /** * Bind touch listener to indicator * * @param i Indicator index to bind edit events to */ public void bindIndicatorsEditEventsToIndex(int i) { indicators[i].setGestureDetector(new GestureDetector(new IndicatorGestureListener(MSLoggerActivity.this, indicators[i], i))); OnTouchListener gestureListener = new View.OnTouchListener() { private Indicator firstIndicator; /** * Determines if given points are inside view * * @param x X coordinate of point * @param y Y coordinate of point * @param view View object to compare * @return true If the points are within view bounds, false otherwise */ private boolean isPointInsideView(float x, float y, View view) { int location[] = new int[2]; view.getLocationOnScreen(location); int viewX = location[0]; int viewY = location[1]; // Point is inside view bounds if (x > viewX && x < viewX + view.getWidth() && y > viewY && y < viewY + view.getHeight()) { return true; } else { return false; } } /** * * @param v * @param event */ public boolean onTouch(View v, MotionEvent event) { if (firstIndicator != null && firstIndicator.getGestureDetector().onTouchEvent(event)) { return true; } else if (event.getAction() == MotionEvent.ACTION_DOWN) { this.firstIndicator = ((Indicator) v); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { Indicator lastIndicator = null; int lastIndexIndicator = 0; // Find indicator when the finger was lifted for (int i = 0; lastIndicator == null && i < indicators.length && indicators[i] != null; i++) { if (this.isPointInsideView(event.getRawX(),event.getRawY(),indicators[i])) { lastIndicator = indicators[i]; lastIndexIndicator = i; } } if (lastIndicator != null && firstIndicator.getId() != lastIndicator.getId()) { String firstIndicatorName = firstIndicator.getName(); String lastIndicatorName = lastIndicator.getName(); int firstIndexIndicator = 0; // Find first touched indicator index for (int i = 0; i < indicators.length; i++) { if (indicators[i] != null && firstIndicator.getId() == indicators[i].getId()) { firstIndexIndicator = i; } } // Remove old last indicator ViewGroup parentLastIndicatorView = (ViewGroup) lastIndicator.getParent(); int indexLast = parentLastIndicatorView.indexOfChild(lastIndicator); parentLastIndicatorView.removeView(lastIndicator); // Remove old first indicator ViewGroup parentFirstIndicatorView = (ViewGroup) firstIndicator.getParent(); int indexFirst = parentFirstIndicatorView.indexOfChild(firstIndicator); parentFirstIndicatorView.removeView(firstIndicator); /* * Since we are removing both view at the same time, if both were in the same parent, * we need to do some magic to keep them in the right order. */ if (parentFirstIndicatorView == parentLastIndicatorView) { if (indexLast > indexFirst) { indexLast -= 1; } else { indexFirst += 1; } } // Add first touched indicator in place of last touched indicator parentLastIndicatorView.addView(indicators[lastIndexIndicator], indexLast); parentLastIndicatorView.forceLayout(); // Add last touched indicator in place of first touched indicator parentFirstIndicatorView.addView(indicators[firstIndexIndicator], indexFirst); parentFirstIndicatorView.forceLayout(); - // Init the indicator with their new gauge details + // Init the indicator with their new indicator details indicators[lastIndexIndicator].initFromName(firstIndicatorName); indicators[firstIndexIndicator].initFromName(lastIndicatorName); indicators[lastIndexIndicator].setId(lastIndicator.getId()); indicators[firstIndexIndicator].setId(firstIndicator.getId()); - // If indicators weren't the same type, we have to change their type + // If indicators weren't the same type, we have to change their types if (firstIndicator.getType() != lastIndicator.getType()) { applyWidgetTypeToIndicators(); } - // Re-map the right indicators with the right view + // Re-map the right indicators with the right views findGauges(); return true; } } return false; } }; indicators[i].setOnClickListener(MSLoggerActivity.this); indicators[i].setOnTouchListener(gestureListener); } /** * */ public void bindIndicatorsEditEvents() { for (int i = 0; i < indicators.length; i++) { if (indicators[i] != null) { bindIndicatorsEditEventsToIndex(i); } } } /** * Set all the gauges variable with their view */ private void findGauges() { indicators[0] = (Indicator) findViewById(R.id.g1); indicators[1] = (Indicator) findViewById(R.id.g2); indicators[2] = (Indicator) findViewById(R.id.g3); indicators[3] = (Indicator) findViewById(R.id.g4); indicators[4] = (Indicator) findViewById(R.id.g5); } /** * Set the touch listener on the gauge * * @param l */ private void setTouchListeners(MarkListener l) { for (int i = 0; i < indicators.length; i++) { if (indicators[i] != null) { indicators[i].setOnTouchListener(l); } } } /** * Register the receiver with the message to receive from the Megasquirt connection */ private void registerMessages() { IntentFilter connectedFilter = new IntentFilter(Megasquirt.CONNECTED); registerReceiver(updateReceiver, connectedFilter); IntentFilter disconnectedFilter = new IntentFilter(Megasquirt.DISCONNECTED); registerReceiver(updateReceiver, disconnectedFilter); IntentFilter dataFilter = new IntentFilter(Megasquirt.NEW_DATA); registerReceiver(updateReceiver, dataFilter); IntentFilter msgFilter = new IntentFilter(ApplicationSettings.GENERAL_MESSAGE); registerReceiver(updateReceiver, msgFilter); IntentFilter rpsFilter = new IntentFilter(ApplicationSettings.RPS_MESSAGE); registerReceiver(updateReceiver, rpsFilter); IntentFilter toastFilter = new IntentFilter(ApplicationSettings.TOAST); registerReceiver(updateReceiver, toastFilter); registered = true; } /** * Unregister receiver */ private void deRegisterMessages() { if (registered) { unregisterReceiver(updateReceiver); } } /** * Process data got from Megasquirt and update the gauges with it */ protected void processData() { Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); List<Indicator> indicators; if ((indicators = indicatorManager.getIndicators()) != null) { indicatorManager.setDisabled(false); for (Indicator i : indicators) { String channelName = i.getChannel(); if (channelName != null) { double value = ecu.getField(channelName); i.setValue(value); } else { i.setValue(0); } } } } /** * * @param menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } /** * Triggered just before the bottom menu are displayed, used to update the state of some menu items * * @param menu */ @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem editItem = menu.findItem(R.id.gaugeEditing); Megasquirt ecuDefinition = ApplicationSettings.INSTANCE.getEcuDefinition(); editItem.setEnabled(ecuDefinition != null); if (gaugeEditEnabled) { editItem.setIcon(R.drawable.ic_menu_disable_gauge_editing); editItem.setTitle(R.string.disable_gauge_edit); } else { editItem.setIcon(R.drawable.ic_menu_enable_gauge_editing); editItem.setTitle(R.string.enable_gauge_edit); } MenuItem connectionItem = menu.findItem(R.id.forceConnection); if (ecuDefinition != null && ecuDefinition.isRunning()) { connectionItem.setIcon(R.drawable.ic_menu_disconnect); connectionItem.setTitle(R.string.disconnect); } else { connectionItem.setIcon(R.drawable.ic_menu_connect); connectionItem.setTitle(R.string.connect); } MenuItem loggingItem = menu.findItem(R.id.forceLogging); loggingItem.setEnabled(ecuDefinition != null); if (ecuDefinition != null && ecuDefinition.isLogging()) { loggingItem.setIcon(R.drawable.ic_menu_stop_logging); loggingItem.setTitle(R.string.stop_logging); } else { loggingItem.setIcon(R.drawable.ic_menu_start_logging); loggingItem.setTitle(R.string.start_logging); } return super.onPrepareOptionsMenu(menu); } /** * Triggered when a bottom menu item is clicked * * @param item The clicked menu item */ @Override public boolean onOptionsItemSelected(MenuItem item) { checkBTDeviceSet(); int itemId = item.getItemId(); if (itemId == R.id.forceConnection) { toggleConnection(); return true; } else if (itemId == R.id.gaugeEditing) { toggleEditing(); return true; } else if (itemId == R.id.forceLogging) { toggleLogging(); return true; } else if (itemId == R.id.manageDatalogs) { openManageDatalogs(); return true; } else if (itemId == R.id.preferences) { openPreferences(); return true; } else if (itemId == R.id.resetGauges) { resetGuages(); return true; } else if (itemId == R.id.calibrate) { openCalibrateTPS(); return true; } else if (itemId == R.id.about) { showAbout(); return true; } else if (itemId == R.id.quit) { quit(); return true; } else { return super.onOptionsItemSelected(item); } } /** * Start the background task to reset the gauges */ public void resetGuages() { new ResetGaugesTask().execute((Void) null); } /** * Toggle the gauge editing */ private void toggleEditing() { // Gauge editing is enabled if (gaugeEditEnabled) { saveGauges(); } // Gauge editing is not enabled else { for (int i = 0; i < 2; i++) { Toast.makeText(getApplicationContext(), R.string.edit_gauges_instructions, Toast.LENGTH_LONG).show(); } } gaugeEditEnabled = !gaugeEditEnabled; initGauges(); } /** * Toggle data logging of the Megasquirt */ private void toggleLogging() { Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecu != null) { if (ecu.isLogging()) { ecu.stopLogging(); sendLogs(); } else { ecu.startLogging(); } } } /** * If the user opted in to get logs sent to his email, we prompt him */ private void sendLogs() { if (ApplicationSettings.INSTANCE.emailEnabled()) { DatalogManager.INSTANCE.close(); FRDLogManager.INSTANCE.close(); List<String> paths = new ArrayList<String>(); paths.add(DatalogManager.INSTANCE.getAbsolutePath()); paths.add(FRDLogManager.INSTANCE.getAbsolutePath()); paths.add(DebugLogManager.INSTANCE.getAbsolutePath()); String emailText = getString(R.string.email_body); String subject = String.format(getString(R.string.email_subject), System.currentTimeMillis()); EmailManager.email(this, ApplicationSettings.INSTANCE.getEmailDestination(), null, subject, emailText, paths); } } /** * Quit the application cleanly by stopping the connection to the Megasquirt if it exists */ private void quit() { ApplicationSettings.INSTANCE.setAutoConnectOverride(false); Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecu != null) { ecu.stop(); } sendLogs(); if (ecu != null) { ecu.reset(); } this.finish(); } /** * Toggle the connection to the Megasquirt */ private void toggleConnection() { Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecu != null) { ecu.toggleConnection(); } } /** * Open an about dialog */ private void showAbout() { Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.about); TextView text = (TextView) dialog.findViewById(R.id.text); String title = ""; try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA); ApplicationInfo ai = pInfo.applicationInfo; final String applicationName = (ai != null) ? getPackageManager().getApplicationLabel(ai).toString() : "(unknown)"; title = applicationName + " " + pInfo.versionName; } catch (NameNotFoundException e) { e.printStackTrace(); } dialog.setTitle(title); text.setText(R.string.about_text); ImageView image = (ImageView) dialog.findViewById(R.id.image); image.setImageResource(R.drawable.icon); dialog.show(); } /** * Open the calibrate TPS activity */ private void openCalibrateTPS() { Intent launchCalibrate = new Intent(this, CalibrateActivity.class); startActivity(launchCalibrate); } /** * Open the manage datalogs activity */ private void openManageDatalogs() { Intent lauchManageDatalogs = new Intent(this, ManageDatalogsActivity.class); startActivity(lauchManageDatalogs); } /** * Open the preferences activity */ private void openPreferences() { Intent launchPrefs = new Intent(this, PreferencesActivity.class); startActivityForResult(launchPrefs, SHOW_PREFS); } /** * * @param requestCode * @param resultCode * @param data */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == MSLoggerApplication.PROBE_ECU) { completeCreate(); } if (requestCode == SHOW_PREFS) { Boolean dirty = (Boolean) data.getExtras().get(PreferencesActivity.DIRTY); if (dirty) { Megasquirt ecuDefinition = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecuDefinition != null) { ecuDefinition.refreshFlags(); GaugeRegister.INSTANCE.flush(); ecuDefinition.initGauges(); initGauges(); } } } } } /** * Called when a preference change * * @param prefs * @param key */ @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (ready == null || !ready) { return; } if (key.startsWith("gauge")) { initGauges(); } Megasquirt ecuDefinition = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ApplicationSettings.INSTANCE.btDeviceSelected() && ecuDefinition != null) { ecuDefinition.refreshFlags(); } } /** * * @param v */ @Override public void onClick(View v) { } /** * Background task user to reset gauge to firmware default */ private class ResetGaugesTask extends AsyncTask<Void, Void, Void> { private ProgressDialog dialog; /** * */ @Override protected void onPreExecute() { dialog = new ProgressDialog(MSLoggerActivity.this); dialog.setMessage(getString(R.string.reset_gauges)); dialog.setIndeterminate(true); dialog.setCancelable(false); dialog.show(); } /** * * @param arg0 */ @Override protected Void doInBackground(Void... arg0) { GaugeRegister.INSTANCE.resetAll(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MSLoggerActivity.this); Editor editor = prefs.edit(); editor.remove("gauge1"); editor.remove("gauge2"); editor.remove("gauge3"); editor.remove("gauge4"); editor.remove("gauge5"); editor.commit(); return null; } /** * * @param unused */ @Override protected void onPostExecute(Void unused) { dialog.dismiss(); Megasquirt ecuDefinition = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecuDefinition != null) { initGauges(); } } } /** * Background task that load the pages */ private class InitTask extends AsyncTask<Void, Void, Void> { /** * * @param result */ @Override protected void onPostExecute(Void result) { super.onPostExecute(result); finaliseInit(); ready = true; } /** * * @param params */ @Override protected Void doInBackground(Void... params) { if (ready != null) { return null; } ready = false; loadGauges(); return null; } } /** * Receiver that get events from other activities about Megasquirt status and activities */ private final class Reciever extends BroadcastReceiver { /** * When an event is received * * @param context * @param intent */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i(ApplicationSettings.TAG, "Received :" + action); boolean autoLoggingEnabled = ApplicationSettings.INSTANCE.getAutoLogging(); if (action.equals(Megasquirt.CONNECTED)) { Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); DebugLogManager.INSTANCE.log(action,Log.INFO); indicatorManager.setDisabled(false); if (autoLoggingEnabled && ecu != null) { ecu.startLogging(); } } else if (action.equals(Megasquirt.DISCONNECTED)) { DebugLogManager.INSTANCE.log(action,Log.INFO); indicatorManager.setDisabled(true); if (autoLoggingEnabled) { DatalogManager.INSTANCE.mark("Connection lost"); } messages.setText(R.string.disconnected_from_ms); rps.setText(""); Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecu != null && ecu.isRunning()) { ecu.stop(); } } else if (action.equals(Megasquirt.NEW_DATA)) { processData(); } else if (action.equals(ApplicationSettings.GENERAL_MESSAGE)) { String msg = intent.getStringExtra(ApplicationSettings.MESSAGE); messages.setText(msg); DebugLogManager.INSTANCE.log("Message : " + msg,Log.INFO); } else if (action.equals(ApplicationSettings.RPS_MESSAGE)) { String RPS = intent.getStringExtra(ApplicationSettings.RPS); rps.setText(RPS + " reads / second"); } else if (action.equals(ApplicationSettings.TOAST)) { String msg = intent.getStringExtra(ApplicationSettings.TOAST_MESSAGE); // The toast is called in a loop so it can be displayed longer (Toast.LENGTH_LONG = 3.5 seconds) for (int j = 0; j < 2; j++) { Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); } } } } /** * Listener used when the user touch the screen to mark the datalog */ private static class MarkListener implements OnTouchListener { private LinearLayout layout; /** * Constructor * * @param layout The layout that will change background then the screen is touch */ public MarkListener(LinearLayout layout) { this.layout = layout; } /** * On touch event * * @param v The view that triggered the event * @param event Information about the event */ @Override public boolean onTouch(View v, MotionEvent event) { Megasquirt ecu = ApplicationSettings.INSTANCE.getEcuDefinition(); if (ecu != null && ecu.isLogging() && event.getAction() == MotionEvent.ACTION_DOWN) { layout.setBackgroundColor(Color.BLUE); layout.invalidate(); return true; } if (event.getAction() == MotionEvent.ACTION_UP) { layout.setBackgroundColor(Color.BLACK); layout.invalidate(); DatalogManager.INSTANCE.mark("Manual"); return true; } return false; } } }
false
true
public void bindIndicatorsEditEventsToIndex(int i) { indicators[i].setGestureDetector(new GestureDetector(new IndicatorGestureListener(MSLoggerActivity.this, indicators[i], i))); OnTouchListener gestureListener = new View.OnTouchListener() { private Indicator firstIndicator; /** * Determines if given points are inside view * * @param x X coordinate of point * @param y Y coordinate of point * @param view View object to compare * @return true If the points are within view bounds, false otherwise */ private boolean isPointInsideView(float x, float y, View view) { int location[] = new int[2]; view.getLocationOnScreen(location); int viewX = location[0]; int viewY = location[1]; // Point is inside view bounds if (x > viewX && x < viewX + view.getWidth() && y > viewY && y < viewY + view.getHeight()) { return true; } else { return false; } } /** * * @param v * @param event */ public boolean onTouch(View v, MotionEvent event) { if (firstIndicator != null && firstIndicator.getGestureDetector().onTouchEvent(event)) { return true; } else if (event.getAction() == MotionEvent.ACTION_DOWN) { this.firstIndicator = ((Indicator) v); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { Indicator lastIndicator = null; int lastIndexIndicator = 0; // Find indicator when the finger was lifted for (int i = 0; lastIndicator == null && i < indicators.length && indicators[i] != null; i++) { if (this.isPointInsideView(event.getRawX(),event.getRawY(),indicators[i])) { lastIndicator = indicators[i]; lastIndexIndicator = i; } } if (lastIndicator != null && firstIndicator.getId() != lastIndicator.getId()) { String firstIndicatorName = firstIndicator.getName(); String lastIndicatorName = lastIndicator.getName(); int firstIndexIndicator = 0; // Find first touched indicator index for (int i = 0; i < indicators.length; i++) { if (indicators[i] != null && firstIndicator.getId() == indicators[i].getId()) { firstIndexIndicator = i; } } // Remove old last indicator ViewGroup parentLastIndicatorView = (ViewGroup) lastIndicator.getParent(); int indexLast = parentLastIndicatorView.indexOfChild(lastIndicator); parentLastIndicatorView.removeView(lastIndicator); // Remove old first indicator ViewGroup parentFirstIndicatorView = (ViewGroup) firstIndicator.getParent(); int indexFirst = parentFirstIndicatorView.indexOfChild(firstIndicator); parentFirstIndicatorView.removeView(firstIndicator); /* * Since we are removing both view at the same time, if both were in the same parent, * we need to do some magic to keep them in the right order. */ if (parentFirstIndicatorView == parentLastIndicatorView) { if (indexLast > indexFirst) { indexLast -= 1; } else { indexFirst += 1; } } // Add first touched indicator in place of last touched indicator parentLastIndicatorView.addView(indicators[lastIndexIndicator], indexLast); parentLastIndicatorView.forceLayout(); // Add last touched indicator in place of first touched indicator parentFirstIndicatorView.addView(indicators[firstIndexIndicator], indexFirst); parentFirstIndicatorView.forceLayout(); // Init the indicator with their new gauge details indicators[lastIndexIndicator].initFromName(firstIndicatorName); indicators[firstIndexIndicator].initFromName(lastIndicatorName); indicators[lastIndexIndicator].setId(lastIndicator.getId()); indicators[firstIndexIndicator].setId(firstIndicator.getId()); // If indicators weren't the same type, we have to change their type if (firstIndicator.getType() != lastIndicator.getType()) { applyWidgetTypeToIndicators(); } // Re-map the right indicators with the right view findGauges(); return true; } } return false; } }; indicators[i].setOnClickListener(MSLoggerActivity.this); indicators[i].setOnTouchListener(gestureListener); }
public void bindIndicatorsEditEventsToIndex(int i) { indicators[i].setGestureDetector(new GestureDetector(new IndicatorGestureListener(MSLoggerActivity.this, indicators[i], i))); OnTouchListener gestureListener = new View.OnTouchListener() { private Indicator firstIndicator; /** * Determines if given points are inside view * * @param x X coordinate of point * @param y Y coordinate of point * @param view View object to compare * @return true If the points are within view bounds, false otherwise */ private boolean isPointInsideView(float x, float y, View view) { int location[] = new int[2]; view.getLocationOnScreen(location); int viewX = location[0]; int viewY = location[1]; // Point is inside view bounds if (x > viewX && x < viewX + view.getWidth() && y > viewY && y < viewY + view.getHeight()) { return true; } else { return false; } } /** * * @param v * @param event */ public boolean onTouch(View v, MotionEvent event) { if (firstIndicator != null && firstIndicator.getGestureDetector().onTouchEvent(event)) { return true; } else if (event.getAction() == MotionEvent.ACTION_DOWN) { this.firstIndicator = ((Indicator) v); return true; } else if (event.getAction() == MotionEvent.ACTION_UP) { Indicator lastIndicator = null; int lastIndexIndicator = 0; // Find indicator when the finger was lifted for (int i = 0; lastIndicator == null && i < indicators.length && indicators[i] != null; i++) { if (this.isPointInsideView(event.getRawX(),event.getRawY(),indicators[i])) { lastIndicator = indicators[i]; lastIndexIndicator = i; } } if (lastIndicator != null && firstIndicator.getId() != lastIndicator.getId()) { String firstIndicatorName = firstIndicator.getName(); String lastIndicatorName = lastIndicator.getName(); int firstIndexIndicator = 0; // Find first touched indicator index for (int i = 0; i < indicators.length; i++) { if (indicators[i] != null && firstIndicator.getId() == indicators[i].getId()) { firstIndexIndicator = i; } } // Remove old last indicator ViewGroup parentLastIndicatorView = (ViewGroup) lastIndicator.getParent(); int indexLast = parentLastIndicatorView.indexOfChild(lastIndicator); parentLastIndicatorView.removeView(lastIndicator); // Remove old first indicator ViewGroup parentFirstIndicatorView = (ViewGroup) firstIndicator.getParent(); int indexFirst = parentFirstIndicatorView.indexOfChild(firstIndicator); parentFirstIndicatorView.removeView(firstIndicator); /* * Since we are removing both view at the same time, if both were in the same parent, * we need to do some magic to keep them in the right order. */ if (parentFirstIndicatorView == parentLastIndicatorView) { if (indexLast > indexFirst) { indexLast -= 1; } else { indexFirst += 1; } } // Add first touched indicator in place of last touched indicator parentLastIndicatorView.addView(indicators[lastIndexIndicator], indexLast); parentLastIndicatorView.forceLayout(); // Add last touched indicator in place of first touched indicator parentFirstIndicatorView.addView(indicators[firstIndexIndicator], indexFirst); parentFirstIndicatorView.forceLayout(); // Init the indicator with their new indicator details indicators[lastIndexIndicator].initFromName(firstIndicatorName); indicators[firstIndexIndicator].initFromName(lastIndicatorName); indicators[lastIndexIndicator].setId(lastIndicator.getId()); indicators[firstIndexIndicator].setId(firstIndicator.getId()); // If indicators weren't the same type, we have to change their types if (firstIndicator.getType() != lastIndicator.getType()) { applyWidgetTypeToIndicators(); } // Re-map the right indicators with the right views findGauges(); return true; } } return false; } }; indicators[i].setOnClickListener(MSLoggerActivity.this); indicators[i].setOnTouchListener(gestureListener); }
diff --git a/jsonhome-registry/src/main/java/de/otto/jsonhome/registry/RegistryBasedJsonHomeSource.java b/jsonhome-registry/src/main/java/de/otto/jsonhome/registry/RegistryBasedJsonHomeSource.java index 3ad27f4..5b4dfb7 100644 --- a/jsonhome-registry/src/main/java/de/otto/jsonhome/registry/RegistryBasedJsonHomeSource.java +++ b/jsonhome-registry/src/main/java/de/otto/jsonhome/registry/RegistryBasedJsonHomeSource.java @@ -1,78 +1,79 @@ package de.otto.jsonhome.registry; import de.otto.jsonhome.client.HttpJsonHomeClient; import de.otto.jsonhome.client.JsonHomeClient; import de.otto.jsonhome.client.JsonHomeClientException; import de.otto.jsonhome.client.NotFoundException; import de.otto.jsonhome.generator.JsonHomeSource; import de.otto.jsonhome.model.JsonHome; import de.otto.jsonhome.model.ResourceLink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.annotation.PreDestroy; import java.net.URI; import java.util.*; import static de.otto.jsonhome.model.JsonHome.jsonHome; /** * Provides access to a json-home document containing the merged json-home documents registered in the {@link Registry}. * <p/> * The service is responsible for retrieving all registered documents. * * @author Guido Steinacker * @since 20.11.12 */ @Component public class RegistryBasedJsonHomeSource implements JsonHomeSource { private static Logger LOG = LoggerFactory.getLogger(RegistryBasedJsonHomeSource.class); private final JsonHomeClient client; private Registry registry; public RegistryBasedJsonHomeSource() { this.client = new HttpJsonHomeClient(); } @PreDestroy public void shutdown() { LOG.info("Shutting down JsonHomeClient"); client.shutdown(); } @Autowired public void setRegistry(final Registry registry) { this.registry = registry; } public JsonHome getJsonHome() { final Map<URI, ResourceLink> allResourceLinks = new HashMap<URI, ResourceLink>(); for (final RegistryEntry registryEntry : registry.getAll()) { try { final JsonHome jsonHome = client.get(registryEntry.getHref()); final Map<URI, ResourceLink> resources = jsonHome.getResources(); for (final URI uri : resources.keySet()) { if (allResourceLinks.containsKey(uri)) { - LOG.warn("Duplicate entries found for resource {}: entry '{}', is overridden by '{}'", uri, allResourceLinks.get(uri), resources.get(uri)); + LOG.warn("Duplicate entries found for resource {}: entry '{}', is overridden by '{}'", + new Object[] {uri, allResourceLinks.get(uri), resources.get(uri)}); } allResourceLinks.put(uri, resources.get(uri)); } allResourceLinks.putAll(resources); } catch (final NotFoundException e) { LOG.warn("Unable to get json-home document {}: {}", registryEntry.getHref(), e.getMessage()); // After some retries, the json-home MAY automatically be unregistered here. } catch (final JsonHomeClientException e) { LOG.warn("Unable to get json-home document {}: {}", registryEntry.getHref(), e.getMessage()); // After some retries, the json-home MAY automatically be unregistered here. } } LOG.debug("Returning json-home instance containing {} relation types: {}", allResourceLinks.size(), allResourceLinks.keySet()); return jsonHome(allResourceLinks.values()); } }
true
true
public JsonHome getJsonHome() { final Map<URI, ResourceLink> allResourceLinks = new HashMap<URI, ResourceLink>(); for (final RegistryEntry registryEntry : registry.getAll()) { try { final JsonHome jsonHome = client.get(registryEntry.getHref()); final Map<URI, ResourceLink> resources = jsonHome.getResources(); for (final URI uri : resources.keySet()) { if (allResourceLinks.containsKey(uri)) { LOG.warn("Duplicate entries found for resource {}: entry '{}', is overridden by '{}'", uri, allResourceLinks.get(uri), resources.get(uri)); } allResourceLinks.put(uri, resources.get(uri)); } allResourceLinks.putAll(resources); } catch (final NotFoundException e) { LOG.warn("Unable to get json-home document {}: {}", registryEntry.getHref(), e.getMessage()); // After some retries, the json-home MAY automatically be unregistered here. } catch (final JsonHomeClientException e) { LOG.warn("Unable to get json-home document {}: {}", registryEntry.getHref(), e.getMessage()); // After some retries, the json-home MAY automatically be unregistered here. } } LOG.debug("Returning json-home instance containing {} relation types: {}", allResourceLinks.size(), allResourceLinks.keySet()); return jsonHome(allResourceLinks.values()); }
public JsonHome getJsonHome() { final Map<URI, ResourceLink> allResourceLinks = new HashMap<URI, ResourceLink>(); for (final RegistryEntry registryEntry : registry.getAll()) { try { final JsonHome jsonHome = client.get(registryEntry.getHref()); final Map<URI, ResourceLink> resources = jsonHome.getResources(); for (final URI uri : resources.keySet()) { if (allResourceLinks.containsKey(uri)) { LOG.warn("Duplicate entries found for resource {}: entry '{}', is overridden by '{}'", new Object[] {uri, allResourceLinks.get(uri), resources.get(uri)}); } allResourceLinks.put(uri, resources.get(uri)); } allResourceLinks.putAll(resources); } catch (final NotFoundException e) { LOG.warn("Unable to get json-home document {}: {}", registryEntry.getHref(), e.getMessage()); // After some retries, the json-home MAY automatically be unregistered here. } catch (final JsonHomeClientException e) { LOG.warn("Unable to get json-home document {}: {}", registryEntry.getHref(), e.getMessage()); // After some retries, the json-home MAY automatically be unregistered here. } } LOG.debug("Returning json-home instance containing {} relation types: {}", allResourceLinks.size(), allResourceLinks.keySet()); return jsonHome(allResourceLinks.values()); }
diff --git a/src/pse11/parser/ParserInterface.java b/src/pse11/parser/ParserInterface.java index 051f036..e2f8cd7 100755 --- a/src/pse11/parser/ParserInterface.java +++ b/src/pse11/parser/ParserInterface.java @@ -1,72 +1,71 @@ package parser; import java.util.LinkedList; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CharStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import ast.Program; import ast.Expression; public class ParserInterface { private String[] errors = new String[0]; private TypeChecker typeChecker; /** * Report all errors from lexer and parser. * @return A list of error messages */ public String[] getErrors() { return errors; } /** * Parse program text into an AST * @param text the text to be parsed * @return the AST * @throws RecognitionException */ public Program parseProgram(String text) throws RecognitionException { LinkedList<String> errors = new LinkedList<String>(); CharStream in = new ANTLRStringStream(text); WhileLanguageLexer lex = new WhileLanguageLexer(in); lex.setErrorReporter(errors); CommonTokenStream tokens = new CommonTokenStream(); tokens.setTokenSource(lex); WhileLanguageParser parser = new WhileLanguageParser(tokens); parser.setErrorReporter(errors); Program p = parser.program(); this.errors = errors.toArray(new String[errors.size()]); if (typeChecker == null) { typeChecker = new TypeChecker(); } - System.out.println(errors); if (errors.isEmpty()) { typeChecker.checkTypes(p); } return errors.isEmpty() ? p : null; } /** * Parse expression text into an AST * @param text the text to be parsed * @return the AST * @throws RecognitionException */ public Expression parseExpression(String text) throws RecognitionException { LinkedList<String> errors = new LinkedList<String>(); CharStream in = new ANTLRStringStream(text); WhileLanguageLexer lex = new WhileLanguageLexer(in); lex.setErrorReporter(errors); CommonTokenStream tokens = new CommonTokenStream(); tokens.setTokenSource(lex); WhileLanguageParser parser = new WhileLanguageParser(tokens); parser.setErrorReporter(errors); Expression e = parser.single_expression(); this.errors = errors.toArray(new String[errors.size()]); return e; } }
true
true
public Program parseProgram(String text) throws RecognitionException { LinkedList<String> errors = new LinkedList<String>(); CharStream in = new ANTLRStringStream(text); WhileLanguageLexer lex = new WhileLanguageLexer(in); lex.setErrorReporter(errors); CommonTokenStream tokens = new CommonTokenStream(); tokens.setTokenSource(lex); WhileLanguageParser parser = new WhileLanguageParser(tokens); parser.setErrorReporter(errors); Program p = parser.program(); this.errors = errors.toArray(new String[errors.size()]); if (typeChecker == null) { typeChecker = new TypeChecker(); } System.out.println(errors); if (errors.isEmpty()) { typeChecker.checkTypes(p); } return errors.isEmpty() ? p : null; }
public Program parseProgram(String text) throws RecognitionException { LinkedList<String> errors = new LinkedList<String>(); CharStream in = new ANTLRStringStream(text); WhileLanguageLexer lex = new WhileLanguageLexer(in); lex.setErrorReporter(errors); CommonTokenStream tokens = new CommonTokenStream(); tokens.setTokenSource(lex); WhileLanguageParser parser = new WhileLanguageParser(tokens); parser.setErrorReporter(errors); Program p = parser.program(); this.errors = errors.toArray(new String[errors.size()]); if (typeChecker == null) { typeChecker = new TypeChecker(); } if (errors.isEmpty()) { typeChecker.checkTypes(p); } return errors.isEmpty() ? p : null; }
diff --git a/solr/core/src/test/org/apache/solr/TestDistributedSearch.java b/solr/core/src/test/org/apache/solr/TestDistributedSearch.java index a8022b514..0b9f3a9ae 100755 --- a/solr/core/src/test/org/apache/solr/TestDistributedSearch.java +++ b/solr/core/src/test/org/apache/solr/TestDistributedSearch.java @@ -1,446 +1,448 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.embedded.JettySolrRunner; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.cloud.ChaosMonkey; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.ShardParams; import org.apache.solr.common.util.NamedList; /** * TODO? perhaps use: * http://docs.codehaus.org/display/JETTY/ServletTester * rather then open a real connection? * * * @since solr 1.3 */ public class TestDistributedSearch extends BaseDistributedSearchTestCase { String t1="a_t"; String i1="a_si"; String nint = "n_i"; String tint = "n_ti"; String nfloat = "n_f"; String tfloat = "n_tf"; String ndouble = "n_d"; String tdouble = "n_td"; String nlong = "n_l"; String tlong = "other_tl1"; String ndate = "n_dt"; String tdate_a = "a_n_tdt"; String tdate_b = "b_n_tdt"; String oddField="oddField_s"; String missingField="ignore_exception__missing_but_valid_field_t"; String invalidField="ignore_exception__invalid_field_not_in_schema"; @Override public void doTest() throws Exception { int backupStress = stress; // make a copy so we can restore del("*:*"); indexr(id,1, i1, 100, tlong, 100,t1,"now is the time for all good men", tdate_a, "2010-04-20T11:00:00Z", tdate_b, "2009-08-20T11:00:00Z", "foo_f", 1.414f, "foo_b", "true", "foo_d", 1.414d); indexr(id,2, i1, 50 , tlong, 50,t1,"to come to the aid of their country.", tdate_a, "2010-05-02T11:00:00Z", tdate_b, "2009-11-02T11:00:00Z"); indexr(id,3, i1, 2, tlong, 2,t1,"how now brown cow", tdate_a, "2010-05-03T11:00:00Z"); indexr(id,4, i1, -100 ,tlong, 101, t1,"the quick fox jumped over the lazy dog", tdate_a, "2010-05-03T11:00:00Z", tdate_b, "2010-05-03T11:00:00Z"); indexr(id,5, i1, 500, tlong, 500 , t1,"the quick fox jumped way over the lazy dog", tdate_a, "2010-05-05T11:00:00Z"); indexr(id,6, i1, -600, tlong, 600 ,t1,"humpty dumpy sat on a wall"); indexr(id,7, i1, 123, tlong, 123 ,t1,"humpty dumpy had a great fall"); indexr(id,8, i1, 876, tlong, 876, tdate_b, "2010-01-05T11:00:00Z", t1,"all the kings horses and all the kings men"); indexr(id,9, i1, 7, tlong, 7,t1,"couldn't put humpty together again"); indexr(id,10, i1, 4321, tlong, 4321,t1,"this too shall pass"); indexr(id,11, i1, -987, tlong, 987, t1,"An eye for eye only ends up making the whole world blind."); indexr(id,12, i1, 379, tlong, 379, t1,"Great works are performed, not by strength, but by perseverance."); indexr(id,13, i1, 232, tlong, 232, t1,"no eggs on wall, lesson learned", oddField, "odd man out"); indexr(id, 14, "SubjectTerms_mfacet", new String[] {"mathematical models", "mathematical analysis"}); indexr(id, 15, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"}); indexr(id, 16, "SubjectTerms_mfacet", new String[] {"test 1", "test 2", "test3"}); String[] vals = new String[100]; for (int i=0; i<100; i++) { vals[i] = "test " + i; } indexr(id, 17, "SubjectTerms_mfacet", vals); for (int i=100; i<150; i++) { indexr(id, i); } commit(); handle.clear(); handle.put("QTime", SKIPVAL); handle.put("timestamp", SKIPVAL); // random value sort for (String f : fieldNames) { query("q","*:*", "sort",f+" desc"); query("q","*:*", "sort",f+" asc"); } // these queries should be exactly ordered and scores should exactly match query("q","*:*", "sort",i1+" desc"); query("q","*:*", "sort","{!func}testfunc(add("+i1+",5))"+" desc"); query("q","*:*", "sort",i1+" asc"); query("q","*:*", "sort",i1+" desc", "fl","*,score"); query("q","*:*", "sort","n_tl1 asc", "fl","*,score"); query("q","*:*", "sort","n_tl1 desc"); handle.put("maxScore", SKIPVAL); query("q","{!func}"+i1);// does not expect maxScore. So if it comes ,ignore it. JavaBinCodec.writeSolrDocumentList() //is agnostic of request params. handle.remove("maxScore"); query("q","{!func}"+i1, "fl","*,score"); // even scores should match exactly here handle.put("highlighting", UNORDERED); handle.put("response", UNORDERED); handle.put("maxScore", SKIPVAL); query("q","quick"); query("q","all","fl","id","start","0"); query("q","all","fl","foofoofoo","start","0"); // no fields in returned docs query("q","all","fl","id","start","100"); handle.put("score", SKIPVAL); query("q","quick","fl","*,score"); query("q","all","fl","*,score","start","1"); query("q","all","fl","*,score","start","100"); query("q","now their fox sat had put","fl","*,score", "hl","true","hl.fl",t1); query("q","now their fox sat had put","fl","foofoofoo", "hl","true","hl.fl",t1); query("q","matchesnothing","fl","*,score"); // test that a single NOW value is propagated to all shards... if that is true // then the primary sort should always be a tie and then the secondary should always decide query("q","{!func}ms(NOW)", "sort","score desc,"+i1+" desc","fl","id"); query("q","*:*", "rows",0, "facet","true", "facet.field",t1); query("q","*:*", "rows",0, "facet","true", "facet.field",t1,"facet.limit",1); query("q","*:*", "rows",0, "facet","true", "facet.query","quick", "facet.query","all", "facet.query","*:*"); query("q","*:*", "rows",0, "facet","true", "facet.field",t1, "facet.mincount",2); // simple date facet on one field query("q","*:*", "rows",100, "facet","true", "facet.date",tdate_a, "facet.date.other", "all", "facet.date.start","2010-05-01T11:00:00Z", "facet.date.gap","+1DAY", "facet.date.end","2010-05-20T11:00:00Z"); // date facet on multiple fields query("q","*:*", "rows",100, "facet","true", "facet.date",tdate_a, "facet.date",tdate_b, "facet.date.other", "all", "f."+tdate_b+".facet.date.start","2009-05-01T11:00:00Z", "f."+tdate_b+".facet.date.gap","+3MONTHS", "facet.date.start","2010-05-01T11:00:00Z", "facet.date.gap","+1DAY", "facet.date.end","2010-05-20T11:00:00Z"); // simple range facet on one field query("q","*:*", "rows",100, "facet","true", "facet.range",tlong, "facet.range.start",200, "facet.range.gap",100, "facet.range.end",900); // range facet on multiple fields query("q","*:*", "rows",100, "facet","true", "facet.range",tlong, "facet.range",i1, "f."+i1+".facet.range.start",300, "f."+i1+".facet.range.gap",87, "facet.range.end",900, "facet.range.start",200, "facet.range.gap",100, "f."+tlong+".facet.range.end",900); // variations of fl query("q","*:*", "fl","score","sort",i1 + " desc"); query("q","*:*", "fl",i1 + ",score","sort",i1 + " desc"); query("q","*:*", "fl", i1, "fl","score","sort",i1 + " desc"); query("q","*:*", "fl", "id," + i1,"sort",i1 + " desc"); query("q","*:*", "fl", "id", "fl",i1,"sort",i1 + " desc"); query("q","*:*", "fl",i1, "fl", "id","sort",i1 + " desc"); query("q","*:*", "fl", "id", "fl",nint, "fl",tint,"sort",i1 + " desc"); query("q","*:*", "fl",nint, "fl", "id", "fl",tint,"sort",i1 + " desc"); stress=0; // turn off stress... we want to tex max combos in min time for (int i=0; i<25*RANDOM_MULTIPLIER; i++) { String f = fieldNames[random.nextInt(fieldNames.length)]; if (random.nextBoolean()) f = t1; // the text field is a really interesting one to facet on (and it's multi-valued too) // we want a random query and not just *:* so we'll get zero counts in facets also // TODO: do a better random query String q = random.nextBoolean() ? "*:*" : "id:(1 3 5 7 9 11 13) OR id:[100 TO " + random.nextInt(50) + "]"; int nolimit = random.nextBoolean() ? -1 : 10000; // these should be equivalent // if limit==-1, we should always get exact matches query("q",q, "rows",0, "facet","true", "facet.field",f, "facet.limit",nolimit, "facet.sort","count", "facet.mincount",random.nextInt(5), "facet.offset",random.nextInt(10)); query("q",q, "rows",0, "facet","true", "facet.field",f, "facet.limit",nolimit, "facet.sort","index", "facet.mincount",random.nextInt(5), "facet.offset",random.nextInt(10)); // for index sort, we should get exact results for mincount <= 1 query("q",q, "rows",0, "facet","true", "facet.field",f, "facet.sort","index", "facet.mincount",random.nextInt(2), "facet.offset",random.nextInt(10), "facet.limit",random.nextInt(11)-1); } stress = backupStress; // restore stress // test faceting multiple things at once query("q","*:*", "rows",0, "facet","true", "facet.query","quick", "facet.query","all", "facet.query","*:*" ,"facet.field",t1); // test filter tagging, facet exclusion, and naming (multi-select facet support) query("q","*:*", "rows",0, "facet","true", "facet.query","{!key=myquick}quick", "facet.query","{!key=myall ex=a}all", "facet.query","*:*" ,"facet.field","{!key=mykey ex=a}"+t1 ,"facet.field","{!key=other ex=b}"+t1 ,"facet.field","{!key=again ex=a,b}"+t1 ,"facet.field",t1 ,"fq","{!tag=a}id:[1 TO 7]", "fq","{!tag=b}id:[3 TO 9]" ); query("q", "*:*", "facet", "true", "facet.field", "{!ex=t1}SubjectTerms_mfacet", "fq", "{!tag=t1}SubjectTerms_mfacet:(test 1)", "facet.limit", "10", "facet.mincount", "1"); // test field that is valid in schema but missing in all shards query("q","*:*", "rows",100, "facet","true", "facet.field",missingField, "facet.mincount",2); // test field that is valid in schema and missing in some shards query("q","*:*", "rows",100, "facet","true", "facet.field",oddField, "facet.mincount",2); query("q","*:*", "sort",i1+" desc", "stats", "true", "stats.field", i1); /*** TODO: the failure may come back in "exception" try { // test error produced for field that is invalid for schema query("q","*:*", "rows",100, "facet","true", "facet.field",invalidField, "facet.mincount",2); TestCase.fail("SolrServerException expected for invalid field that is not in schema"); } catch (SolrServerException ex) { // expected } ***/ // Try to get better coverage for refinement queries by turning off over requesting. // This makes it much more likely that we may not get the top facet values and hence // we turn of that checking. handle.put("facet_fields", SKIPVAL); query("q","*:*", "rows",0, "facet","true", "facet.field",t1,"facet.limit",5, "facet.shard.limit",5); // check a complex key name query("q","*:*", "rows",0, "facet","true", "facet.field","{!key='$a b/c \\' \\} foo'}"+t1,"facet.limit",5, "facet.shard.limit",5); query("q","*:*", "rows",0, "facet","true", "facet.field","{!key='$a'}"+t1,"facet.limit",5, "facet.shard.limit",5); handle.remove("facet_fields"); // index the same document to two servers and make sure things // don't blow up. if (clients.size()>=2) { index(id,100, i1, 107 ,t1,"oh no, a duplicate!"); for (int i=0; i<clients.size(); i++) { index_specific(i, id,100, i1, 107 ,t1,"oh no, a duplicate!"); } commit(); query("q","duplicate", "hl","true", "hl.fl", t1); query("q","fox duplicate horses", "hl","true", "hl.fl", t1); query("q","*:*", "rows",100); } //SOLR 3161 ensure shards.qt=/update fails (anything but search handler really) // Also see TestRemoteStreaming#testQtUpdateFails() try { ignoreException("isShard is only acceptable"); // query("q","*:*","shards.qt","/update","stream.body","<delete><query>*:*</query></delete>"); // fail(); } catch (SolrException e) { //expected } unIgnoreException("isShard is only acceptable"); // test debugging handle.put("explain", UNORDERED); handle.put("debug", UNORDERED); handle.put("time", SKIPVAL); query("q","now their fox sat had put","fl","*,score",CommonParams.DEBUG_QUERY, "true"); query("q", "id:[1 TO 5]", CommonParams.DEBUG_QUERY, "true"); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.TIMING); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.RESULTS); query("q", "id:[1 TO 5]", CommonParams.DEBUG, CommonParams.QUERY); // Check Info is added to for each shard ModifiableSolrParams q = new ModifiableSolrParams(); q.set("q", "*:*"); q.set(ShardParams.SHARDS_INFO, true); setDistributedParams(q); QueryResponse rsp = queryServer(q); NamedList<?> sinfo = (NamedList<?>) rsp.getResponse().get(ShardParams.SHARDS_INFO); String shards = getShardsString(); int cnt = StringUtils.countMatches(shards, ",")+1; assertNotNull("missing shard info", sinfo); assertEquals("should have an entry for each shard ["+sinfo+"] "+shards, cnt, sinfo.size()); // test shards.tolerant=true for(int numDownServers = 0; numDownServers < jettys.size()-1; numDownServers++) { List<JettySolrRunner> upJettys = new ArrayList<JettySolrRunner>(jettys); List<SolrServer> upClients = new ArrayList<SolrServer>(clients); List<JettySolrRunner> downJettys = new ArrayList<JettySolrRunner>(); List<String> upShards = new ArrayList<String>(Arrays.asList(shardsArr)); for(int i=0; i<numDownServers; i++) { // shut down some of the jettys int indexToRemove = r.nextInt(upJettys.size()); JettySolrRunner downJetty = upJettys.remove(indexToRemove); upClients.remove(indexToRemove); upShards.remove(indexToRemove); ChaosMonkey.stop(downJetty); downJettys.add(downJetty); } queryPartialResults(upShards, upClients, "q","*:*",ShardParams.SHARDS_INFO,"true",ShardParams.SHARDS_TOLERANT,"true"); // restart the jettys for (JettySolrRunner downJetty : downJettys) { downJetty.start(); } } // This index has the same number for every field // TODO: This test currently fails because debug info is obtained only // on shards with matches. // query("q","matchesnothing","fl","*,score", "debugQuery", "true"); // Thread.sleep(10000000000L); } - protected void queryPartialResults(final List<String> upShards, List<SolrServer> upClients, Object... q) throws Exception { + protected void queryPartialResults(final List<String> upShards, + final List<SolrServer> upClients, + Object... q) throws Exception { final ModifiableSolrParams params = new ModifiableSolrParams(); for (int i = 0; i < q.length; i += 2) { params.add(q[i].toString(), q[i + 1].toString()); } // TODO: look into why passing true causes fails params.set("distrib", "false"); final QueryResponse controlRsp = controlClient.query(params); validateControlData(controlRsp); params.remove("distrib"); setDistributedParams(params); QueryResponse rsp = queryRandomUpServer(params,upClients); comparePartialResponses(rsp, controlRsp, upShards); if (stress > 0) { log.info("starting stress..."); Thread[] threads = new Thread[nThreads]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < stress; j++) { - int which = r.nextInt(clients.size()); - SolrServer client = clients.get(which); + int which = r.nextInt(upClients.size()); + SolrServer client = upClients.get(which); try { QueryResponse rsp = client.query(new ModifiableSolrParams(params)); if (verifyStress) { comparePartialResponses(rsp, controlRsp, upShards); } } catch (SolrServerException e) { throw new RuntimeException(e); } } } }; threads[i].start(); } for (Thread thread : threads) { thread.join(); } } } protected QueryResponse queryRandomUpServer(ModifiableSolrParams params, List<SolrServer> upClients) throws SolrServerException { // query a random "up" server int which = r.nextInt(upClients.size()); SolrServer client = upClients.get(which); QueryResponse rsp = client.query(params); return rsp; } protected void comparePartialResponses(QueryResponse rsp, QueryResponse controlRsp, List<String> upShards) { NamedList<?> sinfo = (NamedList<?>) rsp.getResponse().get(ShardParams.SHARDS_INFO); assertNotNull("missing shard info", sinfo); assertEquals("should have an entry for each shard ["+sinfo+"] "+shards, shardsArr.length, sinfo.size()); // identify each one for (Map.Entry<String,?> entry : sinfo) { String shard = entry.getKey(); NamedList<?> info = (NamedList<?>) entry.getValue(); boolean found = false; for(int i=0; i<shardsArr.length; i++) { String s = shardsArr[i]; if (shard.contains(s)) { found = true; // make sure that it responded if it's up if (upShards.contains(s)) { assertTrue("Expected to find numFound in the up shard info",info.get("numFound") != null); } else { assertTrue("Expected to find error in the down shard info",info.get("error") != null); } } } assertTrue("Couldn't find shard " + shard + " represented in shards info", found); } } }
false
true
protected void queryPartialResults(final List<String> upShards, List<SolrServer> upClients, Object... q) throws Exception { final ModifiableSolrParams params = new ModifiableSolrParams(); for (int i = 0; i < q.length; i += 2) { params.add(q[i].toString(), q[i + 1].toString()); } // TODO: look into why passing true causes fails params.set("distrib", "false"); final QueryResponse controlRsp = controlClient.query(params); validateControlData(controlRsp); params.remove("distrib"); setDistributedParams(params); QueryResponse rsp = queryRandomUpServer(params,upClients); comparePartialResponses(rsp, controlRsp, upShards); if (stress > 0) { log.info("starting stress..."); Thread[] threads = new Thread[nThreads]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < stress; j++) { int which = r.nextInt(clients.size()); SolrServer client = clients.get(which); try { QueryResponse rsp = client.query(new ModifiableSolrParams(params)); if (verifyStress) { comparePartialResponses(rsp, controlRsp, upShards); } } catch (SolrServerException e) { throw new RuntimeException(e); } } } }; threads[i].start(); } for (Thread thread : threads) { thread.join(); } } }
protected void queryPartialResults(final List<String> upShards, final List<SolrServer> upClients, Object... q) throws Exception { final ModifiableSolrParams params = new ModifiableSolrParams(); for (int i = 0; i < q.length; i += 2) { params.add(q[i].toString(), q[i + 1].toString()); } // TODO: look into why passing true causes fails params.set("distrib", "false"); final QueryResponse controlRsp = controlClient.query(params); validateControlData(controlRsp); params.remove("distrib"); setDistributedParams(params); QueryResponse rsp = queryRandomUpServer(params,upClients); comparePartialResponses(rsp, controlRsp, upShards); if (stress > 0) { log.info("starting stress..."); Thread[] threads = new Thread[nThreads]; for (int i = 0; i < threads.length; i++) { threads[i] = new Thread() { @Override public void run() { for (int j = 0; j < stress; j++) { int which = r.nextInt(upClients.size()); SolrServer client = upClients.get(which); try { QueryResponse rsp = client.query(new ModifiableSolrParams(params)); if (verifyStress) { comparePartialResponses(rsp, controlRsp, upShards); } } catch (SolrServerException e) { throw new RuntimeException(e); } } } }; threads[i].start(); } for (Thread thread : threads) { thread.join(); } } }
diff --git a/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/dal/TweetMentionTest.java b/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/dal/TweetMentionTest.java index d81ede2..7f5da05 100644 --- a/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/dal/TweetMentionTest.java +++ b/backend/skynet_backend/src/test/java/toctep/skynet/backend/test/dal/TweetMentionTest.java @@ -1,66 +1,66 @@ package toctep.skynet.backend.test.dal; import toctep.skynet.backend.dal.domain.tweet.Tweet; import toctep.skynet.backend.dal.domain.tweet.TweetMention; import toctep.skynet.backend.dal.domain.user.User; public class TweetMentionTest extends DomainTest { private TweetMention tweetMention; private User user; private Tweet tweet; @Override public void setUp() { super.setUp(); - TweetMention tweetMention = new TweetMention(); + tweetMention = new TweetMention(); - User user = new User(); + user = new User(); user.setId(new Long(1)); tweetMention.setUser(user); - Tweet tweet = new Tweet(); + tweet = new Tweet(); tweet.setId(new Long(1)); tweetMention.setTweet(tweet); } @Override public void testCreate() { assertNotNull(tweetMention); assertEquals("getTweet: ", tweet, tweetMention.getTweet()); assertEquals("getUser: ", user, tweetMention.getUser()); } @Override public void testInsert() { tweetMention.save(); assertEquals(1, tweetMentionDao.count()); } @Override public void testSelect() { tweetMention.save(); TweetMention postTweetMention = (TweetMention) tweetMentionDao.select(tweetMention.getId()); assertTrue(postTweetMention.getTweet().getId().equals(tweetMention.getTweet().getId())); assertTrue(postTweetMention.getUser().getId().equals(tweetMention.getUser().getId())); } @Override public void testUpdate() { // TODO Auto-generated method stub } @Override public void testDelete() { tweetMention.save(); assertEquals(1, tweetMentionDao.count()); tweetMention.delete(); assertEquals(0, tweetMentionDao.count()); } }
false
true
public void setUp() { super.setUp(); TweetMention tweetMention = new TweetMention(); User user = new User(); user.setId(new Long(1)); tweetMention.setUser(user); Tweet tweet = new Tweet(); tweet.setId(new Long(1)); tweetMention.setTweet(tweet); }
public void setUp() { super.setUp(); tweetMention = new TweetMention(); user = new User(); user.setId(new Long(1)); tweetMention.setUser(user); tweet = new Tweet(); tweet.setId(new Long(1)); tweetMention.setTweet(tweet); }
diff --git a/src/main/ed/js/engine/Convert.java b/src/main/ed/js/engine/Convert.java index 5b44b0c4f..ec664d4f0 100755 --- a/src/main/ed/js/engine/Convert.java +++ b/src/main/ed/js/engine/Convert.java @@ -1,2051 +1,2049 @@ // Convert.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 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 ed.js.engine; import java.io.*; import java.util.*; import java.util.regex.*; import com.twmacinta.util.*; import ed.ext.org.mozilla.javascript.*; import ed.js.*; import ed.io.*; import ed.lang.*; import ed.util.*; public class Convert { static boolean DJS = Boolean.getBoolean( "DEBUG.JS" ); final boolean D; public static final String DEFAULT_PACKAGE = "ed.js.gen"; public static JSFunction makeAnon( String code ){ return makeAnon( code , false ); } public static JSFunction makeAnon( String code , boolean forceEval ){ try { final String nice = code.trim(); final String name = "anon" + Math.random(); if ( nice.startsWith( "function" ) && nice.endsWith( "}" ) ){ Convert c = new Convert( name , code , true ); JSFunction func = c.get(); Scope s = Scope.newGlobal().child(); s.setGlobal( true ); func.call( s ); String keyToUse = null; int numKeys = 0; for ( String key : s.keySet() ){ if ( key.equals( "arguments" ) ) continue; keyToUse = key; numKeys++; } if ( numKeys == 1 ){ Object val = s.get( keyToUse ); if ( val instanceof JSFunction ){ JSFunction f = (JSFunction)val; f.setUsePassedInScope( forceEval ); return f; } } } Convert c = new Convert( name , nice , forceEval ); return c.get(); } catch ( IOException ioe ){ throw new RuntimeException( "should be impossible" , ioe ); } } public Convert( File sourceFile ) throws IOException { this( sourceFile.getAbsolutePath() , StreamUtil.readFully( sourceFile , "UTF-8" ) ); } public Convert( String name , String source ) throws IOException { this(name, source, false); } public Convert( String name , String source, boolean invokedFromEval) throws IOException { this( name , source , invokedFromEval , Language.JS ); } public Convert( String name , String source, boolean invokedFromEval , Language sourceLanguage ) throws IOException { D = DJS && ! name.contains( "src/main/ed/lang" ) && ! name.contains( "src/main/ed/appserver/" ) && ! name.contains( "src_main_ed_lang" ) ; _invokedFromEval = invokedFromEval; _sourceLanguage = sourceLanguage; _name = name; _source = source; _className = cleanName( _name ) + _getNumForClass( _name , _source ); _fullClassName = _package + "." + _className; _random = _random( _fullClassName ); _id = _random.nextInt(); _scriptInfo = new ScriptInfo( _name , _fullClassName , _sourceLanguage , this ); CompilerEnvirons ce = new CompilerEnvirons(); Parser p = new Parser( ce , ce.getErrorReporter() ); ScriptOrFnNode theNode = null; try { theNode = p.parse( _source , _name , 0 ); } catch ( ed.ext.org.mozilla.javascript.EvaluatorException ee ){ throw JSCompileException.create( ee ); } _encodedSource = p.getEncodedSource(); init( theNode ); } public static String cleanName( String name ){ StringBuilder buf = new StringBuilder( name.length() + 5 ); for ( int i=0; i<name.length(); i++ ){ final char c = name.charAt(i); if ( Character.isLetter( c ) || Character.isDigit( c ) ){ if ( buf.length() == 0 && Character.isDigit( c ) ) buf.append( "N" ); // java classes can't start with a number buf.append( c ); continue; } if ( buf.length() == 0 ) continue; buf.append( "_" ); } return buf.toString(); } private void init( ScriptOrFnNode sn ){ if ( _it != null ) throw new RuntimeException( "too late" ); NodeTransformer nf = new NodeTransformer(); nf.transform( sn ); if ( D ){ Debug.print( sn , 0 ); } State state = new State(); _setLineNumbers( sn , sn ); _addFunctionNodes( sn , state ); if ( D ) System.out.println( "***************" ); Node n = sn.getFirstChild(); _loadOnce = _isLoadOnce( n ); if ( _loadOnce ) n = n.getNext(); String whyRasReturn = null; while ( n != null ){ if ( n.getType() != Token.FUNCTION ){ if ( n.getNext() == null ){ if ( n.getType() == Token.EXPR_RESULT ){ _append( "return " , n ); _hasReturn = true; whyRasReturn = "EXPR_RESULT"; } if ( n.getType() == Token.RETURN ){ _hasReturn = true; whyRasReturn = "RETURN"; } } _add( n , sn , state ); _append( "\n" , n ); } n = n.getNext(); } if ( ! _hasReturn ) { _append( "return null; /* null added at end */" , sn ); } else { _append( "/* no return b/c : " + whyRasReturn + " */" , sn ); int end = _mainJavaCode.length() - 1; boolean alreadyHaveOne = false; for ( ; end >= 0; end-- ){ char c = _mainJavaCode.charAt( end ); if ( Character.isWhitespace( c ) ) continue; if ( c == ';' ){ if ( ! alreadyHaveOne ){ alreadyHaveOne = true; continue; } _mainJavaCode.setLength( end + 1 ); } break; } } } private void _add( Node n , State state ){ _add( n , null , state ); } private boolean _isLoadOnce( Node n ){ if ( n == null || n.getType() != Token.EXPR_RESULT ) return false; n = n.getFirstChild(); if ( n == null || n.getType() != Token.CALL ) return false; n = n.getFirstChild(); if ( n == null || n.getType() != Token.NAME ) return false; return n.getString().equals( "loadOnce" ); } private void _add( Node n , ScriptOrFnNode sn , State state ){ switch ( n.getType() ){ case Token.TYPEOF: _append( "JS_typeof( " , n ); _assertOne( n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.TYPEOFNAME: _append( "JS_typeof( " , n ); if ( state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); _append( " ) " , n ); break; case Token.REGEXP: int myId = _regex.size(); ScriptOrFnNode parent = _nodeToSOR.get( n ); if ( parent == null ) throw new RuntimeException( "how is parent null : " + n.hashCode() ); int rId = n.getIntProp( Node.REGEXP_PROP , -1 ); _regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) ); _append( " _regex(" + myId + ") " , n ); break; case Token.ARRAYLIT: { _append( "( JSArray.create( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) ) " , n ); } break; case Token.OBJECTLIT: { _append( "JS_buildLiteralObject( new String[]{ " , n ); boolean first = true; Node c = n.getFirstChild(); for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){ if ( first ) first = false; else _append( " , " , n ); String name = id.toString(); if ( c.getType() == Token.GET ) name = JSObjectBase.getterName( name ); else if ( c.getType() == Token.SET ) name = JSObjectBase.setterName( name ); _append( getStringCode( name ) + ".toString()" , n ); c = c.getNext(); } _append( " } " , n ); c = n.getFirstChild(); while ( c != null ){ _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) " , n ); } break; case Token.NEW: _append( "scope.clearThisNew( " , n ); _addCall( n , state , true ); _append( " ) " , n ); break; case Token.THIS: _append( "passedIn.getThis()" , n ); break; case Token.INC: case Token.DEC: _assertOne( n ); Node tempChild = n.getFirstChild(); if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){ if ( ! state.isNumber( tempChild.getString() ) ) throw new RuntimeException( "can't increment local variable : " + tempChild.getString() ); String str = n.getType() == Token.INC ? "++ " : "-- "; _append( tempChild.getString() + str , n ); } else { _append( "JS_inc( " , n ); _createRef( n.getFirstChild() , state ); _append( " , " , n ); _append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n ); _append( " , " , n ); _append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n ); _append( ")" , n ); } break; case Token.USE_STACK: _append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n ); break; case Token.SETPROP_OP: case Token.SETELEM_OP: Node theOp = n.getFirstChild().getNext().getNext(); if ( ( theOp.getType() == Token.ADD || theOp.getType() == Token.SUB || theOp.getType() == Token.MUL || theOp.getType() == Token.DIV ) && ( theOp.getFirstChild().getType() == Token.USE_STACK || theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){ _append( "\n" , n ); _append( "JS_setDefferedOp( (JSObject) " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( theOp.getFirstChild().getType() == Token.USE_STACK ? theOp.getFirstChild().getNext() : theOp.getFirstChild() , state ); _append( " , " + theOp.getType() , n ); _append( " \n ) \n" , n ); break; } _append( "\n { \n" , n ); _append( "JSObject __tempObject = (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); String tempName = "__temp" + _rand(); state._tempOpNames.push( tempName ); _append( "Object " + tempName + " = " , n ); _add( n.getFirstChild().getNext() , state ); _append( ";\n" , n ); _append( " __tempObject.set(" , n ); _append( tempName , n ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ); \n" , n ); _append( " } \n" , n ); break; case Token.SETPROP: case Token.SETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".set( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) " , n ); break; case Token.GETPROPNOWARN: case Token.GETPROP: case Token.GETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )" , n ); break; case Token.SET_REF: Node fc = n.getFirstChild(); if( fc.getType() != Token.REF_SPECIAL && fc.getType() != Token.REF_MEMBER ) throw new RuntimeException( "token is of type "+Token.name(fc.getType())+", should be of type REF_SPECIAL or REF_MEMBER."); _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".set( " , n ); _add( fc , state ); _append( " , " , n ); _add( fc.getNext() , state ); _append( " )" , n ); break; case Token.GET_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.REF_SPECIAL : _append( "\"" + n.getProp( Node.NAME_PROP ).toString() + "\"" , n ); break; case Token.REF_MEMBER : - _append( "\"" , n ); final int memberTypeFlags = n.getIntProp(Node.MEMBER_TYPE_PROP, 0); if ( ( memberTypeFlags & Node.DESCENDANTS_FLAG ) != 0 ) - _append( ".." , n ); + _append( "\"..\" + " , n ); if ( ( memberTypeFlags & Node.ATTRIBUTE_FLAG ) != 0 ) - _append( "@" , n ); + _append( "\"@\" + " , n ); - _append( n.getFirstChild().getNext().getString() , n ); - _append( "\"" , n ); + _add( n.getFirstChild().getNext(), state ); break; case Token.REF_NS_MEMBER : if( ( n.getIntProp(Node.MEMBER_TYPE_PROP,0) & Node.ATTRIBUTE_FLAG ) != 0 ) { _append( "\"@\" + " , n ); } _add( n.getFirstChild().getNext() , state ); _append( " + \"::\" + ", n ); _add( n.getFirstChild().getNext().getNext() , state ); break; case Token.REF_NAME : case Token.ESCXMLTEXT : case Token.ESCXMLATTR : _add( n.getFirstChild(), state ); break; case Token.EXPR_RESULT: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.CALL: _addCall( n , state ); break; case Token.NUMBER: double d = n.getDouble(); String temp = String.valueOf( d ); if ( temp.endsWith( ".0" ) || JSNumericFunctions.couldBeInt( d ) ) temp = String.valueOf( (int)d ); _append( "JSNumber.self( " + temp + ")" , n ); break; case Token.STRING: final String theString = n.getString(); _append( getStringCode( theString ) , n ); break; case Token.TRUE: _append( " true " , n ); break; case Token.FALSE: _append( " false " , n ); break; case Token.NULL: case Token.VOID: _append( " null " , n ); break; case Token.VAR: _addVar( n , state ); break; case Token.GETVAR: if ( state.useLocalVariable( n.getString() ) ){ _append( n.getString() , n ); break; } case Token.NAME: if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); break; case Token.SETVAR: final String foo = n.getFirstChild().getString(); if ( state.useLocalVariable( foo ) ){ if ( ! state.hasSymbol( foo ) ) throw new RuntimeException( "something is wrong" ); if ( ! state.isPrimitive( foo ) ) _append( "JSInternalFunctions.self ( " , n ); _append( foo + " = " , n ); _add( n.getFirstChild().getNext() , state ); if ( ! state.isPrimitive( foo ) ) _append( " )\n" , n ); } else { _setVar( foo , n.getFirstChild().getNext() , state , true ); } break; case Token.SETNAME: _addSet( n , state ); break; case Token.GET: _addFunction( n.getFirstChild() , state ); break; case Token.SET: _addFunction( n.getFirstChild() , state ); break; case Token.FUNCTION: _addFunction( n , state ); break; case Token.BLOCK: _addBlock( n , state ); break; case Token.EXPR_VOID: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.RETURN: boolean last = state._depth <= 1 && n.getNext() == null; if ( ! last ) _append( "if ( true ) { " , n ); _append( "return " , n ); if ( n.getFirstChild() != null ){ _assertOne( n ); _add( n.getFirstChild() , state ); } else { _append( " null " , n ); } _append( "; /* explicit return */" , n ); if ( ! last ) _append( "}" , n ); _append( "\n" , n ); break; case Token.BITNOT: _assertOne( n ); _append( "JS_bitnot( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.HOOK: _append( " JSInternalFunctions.self( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ? ( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) : ( " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) ) " , n ); break; case Token.POS: _assertOne( n ); _append( "JSNumber.getNumber( ", n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.ADD: if ( state.isNumberAndLocal( n.getFirstChild() ) && state.isNumberAndLocal( n.getFirstChild().getNext() ) ){ _append( "(" , n ); _add( n.getFirstChild() , state ); _append( " + " , n ); _add( n.getFirstChild().getNext() , state ); _append( ")" , n ); break; } case Token.NE: case Token.MUL: case Token.DIV: case Token.SUB: case Token.EQ: case Token.SHEQ: case Token.SHNE: case Token.GE: case Token.LE: case Token.LT: case Token.GT: case Token.BITOR: case Token.BITAND: case Token.BITXOR: case Token.URSH: case Token.RSH: case Token.LSH: case Token.MOD: _append( "JS_" + Token.name( n.getType() ).toLowerCase(), n ); _append( "( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )\n " , n ); break; case Token.IFNE: _addIFNE( n , state ); break; case Token.LOOP: _addLoop( n , state ); break; case Token.EMPTY: if ( n.getFirstChild() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "not really empty" ); } break; case Token.LABEL: _append( n.getString() + ":" , n ); break; case Token.BREAK: _append( "break " + n.getString() + ";\n" , n ); break; case Token.CONTINUE: _append( "if ( true ) continue " + n.getString() + ";\n" , n ); break; case Token.WHILE: _append( "while( false || JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){ " , n ); _add( n.getFirstChild().getNext() , state ); _append( " }\n" , n ); break; case Token.FOR: _addFor( n , state ); break; case Token.TARGET: break; case Token.NOT: _assertOne( n ); _append( " JS_not( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.AND: /* _append( " ( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " && " , n ); _append( " JS_evalToBool( " , n ); _add( c , state ); _append( " ) " , n ); c = c.getNext(); } _append( " ) " , n ); break; */ case Token.OR: Node cc = n.getFirstChild(); if ( cc.getNext() == null ) throw new RuntimeException( "what?" ); if ( cc.getNext().getNext() != null ) throw new RuntimeException( "what?" ); String mod = n.getType() == Token.AND ? "and" : "or"; _append( "JSInternalFunctions.self( scope." + mod + "Save( " , n ); _add( cc , state ); _append( " ) ? scope.get" + mod + "Save() : ( " , n ); _add( cc.getNext() , state ); _append( " ) ) " , n ); break; case Token.LOCAL_BLOCK: _assertOne( n ); if ( n.getFirstChild().getType() != Token.TRY ) throw new RuntimeException("only know about LOCAL_BLOCK with try" ); _addTry( n.getFirstChild() , state ); break; case Token.JSR: case Token.RETURN_RESULT: // these are handled in block break; case Token.THROW: _append( "if ( true ) _throw( " , n ); _add( n.getFirstChild() , state ); _append( " ); " , n ); break; case Token.INSTANCEOF: _append( "JS_instanceof( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); if ( n.getFirstChild().getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); break; case Token.DELPROP: if ( n.getFirstChild().getType() == Token.BINDNAME ) _append( "scope" , n ); else _addAsJSObject( n.getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); break; case Token.DEL_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.SWITCH: _addSwitch( n , state ); break; case Token.COMMA: _append( "JS_comma( " , n ); boolean first = true; Node inner = n.getFirstChild(); while ( inner != null ){ if ( first ) first = false; else _append( " , " , n ); _append( "\n ( " , n ); _add( inner , state ); _append( " )\n " , n ); inner = inner.getNext(); } _append( " ) " , n ); break; case Token.IN: _addAsJSObject( n.getFirstChild().getNext() , state ); _append( ".containsKey( " , n ); _add( n.getFirstChild() , state ); _append( ".toString() ) " , n ); break; case Token.NEG: _append( "JS_mul( -1 , " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.ENTERWITH: _append( "scope.enterWith( (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " );" , n ); break; case Token.LEAVEWITH: _append( "scope.leaveWith();" , n ); break; case Token.WITH: _add( n.getFirstChild() , state ); break; case Token.DOTQUERY: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( new ed.js.e4x.Query( " , n ); Node n2 = n.getFirstChild().getNext(); switch( n2.getFirstChild().getType() ) { case Token.GET_REF : _append( "\"@\" + " , n ); _add( n2.getFirstChild().getFirstChild() , state ); break; case Token.NAME : _append( "\"" + n2.getFirstChild().getString() + "\"" , n ); break; } _append( " , " , n ); _add( n2.getFirstChild().getNext() , state ); _append( " + \"\" , " , n ); String comp = Token.name( n2.getType() ); _append( "\"" + comp + "\" ) ) " , n ); break; case Token.DEFAULTNAMESPACE : _append( "((ed.js.e4x.ENode.Cons)scope.get( \"XML\")).setAndGetDefaultNamespace( ", n ); _add( n.getFirstChild(), state ); _append(")", n ); break; default: Debug.printTree( n , 0 ); throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() ); } } private void _addAsJSObject( Node n , State state ){ if ( n.getType() == Token.NUMBER ){ _append( "(new JSNumber( " + n.getDouble() + "))" , n ); return; } _append( "JS_toJSObject( " , n ); _add( n , state ); _append( ")" , n ); } private void _addDotQuery( Node n , State state ){ _append( "(new ed.js.e4x.E4X.Query(" , n ); String s = Token.name( n.getType() ); { Node t = n.getFirstChild(); switch ( t.getType() ){ case Token.GET_REF: _append( "\"@\" + " , n ); _add( t.getFirstChild().getFirstChild() , state ); break; default: throw new RuntimeException( "don't know how to handle " + Token.name( t.getType() ) + " in a DOTQUERY" ); } } _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( "))" , n ); } private void _addSwitch( Node n , State state ){ _assertType( n , Token.SWITCH ); Node caseDefault = ((Node.Jump)n).getDefault(); String switcherVar = "switcher" + _rand(); _append( "int " + switcherVar + " = -1;\n" , n ); Node caseArea = n.getFirstChild(); String val = "val" + _rand(); _append( "Object " + val + " = " , n ); _add( caseArea , state ); _append( " ; \n " , n ); n = n.getNext(); // this is default _assertType( n , Token.GOTO ); n = n.getNext(); caseArea = caseArea.getNext(); while ( caseArea != null ){ _append( "if ( JS_sheq( " + val + " , " , caseArea ); _add( caseArea.getFirstChild() , state ); _append( " ) ) {\n " + switcherVar + " = " + ((Node.Jump)caseArea).target.hashCode() + "; \n " , caseArea ); _append( " } \n " , caseArea ); _append( "else ", caseArea ); caseArea = caseArea.getNext(); } _append( "; // default: switcher set to -1 \n", n ); _append( "switch( " + switcherVar + " ) { \n" , n ); while( n != null && n.getNext() != null ) { if( n == caseDefault ) { _append( " default: \n" , n ); } else { _append( " case " + n.hashCode() + ": \n" , n ); } n = n.getNext(); _assertType( n , Token.BLOCK ); _add( n, state ); n = n.getNext(); } _append(" } \n" , n ); } private void _createRef( Node n , State state ){ if ( n.getType() == Token.NAME || n.getType() == Token.GETVAR ){ if ( state.useLocalVariable( n.getString() ) ) throw new RuntimeException( "can't create a JSRef from a local variable : " + n.getString() ); _append( " new JSRef( scope , null , " , n ); _append( "\"" + n.getString() + "\"" , n ); _append( " ) " , n ); return; } if ( n.getType() == Token.GETPROP || n.getType() == Token.GETELEM ){ _append( " new JSRef( scope , (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); return; } throw new RuntimeException( "can't handle" ); } private void _addTry( Node n , State state ){ _assertType( n , Token.TRY ); Node mainBlock = n.getFirstChild(); _assertType( mainBlock , Token.BLOCK ); _append( "try { \n " , n ); _add( mainBlock , state ); _append( " \n } \n " , n ); n = mainBlock.getNext(); final String num = _rand(); final String javaEName = "javaEEE" + num; final String javaName = "javaEEEO" + num; while ( n != null ){ if ( n.getType() == Token.FINALLY ){ _assertType( n.getFirstChild() , Token.BLOCK ); _append( "finally { \n" , n ); _add( n.getFirstChild() , state ); _append( " \n } \n " , n ); n = n.getNext(); continue; } if ( n.getType() == Token.LOCAL_BLOCK && n.getFirstChild().getType() == Token.CATCH_SCOPE ){ _append( " \n catch ( Exception " + javaEName + " ){ \n " , n ); _append( " \n Object " + javaName + " = ( " + javaEName + " instanceof JSException ) ? " + " ((JSException)" + javaEName + ").getObject() : " + javaEName + " ; \n" , n ); _append( "try { scope.pushException( " + javaEName + " ); \n" , n ); Node catchScope = n.getFirstChild(); while ( catchScope != null ){ final Node c = catchScope; if ( c.getType() != Token.CATCH_SCOPE ) break; Node b = c.getNext(); _assertType( b , Token.BLOCK ); _assertType( b.getFirstChild() , Token.ENTERWITH ); _assertType( b.getFirstChild().getNext() , Token.WITH ); b = b.getFirstChild().getNext().getFirstChild(); _assertType( b , Token.BLOCK ); String jsName = c.getFirstChild().getString(); _append( " scope.put( \"" + jsName + "\" , " + javaName + " , true ); " , c ); b = b.getFirstChild(); boolean isIF = b.getType() == Token.IFNE; if ( isIF ){ _append( "\n if ( " + javaEName + " != null && JS_evalToBool( " , b ); _add( b.getFirstChild() , state ); _append( " ) ){ \n " , b ); b = b.getNext().getFirstChild(); } while ( b != null ){ if ( b.getType() == Token.LEAVEWITH ) break; _add( b , state ); b = b.getNext(); } _append( "if ( true ) " + javaEName + " = null ;\n" , b ); if ( isIF ){ _append( "\n } \n " , b ); } catchScope = catchScope.getNext().getNext(); } _append( "if ( " + javaEName + " != null ){ if ( " + javaEName + " instanceof RuntimeException ){ throw (RuntimeException)" + javaEName + ";} throw new JSException( " + javaEName + ");}\n" , n ); _append( " } finally { scope.popException(); } " , n ); _append( "\n } \n " , n ); // ends catch n = n.getNext(); continue; } if ( n.getType() == Token.GOTO || n.getType() == Token.TARGET || n.getType() == Token.JSR ){ n = n.getNext(); continue; } if ( n.getType() == Token.RETHROW ){ //_append( "\nthrow " + javaEName + ";\n" , n ); n = n.getNext(); continue; } throw new RuntimeException( "what : " + Token.name( n.getType() ) ); } } private void _addFor( Node n , State state ){ _assertType( n , Token.FOR ); final int numChildren = countChildren( n ); if ( numChildren == 4 ){ _append( "\n for ( " , n ); if ( n.getFirstChild().getType() == Token.BLOCK ){ Node temp = n.getFirstChild().getFirstChild(); while ( temp != null ){ if ( temp.getType() == Token.EXPR_VOID ) _add( temp.getFirstChild() , state ); else _add( temp , state ); temp = temp.getNext(); if ( temp != null ) _append( " , " , n ); } } else if ( n.getFirstChild().getType() != Token.EMPTY ) { _add( n.getFirstChild() , state ); } _append( " ; \n JS_evalToBool( " , n ); if( n.getFirstChild().getNext().getType() == Token.EMPTY ) { _append( "true" , n ); } else { _add( n.getFirstChild().getNext() , state ); } _append( " ) ; \n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " )\n " , n ); _append( " { \n " , n ); _add( n.getFirstChild().getNext().getNext().getNext() , state ); _append( " } \n " , n ); } else if ( numChildren == 3 ){ String name = n.getFirstChild().getString(); String tempName = name + "TEMP"; if( n.getFirstChild().getFirstChild() != null && n.getFirstChild().getFirstChild().getType() == Token.ENUM_INIT_VALUES ) { _append( "\n for ( Object " , n ); _append( tempName , n ); _append( " : JSInternalFunctions.JS_collForForEach( ", n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ){\n " , n ); if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ) _append( name + " = " + tempName + "; " , n ); else _append( "scope.put( \"" + name + "\" , " + tempName + " , true );\n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( "\n}\n" , n ); } else { _append( "\n for ( String " , n ); _append( tempName , n ); _append( " : JSInternalFunctions.JS_collForFor( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) ){\n " , n ); if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ) _append( name + " = new JSString( " + tempName + ") ; " , n ); else _append( "scope.put( \"" + name + "\" , new JSString( " + tempName + " ) , true );\n" , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( "\n}\n" , n ); } } else { throw new RuntimeException( "wtf?" ); } } private void _addLoop( Node n , State state ){ _assertType( n , Token.LOOP ); final Node theLoop = n; n = n.getFirstChild(); Node nodes[] = null; if ( ( nodes = _matches( n , _while1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[5]; _append( "while ( JS_evalToBool( " , theLoop ); _add( predicate.getFirstChild() , state ); _append( " ) ) " , theLoop ); _add( main , state ); } else if ( ( nodes = _matches( n , _doWhile1 ) ) != null ){ Node main = nodes[1]; Node predicate = nodes[3]; _assertType( predicate , Token.IFEQ ); _append( "do { \n " , theLoop ); _add( main , state ); _append( " } \n while ( false || JS_evalToBool( " , n ); _add( predicate.getFirstChild() , state ); _append( " ) );\n " , n ); } else { throw new RuntimeException( "what?" ); } } private void _addIFNE( Node n , State state ){ _assertType( n , Token.IFNE ); final Node.Jump theIf = (Node.Jump)n; _assertOne( n ); // this is the predicate Node ifBlock = n.getNext(); _append( "if ( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){\n" , n ); _add( ifBlock , state ); _append( "}\n" , n ); n = n.getNext().getNext(); if ( n.getType() == Token.TARGET ){ if ( n.getNext() != null ) throw new RuntimeException( "something is wrong" ); return; } _assertType( n , Token.GOTO ); _assertType( n.getNext() , Token.TARGET ); if ( theIf.target.hashCode() != n.getNext().hashCode() ) throw new RuntimeException( "hashes don't match" ); n = n.getNext().getNext(); _append( " else if ( true ) { " , n ); _add( n , state ); _append( " } \n" , n ); _assertType( n.getNext() , Token.TARGET ); if ( n.getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); } private void _addFunctionNodes( final ScriptOrFnNode sn , final State state ){ Set<Integer> baseIds = new HashSet<Integer>(); { Node temp = sn.getFirstChild(); while ( temp != null ){ if ( temp.getType() == Token.FUNCTION && temp.getString() != null ){ int prop = temp.getIntProp( Node.FUNCTION_PROP , -1 ); if ( prop >= 0 ){ baseIds.add( prop ); } } temp = temp.getNext(); } } for ( int i=0; i<sn.getFunctionCount(); i++ ){ FunctionNode fn = sn.getFunctionNode( i ); _setLineNumbers( fn , fn ); String name = fn.getFunctionName(); String anonName = "tempFunc_" + _id + "_" + i + "_" + _methodId++; boolean anon = name.length() == 0; if ( anon ) name = anonName; if ( D ){ System.out.println( "***************" ); System.out.println( i + " : " + name ); } String useName = name; if ( ! anon && ! baseIds.contains( i ) ){ useName = anonName; state._nonRootFunctions.add( i ); } state._functionIdToName.put( i , useName ); _setVar( useName , fn , state , anon ); _append( "; \n scope.getFunction( \"" + useName + "\" ).setName( \"" + name + "\" );\n\n" , fn ); } } private void _addFunction( Node n , State state ){ if ( ! ( n instanceof FunctionNode ) ){ if ( n.getString() != null && n.getString().length() != 0 ){ int id = n.getIntProp( Node.FUNCTION_PROP , -1 ); if ( state._nonRootFunctions.contains( id ) ){ _append( "scope.set( \"" + n.getString() + "\" , scope.get( \"" + state._functionIdToName.get( id ) + "\" ) );\n" , n ); } return; } _append( getFunc( n , state ) , n ); return; } _assertOne( n ); FunctionNode fn = (FunctionNode)n; FunctionInfo fi = FunctionInfo.create( fn ); state = state.child(); state._fi = fi; boolean hasArguments = fi.usesArguemnts(); _append( "new JSFunctionCalls" + fn.getParamCount() + "( scope , null ){ \n" , n ); _append( "protected void init(){ super.init(); _sourceLanguage = getFileLanguage(); \n " , n ); _append( "_arguments = new JSArray();\n" , n ); for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); _append( "_arguments.add( \"" + foo + "\" );\n" , n ); } _append( "_globals = new JSArray();\n" , n ); for ( String g : fi._globals ) _append( "_globals.add( \"" + g + "\" );\n" , n ); _append( "}\n" , n ); String callLine = "public Object call( final Scope passedIn "; String varSetup = ""; ArrayList<String> paramNames = new ArrayList<String>(); for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); if( paramNames.contains( foo ) ) { int index = paramNames.indexOf( foo ); paramNames.remove( index ); paramNames.add( index, foo + _rand() ); } paramNames.add( foo ); } for ( String foo : paramNames ){ callLine += " , "; callLine += " Object " + foo; if ( ! state.useLocalVariable( foo ) ){ callLine += "INNNNN"; varSetup += " \nscope.put(\"" + foo + "\"," + foo + "INNNNN , true );\n "; if ( hasArguments ) varSetup += "arguments.add( " + foo + "INNNNN );\n"; } else { state.addSymbol( foo ); if ( hasArguments ) varSetup += "arguments.add( " + foo + " );\n"; } callLine += " "; } callLine += " , Object ___extra[] ){\n" ; _append( callLine + " final Scope scope = usePassedInScope() ? passedIn : new Scope( \"func scope\" , getScope() , passedIn , getFileLanguage() ); " , n ); if ( hasArguments ){ _append( "JSArray arguments = new JSArray();\n" , n ); _append( "arguments.set( \"callee\" , this );\n" , n ); _append( "scope.put( \"arguments\" , arguments , true );\n" , n ); } for ( int i=0; i<fn.getParamCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); final String javaName = foo + ( state.useLocalVariable( foo ) ? "" : "INNNNN" ); final Node defArg = fn.getDefault( foo ); if ( defArg == null ) continue; _append( "if ( null == " + javaName + " ) " , defArg ); _append( javaName + " = " , defArg ); _add( defArg , state ); _append( ";\n" , defArg ); } _append( varSetup , n ); if ( hasArguments ){ _append( "if ( ___extra != null ) for ( Object TTTT : ___extra ) arguments.add( TTTT );\n" , n ); _append( "{ Integer numArgs = _lastStart.get(); _lastStart.set( null ); while( numArgs != null && arguments.size() > numArgs && arguments.get( arguments.size() -1 ) == null ) arguments.remove( arguments.size() - 1 ); }" , n ); } for ( int i=fn.getParamCount(); i<fn.getParamAndVarCount(); i++ ){ final String foo = fn.getParamOrVarName( i ); if ( state.useLocalVariable( foo ) ){ state.addSymbol( foo ); if ( state.isNumber( foo ) ){ _append( "double " + foo + " = 0;\n" , n ); } else _append( "Object " + foo + " = null;\n" , n ); } else { _append( "scope.put( \"" + foo + "\" , null , true );\n" , n ); } } _addFunctionNodes( fn , state ); _add( n.getFirstChild() , fn , state ); _append( "}\n" , n ); int myStringId = _strings.size(); _strings.add( getSource( fn ) ); _append( "\t public String getSourceCode(){ return _strings[" + myStringId + "].toString(); }" , fn ); _append( "\t public String toString(){ return _strings[" + myStringId + "].toString(); }" , fn ); _append( "}\n" , n ); } private void _addBlock( Node n , State state ){ _assertType( n , Token.BLOCK ); if ( n.getFirstChild() == null ){ _append( "{}" , n ); return; } // this is weird. look at bracing0.js boolean bogusBrace = true; Node c = n.getFirstChild(); while ( c != null ){ if ( c.getType() != Token.EXPR_VOID ){ bogusBrace = false; break; } if ( c.getFirstChild().getNext() != null ){ bogusBrace = false; break; } if ( c.getFirstChild().getType() != Token.SETVAR ){ bogusBrace = false; break; } c = c.getNext(); } bogusBrace = bogusBrace || ( n.getFirstChild().getNext() == null && n.getFirstChild().getType() == Token.EXPR_VOID && n.getFirstChild().getFirstChild() == null ); if ( bogusBrace ){ c = n.getFirstChild(); while ( c != null ){ _add( c , state ); c = c.getNext(); } return; } boolean endReturn = n.getLastChild() != null && n.getLastChild().getType() == Token.RETURN_RESULT; state._depth++; _append( "{" , n ); String ret = "retName" + _rand(); if ( endReturn ) _append( "\n\nObject " + ret + " = null;\n\n" , n ); Node child = n.getFirstChild(); while ( child != null ){ if ( endReturn && child.getType() == Token.LEAVEWITH ) break; if ( endReturn && child.getType() == Token.EXPR_RESULT ) _append( ret + " = " , child ); _add( child , state ); if ( child.getType() == Token.IFNE || child.getType() == Token.SWITCH ) break; child = child.getNext(); } if ( endReturn ) _append( "\n\nif ( true ){ return " + ret + "; }\n\n" , n ); _append( "}" , n ); state._depth--; } private void _addSet( Node n , State state ){ _assertType( n , Token.SETNAME ); Node name = n.getFirstChild(); _setVar( name.getString() , name.getNext() , state ); } private void _addVar( Node n , State state ){ _assertType( n , Token.VAR ); _assertOne( n ); Node name = n.getFirstChild(); _assertOne( name ); _setVar( name.getString() , name.getFirstChild() , state ); } private void _addCall( Node n , State state ){ _addCall( n , state , false ); } private void _addCall( Node n , State state , boolean isClass ){ Node name = n.getFirstChild(); boolean useThis = name.getType() == Token.GETPROP && ! isClass; if ( useThis ) _append( "scope.clearThisNormal( " , n ); Boolean inc[] = new Boolean[]{ true }; String f = getFunc( name , state , isClass , inc ); _append( ( inc[0] ? f : "" ) + ".call( scope" + ( isClass ? ".newThis( " + f + " )" : "" ) + " " , n ); int numParam = 0; Node param = name.getNext(); while ( param != null ){ _append( " , " , param ); _add( param , state ); param = param.getNext(); numParam++; } if( numParam <= MAX_NUM_PARAMS ) { _append( " , new Object[0] " , n ); } _append( " ) " , n ); if ( useThis ) _append( " ) " , n ); } private void _setVar( String name , Node val , State state ){ _setVar( name , val , state , false ); } private void _setVar( String name , Node val , State state , boolean local ){ if ( state.useLocalVariable( name ) && state.hasSymbol( name ) ){ boolean prim = state.isPrimitive( name ); if ( ! prim ) _append( "JSInternalFunctions.self( " , val ); _append( name + " = " , val ); _add( val , state ); _append( "\n" , val ); if ( ! prim ) _append( ")\n" , val ); return; } _append( "scope.put( \"" + name + "\" , " , val); _add( val , state ); _append( " , " + local + " ) " , val ); } static int countChildren( Node n ){ int num = 0; Node c = n.getFirstChild(); while ( c != null ){ num++; c = c.getNext(); } return num; } public static void _assertOne( Node n ){ if ( n.getFirstChild() == null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "no child" ); } if ( n.getFirstChild().getNext() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "more than 1 child" ); } } public void _assertType( Node n , int type ){ _assertType( n , type , this ); } public static void _assertType( Node n , int type , Convert c ){ if ( type == n.getType() ) return; String msg = "wrong type. was : " + Token.name( n.getType() ) + " should be " + Token.name( type ); if ( c != null ) msg += " file : " + c._name + " : " + ( c._nodeToSourceLine.get( n ) + 1 ); throw new RuntimeException( msg ); } private void _setLineNumbers( final Node startN , final ScriptOrFnNode startSOF ){ final IdentitySet seen = new IdentitySet(); final List<Pair<Node,ScriptOrFnNode>> overallTODO = new LinkedList<Pair<Node,ScriptOrFnNode>>(); overallTODO.add( new Pair<Node,ScriptOrFnNode>( startN , startSOF ) ); while ( overallTODO.size() > 0 ){ final Pair<Node,ScriptOrFnNode> temp = overallTODO.remove( 0 ); Node n = temp.first; final ScriptOrFnNode sof = temp.second; assert( sof != null ); final int line = n.getLineno(); if ( line < 0 ) throw new RuntimeException( "something is wrong" ); List<Node> todo = new LinkedList<Node>(); _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); while ( todo.size() > 0 ){ n = todo.remove(0); if ( seen.contains( n ) ) continue; seen.add( n ); if ( n.getLineno() > 0 ){ overallTODO.add( new Pair<Node,ScriptOrFnNode>( n , n instanceof ScriptOrFnNode ? (ScriptOrFnNode)n : sof ) ); continue; } _nodeToSourceLine.put( n , line ); _nodeToSOR.put( n , sof ); if ( n.getFirstChild() != null ) todo.add( n.getFirstChild() ); if ( n.getNext() != null ) todo.add( n.getNext() ); } } } private void _append( String s , Node n ){ _mainJavaCode.append( s ); if ( n == null ) return; int numLines = 0; int max = s.length(); for ( int i=0; i<max; i++ ) if ( s.charAt( i ) == '\n' ) numLines++; final int start = _currentLineNumber; int end = _currentLineNumber + numLines; for ( int i=start; i<end; i++ ){ List<Node> l = _javaCodeToLines.get( i ); if ( l == null ){ l = new ArrayList<Node>(); _javaCodeToLines.put( i , l ); } l.add( n ); } _currentLineNumber = end; } private String getFunc( Node n , State state ){ return getFunc( n , state , false , null ); } private String getFunc( Node n , State state , boolean isClass , Boolean inc[] ){ if ( n.getClass().getName().indexOf( "StringNode" ) < 0 ){ if ( n.getType() == Token.GETPROP && ! isClass ){ _append( "scope.getFunctionAndSetThis( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( ".toString() ) " , n ); return ""; } int start = _mainJavaCode.length(); _append( "((JSFunction )" , n); _add( n , state ); _append( ")" , n ); int end = _mainJavaCode.length(); if( isClass ){ if ( inc == null ) throw new RuntimeException( "inc is null and can't be here" ); inc[0] = false; return "(" + _mainJavaCode.substring( start , end ) + ")"; } return ""; } String name = n.getString(); if ( name == null || name.length() == 0 ){ int id = n.getIntProp( Node.FUNCTION_PROP , -1 ); if ( id == -1 ) throw new RuntimeException( "no name or id for this thing" ); name = state._functionIdToName.get( id ); if ( name == null || name.length() == 0 ) throw new RuntimeException( "no name for this id " ); } if ( state.hasSymbol( name ) ) return "(( JSFunction)" + name + ")"; return "scope.getFunction( \"" + name + "\" )"; } public String getClassName(){ return _className; } public String getClassString(){ StringBuilder buf = new StringBuilder(); buf.append( "package " + _package + ";\n" ); buf.append( "import ed.js.*;\n" ); buf.append( "import ed.js.func.*;\n" ); buf.append( "import ed.js.engine.Scope;\n" ); buf.append( "import ed.js.engine.JSCompiledScript;\n" ); buf.append( "public class " ).append( _className ).append( " extends JSCompiledScript {\n" ); buf.append( "\t protected void myInit(){\n" ); if ( _loadOnce ) buf.append( "\t\t _loadOnce = true; \n" ); buf.append( "\t} \n" ); buf.append( "\tpublic Object _call( Scope scope , Object extra[] ) throws Exception {\n" ); buf.append( "\t\t final Scope passedIn = scope; \n" ); if (_invokedFromEval) { buf.append("\t\t // not creating new scope for execution as we're being run in the context of an eval\n"); } else { String cleanName = FileUtil.clean( _name ); buf.append( "\t\t if ( ! usePassedInScope() ){\n" ); buf.append( "\t\t\t scope = new Scope( \"compiled script for:" + cleanName + "\" , scope , null , getFileLanguage() ); \n" ); buf.append( "\t\t\t scope.setPath( this._path ); \n" ); buf.append( "\t\t }\n" ); buf.append( "\t\t scope.putAll( getTLScope() );\n" ); } buf.append( "\t\t JSArray arguments = new JSArray(); scope.put( \"arguments\" , arguments , true );\n " ); buf.append( "\t\t if ( extra != null ) for ( Object TTTT : extra ) arguments.add( TTTT );\n" ); _preMainLines = StringUtil.count( buf.toString() , "\n" ); buf.append( _mainJavaCode ); buf.append( "\n\n\t}\n\n" ); buf.append( "\n}\n\n" ); return buf.toString(); } public JSFunction get(){ if ( _it != null ) return _it; try { Class c = CompileUtil.compile( _package , getClassName() , getClassString() , this ); JSCompiledScript it = (JSCompiledScript)c.newInstance(); _scriptInfo.setup( this ); it._scriptInfo = _scriptInfo; it._regex = _regex; it._strings = new String[ _strings.size() ]; for ( int i=0; i<_strings.size(); i++ ) it._strings[i] = _strings.get( i ); it.setName( _name ); _it = it; StackTraceHolder.getInstance().set( _fullClassName , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js" , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js.func" , _scriptInfo ); StackTraceHolder.getInstance().setPackage( "ed.js.engine" , _scriptInfo ); return _it; } catch ( RuntimeException re ){ re.printStackTrace(); fixStack( re ); throw re; } catch ( Exception e ){ e.printStackTrace(); fixStack( e ); throw new RuntimeException( e ); } } public void fixStack( Throwable e ){ StackTraceHolder.getInstance().fix( e ); } Node _getNodeFromJavaLine( int line ){ line = ( line - _preMainLines ) - 1; List<Node> nodes = _javaCodeToLines.get( line ); if ( nodes == null || nodes.size() == 0 ){ return null; } return nodes.get(0); } public int _mapLineNumber( int line ){ Node n = _getNodeFromJavaLine( line ); if ( n == null ) return -1; Integer i = _nodeToSourceLine.get( n ); if ( i == null ) return -1; return i + 1; } public void _debugLineNumber( final int line ){ System.out.println( "-----" ); for ( int temp = Math.max( 0 , line - 5 ); temp < line + 5 ; temp++ ) System.out.println( "\t" + temp + "->" + _mapLineNumber( temp ) + " || " + _getNodeFromJavaLine( temp ) ); System.out.println( "-----" ); } String getSource( FunctionNode fn ){ final int start = fn.getEncodedSourceStart(); final int end = fn.getEncodedSourceEnd(); final String encoded = _encodedSource.substring( start , end ); final String realSource = Decompiler.decompile( encoded , 0 , new UintMap() ); return realSource; } private String getStringCode( String s ){ int stringId = _strings.size(); _strings.add( s ); return "_string(" + stringId + ")"; } public boolean hasReturn(){ return _hasReturn; } public int findStringId( String s ){ for ( int i=0; i<_strings.size(); i++ ){ if ( _strings.get(i).equals( s ) ){ return i; } } return -1; } String _rand(){ return String.valueOf( _random.nextInt( 1000000 ) ); } static Random _random( String name ){ return new Random( name.hashCode() ); } final Random _random; final String _name; final String _source; final String _encodedSource; final String _className; final String _fullClassName; final String _package = DEFAULT_PACKAGE; final boolean _invokedFromEval; final Language _sourceLanguage; final int _id; // these 3 variables should only be use by _append private int _currentLineNumber = 0; final Map<Integer,List<Node>> _javaCodeToLines = new TreeMap<Integer,List<Node>>(); final Map<Node,Integer> _nodeToSourceLine = new IdentityHashMap<Node,Integer>(); final Map<Node,ScriptOrFnNode> _nodeToSOR = new IdentityHashMap<Node,ScriptOrFnNode>(); final List<Pair<String,String>> _regex = new ArrayList<Pair<String,String>>(); final List<String> _strings = new ArrayList<String>(); final ScriptInfo _scriptInfo; int _preMainLines = -1; private final StringBuilder _mainJavaCode = new StringBuilder(); private boolean _hasReturn = false; private JSFunction _it; private boolean _loadOnce = false; private int _methodId = 0; // There are JSFunctionCalls 0-28 private final int MAX_NUM_PARAMS = 28; private static final int _while1[] = new int[]{ Token.GOTO , Token.TARGET , 0 , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static final int _doWhile1[] = new int[]{ Token.TARGET , 0 , Token.TARGET , Token.IFEQ , Token.TARGET }; private static Node[] _matches( Node n , int types[] ){ Node foo[] = new Node[types.length]; for ( int i=0; i<types.length; i++ ){ foo[i] = n; if ( types[i] > 0 && n.getType() != types[i] ) return null; n = n.getNext(); } return n == null ? foo : null; } // SCRIPT INFO static class ScriptInfo implements StackTraceFixer { ScriptInfo( String name , String fullClassName , Language l , Convert c ){ _name = name; _fullClassName = fullClassName; _sourceLanguage = l; _convert = DJS ? c : null; } public void fixStack( Throwable e ){ StackTraceHolder.getInstance().fix( e ); } public StackTraceElement fixSTElement( StackTraceElement element ){ return fixSTElement( element , false ); } public StackTraceElement fixSTElement( StackTraceElement element , boolean debug ){ if ( ! element.getClassName().startsWith( _fullClassName ) ) return null; if ( debug ){ System.out.println( element ); if ( _convert != null ) _convert._debugLineNumber( element.getLineNumber() ); } Pair<Integer,String> p = _lines.get( element.getLineNumber() ); if ( p == null ) return null; return new StackTraceElement( _name , p.second , _name , p.first ); } public boolean removeSTElement( StackTraceElement element ){ String s = element.toString(); return s.contains( ".call(JSFunctionCalls" ) || s.contains( "ed.js.JSFunctionBase.call(" ) || s.contains( "ed.js.engine.JSCompiledScript.call" ); } void setup( Convert c ){ for ( int i=0; i<c._currentLineNumber + 100; i++ ){ Node n = c._getNodeFromJavaLine( i ); if ( n == null ) continue; int line = c._mapLineNumber( i ); ScriptOrFnNode sof = c._nodeToSOR.get( n ); String method = "___"; if ( sof instanceof FunctionNode ) method = ((FunctionNode)sof).getFunctionName(); _lines.put( i , new Pair<Integer,String>( line , method ) ); } } final String _name; final String _fullClassName; final Language _sourceLanguage; final Convert _convert; final Map<Integer,Pair<Integer,String>> _lines = new HashMap<Integer,Pair<Integer,String>>(); } // END SCRIPT INFO // this is class compile optimization below static synchronized int _getNumForClass( String name , String source ){ ClassInfo ci = _classes.get( name ); if ( ci == null ){ ci = new ClassInfo(); _classes.put( name , ci ); } return ci.getNum( source ); } private static Map<String,ClassInfo> _classes = Collections.synchronizedMap( new HashMap<String,ClassInfo>() ); static class ClassInfo { synchronized int getNum( String source ){ _myMd5.Init(); _myMd5.Update( source ); final String hash = _myMd5.asHex(); Integer num = _sourceToNumber.get( hash ); if ( num != null ) return num; num = ++_numSoFar; _sourceToNumber.put( hash , num ); return num; } final MD5 _myMd5 = new MD5(); final Map<String,Integer> _sourceToNumber = new TreeMap<String,Integer>(); int _numSoFar = 0; } }
false
true
private void _add( Node n , ScriptOrFnNode sn , State state ){ switch ( n.getType() ){ case Token.TYPEOF: _append( "JS_typeof( " , n ); _assertOne( n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.TYPEOFNAME: _append( "JS_typeof( " , n ); if ( state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); _append( " ) " , n ); break; case Token.REGEXP: int myId = _regex.size(); ScriptOrFnNode parent = _nodeToSOR.get( n ); if ( parent == null ) throw new RuntimeException( "how is parent null : " + n.hashCode() ); int rId = n.getIntProp( Node.REGEXP_PROP , -1 ); _regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) ); _append( " _regex(" + myId + ") " , n ); break; case Token.ARRAYLIT: { _append( "( JSArray.create( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) ) " , n ); } break; case Token.OBJECTLIT: { _append( "JS_buildLiteralObject( new String[]{ " , n ); boolean first = true; Node c = n.getFirstChild(); for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){ if ( first ) first = false; else _append( " , " , n ); String name = id.toString(); if ( c.getType() == Token.GET ) name = JSObjectBase.getterName( name ); else if ( c.getType() == Token.SET ) name = JSObjectBase.setterName( name ); _append( getStringCode( name ) + ".toString()" , n ); c = c.getNext(); } _append( " } " , n ); c = n.getFirstChild(); while ( c != null ){ _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) " , n ); } break; case Token.NEW: _append( "scope.clearThisNew( " , n ); _addCall( n , state , true ); _append( " ) " , n ); break; case Token.THIS: _append( "passedIn.getThis()" , n ); break; case Token.INC: case Token.DEC: _assertOne( n ); Node tempChild = n.getFirstChild(); if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){ if ( ! state.isNumber( tempChild.getString() ) ) throw new RuntimeException( "can't increment local variable : " + tempChild.getString() ); String str = n.getType() == Token.INC ? "++ " : "-- "; _append( tempChild.getString() + str , n ); } else { _append( "JS_inc( " , n ); _createRef( n.getFirstChild() , state ); _append( " , " , n ); _append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n ); _append( " , " , n ); _append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n ); _append( ")" , n ); } break; case Token.USE_STACK: _append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n ); break; case Token.SETPROP_OP: case Token.SETELEM_OP: Node theOp = n.getFirstChild().getNext().getNext(); if ( ( theOp.getType() == Token.ADD || theOp.getType() == Token.SUB || theOp.getType() == Token.MUL || theOp.getType() == Token.DIV ) && ( theOp.getFirstChild().getType() == Token.USE_STACK || theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){ _append( "\n" , n ); _append( "JS_setDefferedOp( (JSObject) " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( theOp.getFirstChild().getType() == Token.USE_STACK ? theOp.getFirstChild().getNext() : theOp.getFirstChild() , state ); _append( " , " + theOp.getType() , n ); _append( " \n ) \n" , n ); break; } _append( "\n { \n" , n ); _append( "JSObject __tempObject = (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); String tempName = "__temp" + _rand(); state._tempOpNames.push( tempName ); _append( "Object " + tempName + " = " , n ); _add( n.getFirstChild().getNext() , state ); _append( ";\n" , n ); _append( " __tempObject.set(" , n ); _append( tempName , n ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ); \n" , n ); _append( " } \n" , n ); break; case Token.SETPROP: case Token.SETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".set( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) " , n ); break; case Token.GETPROPNOWARN: case Token.GETPROP: case Token.GETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )" , n ); break; case Token.SET_REF: Node fc = n.getFirstChild(); if( fc.getType() != Token.REF_SPECIAL && fc.getType() != Token.REF_MEMBER ) throw new RuntimeException( "token is of type "+Token.name(fc.getType())+", should be of type REF_SPECIAL or REF_MEMBER."); _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".set( " , n ); _add( fc , state ); _append( " , " , n ); _add( fc.getNext() , state ); _append( " )" , n ); break; case Token.GET_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.REF_SPECIAL : _append( "\"" + n.getProp( Node.NAME_PROP ).toString() + "\"" , n ); break; case Token.REF_MEMBER : _append( "\"" , n ); final int memberTypeFlags = n.getIntProp(Node.MEMBER_TYPE_PROP, 0); if ( ( memberTypeFlags & Node.DESCENDANTS_FLAG ) != 0 ) _append( ".." , n ); if ( ( memberTypeFlags & Node.ATTRIBUTE_FLAG ) != 0 ) _append( "@" , n ); _append( n.getFirstChild().getNext().getString() , n ); _append( "\"" , n ); break; case Token.REF_NS_MEMBER : if( ( n.getIntProp(Node.MEMBER_TYPE_PROP,0) & Node.ATTRIBUTE_FLAG ) != 0 ) { _append( "\"@\" + " , n ); } _add( n.getFirstChild().getNext() , state ); _append( " + \"::\" + ", n ); _add( n.getFirstChild().getNext().getNext() , state ); break; case Token.REF_NAME : case Token.ESCXMLTEXT : case Token.ESCXMLATTR : _add( n.getFirstChild(), state ); break; case Token.EXPR_RESULT: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.CALL: _addCall( n , state ); break; case Token.NUMBER: double d = n.getDouble(); String temp = String.valueOf( d ); if ( temp.endsWith( ".0" ) || JSNumericFunctions.couldBeInt( d ) ) temp = String.valueOf( (int)d ); _append( "JSNumber.self( " + temp + ")" , n ); break; case Token.STRING: final String theString = n.getString(); _append( getStringCode( theString ) , n ); break; case Token.TRUE: _append( " true " , n ); break; case Token.FALSE: _append( " false " , n ); break; case Token.NULL: case Token.VOID: _append( " null " , n ); break; case Token.VAR: _addVar( n , state ); break; case Token.GETVAR: if ( state.useLocalVariable( n.getString() ) ){ _append( n.getString() , n ); break; } case Token.NAME: if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); break; case Token.SETVAR: final String foo = n.getFirstChild().getString(); if ( state.useLocalVariable( foo ) ){ if ( ! state.hasSymbol( foo ) ) throw new RuntimeException( "something is wrong" ); if ( ! state.isPrimitive( foo ) ) _append( "JSInternalFunctions.self ( " , n ); _append( foo + " = " , n ); _add( n.getFirstChild().getNext() , state ); if ( ! state.isPrimitive( foo ) ) _append( " )\n" , n ); } else { _setVar( foo , n.getFirstChild().getNext() , state , true ); } break; case Token.SETNAME: _addSet( n , state ); break; case Token.GET: _addFunction( n.getFirstChild() , state ); break; case Token.SET: _addFunction( n.getFirstChild() , state ); break; case Token.FUNCTION: _addFunction( n , state ); break; case Token.BLOCK: _addBlock( n , state ); break; case Token.EXPR_VOID: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.RETURN: boolean last = state._depth <= 1 && n.getNext() == null; if ( ! last ) _append( "if ( true ) { " , n ); _append( "return " , n ); if ( n.getFirstChild() != null ){ _assertOne( n ); _add( n.getFirstChild() , state ); } else { _append( " null " , n ); } _append( "; /* explicit return */" , n ); if ( ! last ) _append( "}" , n ); _append( "\n" , n ); break; case Token.BITNOT: _assertOne( n ); _append( "JS_bitnot( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.HOOK: _append( " JSInternalFunctions.self( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ? ( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) : ( " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) ) " , n ); break; case Token.POS: _assertOne( n ); _append( "JSNumber.getNumber( ", n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.ADD: if ( state.isNumberAndLocal( n.getFirstChild() ) && state.isNumberAndLocal( n.getFirstChild().getNext() ) ){ _append( "(" , n ); _add( n.getFirstChild() , state ); _append( " + " , n ); _add( n.getFirstChild().getNext() , state ); _append( ")" , n ); break; } case Token.NE: case Token.MUL: case Token.DIV: case Token.SUB: case Token.EQ: case Token.SHEQ: case Token.SHNE: case Token.GE: case Token.LE: case Token.LT: case Token.GT: case Token.BITOR: case Token.BITAND: case Token.BITXOR: case Token.URSH: case Token.RSH: case Token.LSH: case Token.MOD: _append( "JS_" + Token.name( n.getType() ).toLowerCase(), n ); _append( "( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )\n " , n ); break; case Token.IFNE: _addIFNE( n , state ); break; case Token.LOOP: _addLoop( n , state ); break; case Token.EMPTY: if ( n.getFirstChild() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "not really empty" ); } break; case Token.LABEL: _append( n.getString() + ":" , n ); break; case Token.BREAK: _append( "break " + n.getString() + ";\n" , n ); break; case Token.CONTINUE: _append( "if ( true ) continue " + n.getString() + ";\n" , n ); break; case Token.WHILE: _append( "while( false || JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){ " , n ); _add( n.getFirstChild().getNext() , state ); _append( " }\n" , n ); break; case Token.FOR: _addFor( n , state ); break; case Token.TARGET: break; case Token.NOT: _assertOne( n ); _append( " JS_not( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.AND: /* _append( " ( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " && " , n ); _append( " JS_evalToBool( " , n ); _add( c , state ); _append( " ) " , n ); c = c.getNext(); } _append( " ) " , n ); break; */ case Token.OR: Node cc = n.getFirstChild(); if ( cc.getNext() == null ) throw new RuntimeException( "what?" ); if ( cc.getNext().getNext() != null ) throw new RuntimeException( "what?" ); String mod = n.getType() == Token.AND ? "and" : "or"; _append( "JSInternalFunctions.self( scope." + mod + "Save( " , n ); _add( cc , state ); _append( " ) ? scope.get" + mod + "Save() : ( " , n ); _add( cc.getNext() , state ); _append( " ) ) " , n ); break; case Token.LOCAL_BLOCK: _assertOne( n ); if ( n.getFirstChild().getType() != Token.TRY ) throw new RuntimeException("only know about LOCAL_BLOCK with try" ); _addTry( n.getFirstChild() , state ); break; case Token.JSR: case Token.RETURN_RESULT: // these are handled in block break; case Token.THROW: _append( "if ( true ) _throw( " , n ); _add( n.getFirstChild() , state ); _append( " ); " , n ); break; case Token.INSTANCEOF: _append( "JS_instanceof( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); if ( n.getFirstChild().getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); break; case Token.DELPROP: if ( n.getFirstChild().getType() == Token.BINDNAME ) _append( "scope" , n ); else _addAsJSObject( n.getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); break; case Token.DEL_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.SWITCH: _addSwitch( n , state ); break; case Token.COMMA: _append( "JS_comma( " , n ); boolean first = true; Node inner = n.getFirstChild(); while ( inner != null ){ if ( first ) first = false; else _append( " , " , n ); _append( "\n ( " , n ); _add( inner , state ); _append( " )\n " , n ); inner = inner.getNext(); } _append( " ) " , n ); break; case Token.IN: _addAsJSObject( n.getFirstChild().getNext() , state ); _append( ".containsKey( " , n ); _add( n.getFirstChild() , state ); _append( ".toString() ) " , n ); break; case Token.NEG: _append( "JS_mul( -1 , " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.ENTERWITH: _append( "scope.enterWith( (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " );" , n ); break; case Token.LEAVEWITH: _append( "scope.leaveWith();" , n ); break; case Token.WITH: _add( n.getFirstChild() , state ); break; case Token.DOTQUERY: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( new ed.js.e4x.Query( " , n ); Node n2 = n.getFirstChild().getNext(); switch( n2.getFirstChild().getType() ) { case Token.GET_REF : _append( "\"@\" + " , n ); _add( n2.getFirstChild().getFirstChild() , state ); break; case Token.NAME : _append( "\"" + n2.getFirstChild().getString() + "\"" , n ); break; } _append( " , " , n ); _add( n2.getFirstChild().getNext() , state ); _append( " + \"\" , " , n ); String comp = Token.name( n2.getType() ); _append( "\"" + comp + "\" ) ) " , n ); break; case Token.DEFAULTNAMESPACE : _append( "((ed.js.e4x.ENode.Cons)scope.get( \"XML\")).setAndGetDefaultNamespace( ", n ); _add( n.getFirstChild(), state ); _append(")", n ); break; default: Debug.printTree( n , 0 ); throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() ); } }
private void _add( Node n , ScriptOrFnNode sn , State state ){ switch ( n.getType() ){ case Token.TYPEOF: _append( "JS_typeof( " , n ); _assertOne( n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.TYPEOFNAME: _append( "JS_typeof( " , n ); if ( state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); _append( " ) " , n ); break; case Token.REGEXP: int myId = _regex.size(); ScriptOrFnNode parent = _nodeToSOR.get( n ); if ( parent == null ) throw new RuntimeException( "how is parent null : " + n.hashCode() ); int rId = n.getIntProp( Node.REGEXP_PROP , -1 ); _regex.add( new Pair<String,String>( parent.getRegexpString( rId ) , parent.getRegexpFlags( rId ) ) ); _append( " _regex(" + myId + ") " , n ); break; case Token.ARRAYLIT: { _append( "( JSArray.create( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) ) " , n ); } break; case Token.OBJECTLIT: { _append( "JS_buildLiteralObject( new String[]{ " , n ); boolean first = true; Node c = n.getFirstChild(); for ( Object id : (Object[])n.getProp( Node.OBJECT_IDS_PROP ) ){ if ( first ) first = false; else _append( " , " , n ); String name = id.toString(); if ( c.getType() == Token.GET ) name = JSObjectBase.getterName( name ); else if ( c.getType() == Token.SET ) name = JSObjectBase.setterName( name ); _append( getStringCode( name ) + ".toString()" , n ); c = c.getNext(); } _append( " } " , n ); c = n.getFirstChild(); while ( c != null ){ _append( " , " , n ); _add( c , state ); c = c.getNext(); } _append( " ) " , n ); } break; case Token.NEW: _append( "scope.clearThisNew( " , n ); _addCall( n , state , true ); _append( " ) " , n ); break; case Token.THIS: _append( "passedIn.getThis()" , n ); break; case Token.INC: case Token.DEC: _assertOne( n ); Node tempChild = n.getFirstChild(); if ( ( tempChild.getType() == Token.NAME || tempChild.getType() == Token.GETVAR ) && state.useLocalVariable( tempChild.getString() ) ){ if ( ! state.isNumber( tempChild.getString() ) ) throw new RuntimeException( "can't increment local variable : " + tempChild.getString() ); String str = n.getType() == Token.INC ? "++ " : "-- "; _append( tempChild.getString() + str , n ); } else { _append( "JS_inc( " , n ); _createRef( n.getFirstChild() , state ); _append( " , " , n ); _append( String.valueOf( ( n.getIntProp( Node.INCRDECR_PROP , 0 ) & Node.POST_FLAG ) > 0 ) , n ); _append( " , " , n ); _append( String.valueOf( n.getType() == Token.INC ? 1 : -1 ) , n ); _append( ")" , n ); } break; case Token.USE_STACK: _append( "__tempObject.get( " + state._tempOpNames.pop() + " ) " , n ); break; case Token.SETPROP_OP: case Token.SETELEM_OP: Node theOp = n.getFirstChild().getNext().getNext(); if ( ( theOp.getType() == Token.ADD || theOp.getType() == Token.SUB || theOp.getType() == Token.MUL || theOp.getType() == Token.DIV ) && ( theOp.getFirstChild().getType() == Token.USE_STACK || theOp.getFirstChild().getNext().getType() == Token.USE_STACK ) ){ _append( "\n" , n ); _append( "JS_setDefferedOp( (JSObject) " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( theOp.getFirstChild().getType() == Token.USE_STACK ? theOp.getFirstChild().getNext() : theOp.getFirstChild() , state ); _append( " , " + theOp.getType() , n ); _append( " \n ) \n" , n ); break; } _append( "\n { \n" , n ); _append( "JSObject __tempObject = (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); String tempName = "__temp" + _rand(); state._tempOpNames.push( tempName ); _append( "Object " + tempName + " = " , n ); _add( n.getFirstChild().getNext() , state ); _append( ";\n" , n ); _append( " __tempObject.set(" , n ); _append( tempName , n ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ); \n" , n ); _append( " } \n" , n ); break; case Token.SETPROP: case Token.SETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".set( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) " , n ); break; case Token.GETPROPNOWARN: case Token.GETPROP: case Token.GETELEM: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )" , n ); break; case Token.SET_REF: Node fc = n.getFirstChild(); if( fc.getType() != Token.REF_SPECIAL && fc.getType() != Token.REF_MEMBER ) throw new RuntimeException( "token is of type "+Token.name(fc.getType())+", should be of type REF_SPECIAL or REF_MEMBER."); _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".set( " , n ); _add( fc , state ); _append( " , " , n ); _add( fc.getNext() , state ); _append( " )" , n ); break; case Token.GET_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".get( " , n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.REF_SPECIAL : _append( "\"" + n.getProp( Node.NAME_PROP ).toString() + "\"" , n ); break; case Token.REF_MEMBER : final int memberTypeFlags = n.getIntProp(Node.MEMBER_TYPE_PROP, 0); if ( ( memberTypeFlags & Node.DESCENDANTS_FLAG ) != 0 ) _append( "\"..\" + " , n ); if ( ( memberTypeFlags & Node.ATTRIBUTE_FLAG ) != 0 ) _append( "\"@\" + " , n ); _add( n.getFirstChild().getNext(), state ); break; case Token.REF_NS_MEMBER : if( ( n.getIntProp(Node.MEMBER_TYPE_PROP,0) & Node.ATTRIBUTE_FLAG ) != 0 ) { _append( "\"@\" + " , n ); } _add( n.getFirstChild().getNext() , state ); _append( " + \"::\" + ", n ); _add( n.getFirstChild().getNext().getNext() , state ); break; case Token.REF_NAME : case Token.ESCXMLTEXT : case Token.ESCXMLATTR : _add( n.getFirstChild(), state ); break; case Token.EXPR_RESULT: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.CALL: _addCall( n , state ); break; case Token.NUMBER: double d = n.getDouble(); String temp = String.valueOf( d ); if ( temp.endsWith( ".0" ) || JSNumericFunctions.couldBeInt( d ) ) temp = String.valueOf( (int)d ); _append( "JSNumber.self( " + temp + ")" , n ); break; case Token.STRING: final String theString = n.getString(); _append( getStringCode( theString ) , n ); break; case Token.TRUE: _append( " true " , n ); break; case Token.FALSE: _append( " false " , n ); break; case Token.NULL: case Token.VOID: _append( " null " , n ); break; case Token.VAR: _addVar( n , state ); break; case Token.GETVAR: if ( state.useLocalVariable( n.getString() ) ){ _append( n.getString() , n ); break; } case Token.NAME: if ( state.useLocalVariable( n.getString() ) && state.hasSymbol( n.getString() ) ) _append( n.getString() , n ); else _append( "scope.get( \"" + n.getString() + "\" )" , n ); break; case Token.SETVAR: final String foo = n.getFirstChild().getString(); if ( state.useLocalVariable( foo ) ){ if ( ! state.hasSymbol( foo ) ) throw new RuntimeException( "something is wrong" ); if ( ! state.isPrimitive( foo ) ) _append( "JSInternalFunctions.self ( " , n ); _append( foo + " = " , n ); _add( n.getFirstChild().getNext() , state ); if ( ! state.isPrimitive( foo ) ) _append( " )\n" , n ); } else { _setVar( foo , n.getFirstChild().getNext() , state , true ); } break; case Token.SETNAME: _addSet( n , state ); break; case Token.GET: _addFunction( n.getFirstChild() , state ); break; case Token.SET: _addFunction( n.getFirstChild() , state ); break; case Token.FUNCTION: _addFunction( n , state ); break; case Token.BLOCK: _addBlock( n , state ); break; case Token.EXPR_VOID: _assertOne( n ); _add( n.getFirstChild() , state ); _append( ";\n" , n ); break; case Token.RETURN: boolean last = state._depth <= 1 && n.getNext() == null; if ( ! last ) _append( "if ( true ) { " , n ); _append( "return " , n ); if ( n.getFirstChild() != null ){ _assertOne( n ); _add( n.getFirstChild() , state ); } else { _append( " null " , n ); } _append( "; /* explicit return */" , n ); if ( ! last ) _append( "}" , n ); _append( "\n" , n ); break; case Token.BITNOT: _assertOne( n ); _append( "JS_bitnot( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.HOOK: _append( " JSInternalFunctions.self( JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ? ( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) : ( " , n ); _add( n.getFirstChild().getNext().getNext() , state ); _append( " ) ) " , n ); break; case Token.POS: _assertOne( n ); _append( "JSNumber.getNumber( ", n ); _add( n.getFirstChild() , state ); _append( " ) ", n ); break; case Token.ADD: if ( state.isNumberAndLocal( n.getFirstChild() ) && state.isNumberAndLocal( n.getFirstChild().getNext() ) ){ _append( "(" , n ); _add( n.getFirstChild() , state ); _append( " + " , n ); _add( n.getFirstChild().getNext() , state ); _append( ")" , n ); break; } case Token.NE: case Token.MUL: case Token.DIV: case Token.SUB: case Token.EQ: case Token.SHEQ: case Token.SHNE: case Token.GE: case Token.LE: case Token.LT: case Token.GT: case Token.BITOR: case Token.BITAND: case Token.BITXOR: case Token.URSH: case Token.RSH: case Token.LSH: case Token.MOD: _append( "JS_" + Token.name( n.getType() ).toLowerCase(), n ); _append( "( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " )\n " , n ); break; case Token.IFNE: _addIFNE( n , state ); break; case Token.LOOP: _addLoop( n , state ); break; case Token.EMPTY: if ( n.getFirstChild() != null ){ Debug.printTree( n , 0 ); throw new RuntimeException( "not really empty" ); } break; case Token.LABEL: _append( n.getString() + ":" , n ); break; case Token.BREAK: _append( "break " + n.getString() + ";\n" , n ); break; case Token.CONTINUE: _append( "if ( true ) continue " + n.getString() + ";\n" , n ); break; case Token.WHILE: _append( "while( false || JS_evalToBool( " , n ); _add( n.getFirstChild() , state ); _append( " ) ){ " , n ); _add( n.getFirstChild().getNext() , state ); _append( " }\n" , n ); break; case Token.FOR: _addFor( n , state ); break; case Token.TARGET: break; case Token.NOT: _assertOne( n ); _append( " JS_not( " , n ); _add( n.getFirstChild() , state ); _append( " ) " , n ); break; case Token.AND: /* _append( " ( " , n ); Node c = n.getFirstChild(); while ( c != null ){ if ( c != n.getFirstChild() ) _append( " && " , n ); _append( " JS_evalToBool( " , n ); _add( c , state ); _append( " ) " , n ); c = c.getNext(); } _append( " ) " , n ); break; */ case Token.OR: Node cc = n.getFirstChild(); if ( cc.getNext() == null ) throw new RuntimeException( "what?" ); if ( cc.getNext().getNext() != null ) throw new RuntimeException( "what?" ); String mod = n.getType() == Token.AND ? "and" : "or"; _append( "JSInternalFunctions.self( scope." + mod + "Save( " , n ); _add( cc , state ); _append( " ) ? scope.get" + mod + "Save() : ( " , n ); _add( cc.getNext() , state ); _append( " ) ) " , n ); break; case Token.LOCAL_BLOCK: _assertOne( n ); if ( n.getFirstChild().getType() != Token.TRY ) throw new RuntimeException("only know about LOCAL_BLOCK with try" ); _addTry( n.getFirstChild() , state ); break; case Token.JSR: case Token.RETURN_RESULT: // these are handled in block break; case Token.THROW: _append( "if ( true ) _throw( " , n ); _add( n.getFirstChild() , state ); _append( " ); " , n ); break; case Token.INSTANCEOF: _append( "JS_instanceof( " , n ); _add( n.getFirstChild() , state ); _append( " , " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); if ( n.getFirstChild().getNext().getNext() != null ) throw new RuntimeException( "something is wrong" ); break; case Token.DELPROP: if ( n.getFirstChild().getType() == Token.BINDNAME ) _append( "scope" , n ); else _addAsJSObject( n.getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild().getNext() , state ); _append( " ) " , n ); break; case Token.DEL_REF: _addAsJSObject( n.getFirstChild().getFirstChild() , state ); _append( ".removeField( " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.SWITCH: _addSwitch( n , state ); break; case Token.COMMA: _append( "JS_comma( " , n ); boolean first = true; Node inner = n.getFirstChild(); while ( inner != null ){ if ( first ) first = false; else _append( " , " , n ); _append( "\n ( " , n ); _add( inner , state ); _append( " )\n " , n ); inner = inner.getNext(); } _append( " ) " , n ); break; case Token.IN: _addAsJSObject( n.getFirstChild().getNext() , state ); _append( ".containsKey( " , n ); _add( n.getFirstChild() , state ); _append( ".toString() ) " , n ); break; case Token.NEG: _append( "JS_mul( -1 , " , n ); _add( n.getFirstChild() , state ); _append( " )" , n ); break; case Token.ENTERWITH: _append( "scope.enterWith( (JSObject)" , n ); _add( n.getFirstChild() , state ); _append( " );" , n ); break; case Token.LEAVEWITH: _append( "scope.leaveWith();" , n ); break; case Token.WITH: _add( n.getFirstChild() , state ); break; case Token.DOTQUERY: _addAsJSObject( n.getFirstChild() , state ); _append( ".get( new ed.js.e4x.Query( " , n ); Node n2 = n.getFirstChild().getNext(); switch( n2.getFirstChild().getType() ) { case Token.GET_REF : _append( "\"@\" + " , n ); _add( n2.getFirstChild().getFirstChild() , state ); break; case Token.NAME : _append( "\"" + n2.getFirstChild().getString() + "\"" , n ); break; } _append( " , " , n ); _add( n2.getFirstChild().getNext() , state ); _append( " + \"\" , " , n ); String comp = Token.name( n2.getType() ); _append( "\"" + comp + "\" ) ) " , n ); break; case Token.DEFAULTNAMESPACE : _append( "((ed.js.e4x.ENode.Cons)scope.get( \"XML\")).setAndGetDefaultNamespace( ", n ); _add( n.getFirstChild(), state ); _append(")", n ); break; default: Debug.printTree( n , 0 ); throw new RuntimeException( "can't handle : " + n.getType() + ":" + Token.name( n.getType() ) + ":" + n.getClass().getName() + " line no : " + n.getLineno() ); } }
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java b/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java index 050329567..3eba8fd4f 100644 --- a/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java +++ b/javasvn/src/org/tmatesoft/svn/core/internal/SVNWorkspace.java @@ -1,1988 +1,1988 @@ /* * ==================================================================== * Copyright (c) 2004 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://tmate.org/svn/license.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Pattern; import org.tmatesoft.svn.core.ISVNCommitHandler; import org.tmatesoft.svn.core.ISVNDirectoryEntry; import org.tmatesoft.svn.core.ISVNEntry; import org.tmatesoft.svn.core.ISVNEntryContent; import org.tmatesoft.svn.core.ISVNExternalsHandler; import org.tmatesoft.svn.core.ISVNFileContent; import org.tmatesoft.svn.core.ISVNRootEntry; import org.tmatesoft.svn.core.ISVNRunnable; import org.tmatesoft.svn.core.ISVNStatusHandler; import org.tmatesoft.svn.core.ISVNWorkspace; import org.tmatesoft.svn.core.ISVNWorkspaceListener; import org.tmatesoft.svn.core.SVNCommitPacket; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.SVNStatus; import org.tmatesoft.svn.core.SVNWorkspaceManager; import org.tmatesoft.svn.core.internal.ws.fs.FSDirEntry; import org.tmatesoft.svn.core.internal.ws.fs.FSUtil; import org.tmatesoft.svn.core.io.ISVNCredentialsProvider; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.ISVNLogEntryHandler; import org.tmatesoft.svn.core.io.ISVNReporterBaton; import org.tmatesoft.svn.core.io.SVNCommitInfo; import org.tmatesoft.svn.core.io.SVNError; import org.tmatesoft.svn.core.io.SVNException; import org.tmatesoft.svn.core.io.SVNLock; import org.tmatesoft.svn.core.io.SVNNodeKind; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.io.SVNRepositoryLocation; import org.tmatesoft.svn.core.io.SVNSimpleCredentialsProvider; import org.tmatesoft.svn.core.progress.ISVNProgressViewer; import org.tmatesoft.svn.util.DebugLog; import org.tmatesoft.svn.util.PathUtil; import org.tmatesoft.svn.util.SVNUtil; import org.tmatesoft.svn.util.TimeUtil; /** * @author TMate Software Ltd. */ public class SVNWorkspace implements ISVNWorkspace { private ISVNRootEntry myRoot; private SVNRepositoryLocation myLocation; private Map myAutoProperties; private Map myCompiledAutoProperties; private List myListeners; private ISVNCredentialsProvider myCredentialsProvider; private ISVNExternalsHandler myExternalsHandler; private boolean myIsCommandRunning; private boolean myIsNeedToSleepForTimestamp; private boolean myIsCopyCommit; public SVNWorkspace(ISVNRootEntry root) { setAutoProperties(null); setExternalsHandler(new QuietSVNExternalsHandler()); myRoot = root; } public String getID() { if (myRoot == null) { return null; } return myRoot.getID(); } public void setGlobalIgnore(String ignore) { myRoot.setGlobalIgnore(ignore == null ? "" : ignore); } public String getGlobalIgnore() { return myRoot.getGlobalIgnore(); } public void setUseCommitTimes(boolean useCommitTimes) { myRoot.setUseCommitTimes(useCommitTimes); } public boolean isUseCommitTimes() { return myRoot.isUseCommitTimes(); } public void setAutoProperties(Map properties) { myAutoProperties = properties == null ? new HashMap() : new HashMap( properties); myCompiledAutoProperties = null; } public Map getAutoProperties() { return Collections.unmodifiableMap(myAutoProperties); } public void setExternalsHandler(ISVNExternalsHandler handler) { myExternalsHandler = handler; } public void addWorkspaceListener(ISVNWorkspaceListener listener) { if (listener != null) { if (myListeners == null) { myListeners = new ArrayList(); } myListeners.add(listener); } } public void removeWorkspaceListener(ISVNWorkspaceListener listener) { if (listener != null && myListeners != null) { myListeners.remove(listener); if (myListeners.isEmpty()) { myListeners = null; } } } public List getWorkspaceListeners() { if (myListeners == null) { return Collections.EMPTY_LIST; } return Collections.unmodifiableList(myListeners); } public SVNRepositoryLocation getLocation() throws SVNException { if (myLocation == null) { String url = getRoot().getPropertyValue(SVNProperty.URL); url = PathUtil.decode(url); if (url != null) { try { myLocation = SVNRepositoryLocation.parseURL(url); } catch (SVNException e) { } } } return myLocation; } public void setCredentials(String userName, String password) { if (userName != null && password != null) { myCredentialsProvider = new SVNSimpleCredentialsProvider(userName, password); } else { myCredentialsProvider = null; } } public ISVNCredentialsProvider getCredentialsProvider() { return myCredentialsProvider; } public void setCredentials(ISVNCredentialsProvider provider) { myCredentialsProvider = provider; } public void refresh() throws SVNException { if (getRoot() != null) { getRoot().dispose(); } } public ISVNWorkspace getRootWorkspace(boolean stopOnExternals, boolean stopOnSwitch) { ISVNWorkspace workspace = this; while (true) { String name = PathUtil.tail(workspace.getID()); if (name.trim().length() == 0 || PathUtil.isEmpty(name)) { return workspace; } String parentID = PathUtil.removeTail(workspace.getID().replace( File.separatorChar, '/')); ISVNWorkspace parentWorkspace = null; SVNRepositoryLocation location = null; DebugLog.log("creating parent workspace for " + workspace.getID()); DebugLog.log("parent id " + parentID); try { parentWorkspace = SVNWorkspaceManager.createWorkspace(getRoot() .getType(), parentID); if (parentWorkspace == null) { return workspace; } parentWorkspace.setCredentials(myCredentialsProvider); if (workspace.getLocation() == null && parentWorkspace.getLocation() != null) { return parentWorkspace; } if (workspace.getLocation() == null) { return workspace; } location = parentWorkspace.getLocation(); if (location == null) { return workspace; } String expectedUrl = PathUtil.append(location.toString(), PathUtil.encode(name)); if (!expectedUrl.equals(workspace.getLocation().toString())) { // check that ws.url at least starts with // as an external ws should be "unversioned". // as switched it should has "switched" status (at least not // unversioned). DebugLog.log("existing url: " + workspace.getLocation()); DebugLog.log("expected url: " + expectedUrl); SVNStatus wsStatus = parentWorkspace.status(name, false); if (wsStatus == null) { return workspace; } int status = wsStatus.getContentsStatus(); if ((status == SVNStatus.UNVERSIONED || status == SVNStatus.IGNORED || status == SVNStatus.EXTERNAL)) { if (stopOnExternals) { return workspace; } } else if (((status != SVNStatus.UNVERSIONED && status != SVNStatus.IGNORED) || wsStatus .isSwitched())) { if (stopOnSwitch) { return workspace; } } } } catch (SVNException e1) { return workspace; } workspace = parentWorkspace; } } public SVNRepositoryLocation getLocation(String path) throws SVNException { if (path == null || "".equals(path)) { return getLocation(); } ISVNEntry entry = locateEntry(path); if (entry == null) { return null; } String url = entry.getPropertyValue(SVNProperty.URL); if (url == null) { return null; } url = PathUtil.decode(url); return SVNRepositoryLocation.parseURL(url); } public void setLocation(SVNRepositoryLocation location) throws SVNException { if (getLocation() == null && location != null) { getRoot().setPropertyValue(SVNProperty.URL, location.toString()); myLocation = location; } } public long checkout(SVNRepositoryLocation location, long revision, boolean export) throws SVNException { return checkout(location, revision, export, true); } public long checkout(SVNRepositoryLocation location, long revision, boolean export, boolean recurse) throws SVNException { return checkout(location, revision, export, recurse, null); } public long checkout(SVNRepositoryLocation location, long revision, boolean export, boolean recurse, ISVNProgressViewer progressViewer) throws SVNException { if (getLocation() != null) { throw new SVNException(getRoot().getID() + " already contains working copy files"); } try { SVNRepository repository = null; if (!export) { setLocation(location); repository = SVNUtil.createRepository(this, ""); } else { repository = SVNRepositoryFactory.create(location); repository.setCredentialsProvider(myCredentialsProvider); } final SVNCheckoutProgressProcessor processor = progressViewer != null ? new SVNCheckoutProgressProcessor( progressViewer, repository, revision) : null; SVNCheckoutEditor editor = new SVNCheckoutEditor(getRoot(), this, getRoot(), export, null, true, processor); repository.checkout(revision, null, recurse, editor); if (myExternalsHandler != null) { Collection paths = new HashSet(); for (Iterator externals = editor.getExternals().iterator(); externals .hasNext();) { SVNExternal external = (SVNExternal) externals.next(); if (paths.contains(external.getPath())) { continue; } paths.add(external.getPath()); String path = PathUtil.append(getID(), external.getPath()); new File(path).mkdirs(); ISVNWorkspace extWorkspace = createWorkspace(external); myExternalsHandler.handleCheckout(this, external.getPath(), extWorkspace, external.getLocation(), external .getRevision(), export, true); } } if (!export && editor.isTimestampsChanged()) { sleepForTimestamp(); } return editor.getTargetRevision(); } finally { getRoot().dispose(); } } public long update(long revision) throws SVNException { return update("", revision, true); } public long update(String path, long revision, boolean recursive) throws SVNException { if (getLocation() == null) { throw new SVNException(getRoot().getID() + " does not contain working copy files"); } try { ISVNEntry targetEntry = locateEntry(path); Collection externalsSet = createExternals(path); String target = null; if (targetEntry == null || !targetEntry.isDirectory()) { target = targetEntry != null ? targetEntry.getName() : PathUtil .tail(path); targetEntry = locateParentEntry(path); } if (targetEntry.isMissing()) { target = targetEntry.getName(); targetEntry = locateParentEntry(path); } SVNRepository repository = SVNUtil.createRepository(this, targetEntry.getPath()); SVNCheckoutEditor editor = new SVNCheckoutEditor(getRoot(), this, targetEntry, false, target, recursive, null); SVNReporterBaton reporterBaton = new SVNReporterBaton(this, targetEntry, target, recursive); repository.update(revision, target, recursive, reporterBaton, editor); for (Iterator missingPaths = reporterBaton.missingEntries(); missingPaths .hasNext();) { ISVNEntry missingEntry = (ISVNEntry) missingPaths.next(); if (locateEntry(missingEntry.getPath()) == null) { fireEntryUpdated(missingEntry, SVNStatus.DELETED, 0, -1); } } if (myExternalsHandler != null) { Collection existingExternals = reporterBaton.getExternals(); Collection updatedExternals = editor.getExternals(); Collection allExternals = new HashSet(existingExternals); allExternals.addAll(externalsSet); existingExternals.addAll(updatedExternals); Collection paths = new HashSet(); for (Iterator externals = allExternals.iterator(); externals .hasNext();) { SVNExternal external = (SVNExternal) externals.next(); if (paths.contains(external.getPath())) { continue; } paths.add(external.getPath()); if (!external.getPath().startsWith(path)) { continue; } ISVNWorkspace extWorkspace = createWorkspace(external); myExternalsHandler.handleUpdate(this, external.getPath(), extWorkspace, external.getRevision()); } } if (editor.isTimestampsChanged()) { sleepForTimestamp(); } return editor.getTargetRevision(); } finally { getRoot().dispose(); } } public long update(SVNRepositoryLocation url, String path, long revision, boolean recursive) throws SVNException { if (getLocation() == null) { throw new SVNException(getRoot().getID() + " does not contain working copy files"); } try { ISVNEntry targetEntry = locateEntry(path); if (targetEntry == null) { throw new SVNException("could not find directory '" + path + "'"); } String target = null; if (!targetEntry.isDirectory()) { target = targetEntry.getName(); targetEntry = locateParentEntry(targetEntry.getPath()); } SVNRepository repository = SVNUtil.createRepository(this, targetEntry.getPath()); SVNCheckoutEditor editor = new SVNCheckoutEditor(getRoot(), this, targetEntry, false, target); ISVNReporterBaton reporterBaton = new SVNReporterBaton(this, targetEntry, null, recursive); repository.update(url.toString(), revision, target, recursive, reporterBaton, editor); if (myExternalsHandler != null) { Collection paths = new HashSet(); for (Iterator externals = editor.getExternals().iterator(); externals .hasNext();) { SVNExternal external = (SVNExternal) externals.next(); if (paths.contains(external.getPath())) { continue; } paths.add(external.getPath()); ISVNWorkspace extWorkspace = createWorkspace(external); myExternalsHandler.handleCheckout(this, external.getPath(), extWorkspace, external.getLocation(), external .getRevision(), false, true); } } // update urls. String newURL = url.toString(); if (target != null) { targetEntry = locateEntry(path); } targetEntry.setPropertyValue(SVNProperty.URL, newURL); targetEntry.setPropertyValue(SVNProperty.WC_URL, null); DebugLog.log("setting new url for " + targetEntry.getPath() + " : " + newURL); if (targetEntry.isDirectory()) { for (Iterator children = targetEntry.asDirectory() .childEntries(); children.hasNext();) { ISVNEntry child = (ISVNEntry) children.next(); updateURL(child, newURL, recursive); } targetEntry.save(); } else { locateParentEntry(path).save(); } if (targetEntry.equals(getRoot())) { setLocation(url); } if (editor.isTimestampsChanged()) { sleepForTimestamp(); } return editor.getTargetRevision(); } finally { getRoot().dispose(); } } private ISVNWorkspace createWorkspace(SVNExternal external) throws SVNException { ISVNWorkspace extWorkspace = SVNWorkspaceManager.createWorkspace( getRoot().getType(), PathUtil.append(getID(), external .getPath())); extWorkspace.setCredentials(myCredentialsProvider); extWorkspace.setAutoProperties(getAutoProperties()); extWorkspace.setExternalsHandler(myExternalsHandler); return extWorkspace; } public void relocate(SVNRepositoryLocation newLocation, String path, boolean recursive) throws SVNException { try { ISVNEntry targetEntry = locateEntry(path); if (targetEntry == null) { throw new SVNException("could not find directory '" + path + "'"); } if (!targetEntry.isDirectory()) { throw new SVNException("could not relocate file '" + path + "' only directories could be switched"); } String newURL = newLocation.toString(); targetEntry.setPropertyValue(SVNProperty.URL, newURL); for (Iterator children = targetEntry.asDirectory().childEntries(); children .hasNext();) { ISVNEntry child = (ISVNEntry) children.next(); updateURL(child, newURL, recursive); } targetEntry.save(); if (targetEntry.equals(getRoot())) { setLocation(newLocation); } } finally { getRoot().dispose(); } } public long status(String path, boolean remote, ISVNStatusHandler handler, boolean descend, boolean includeUnmodified, boolean includeIgnored) throws SVNException { return status(path, remote, handler, descend, includeUnmodified, includeIgnored, false, false); } public long status(String path, boolean remote, ISVNStatusHandler handler, boolean descend, boolean includeUnmodified, boolean includeIgnored, boolean descendInUnversioned, boolean descendFurtherInIgnored) throws SVNException { return status(path, remote, handler, descend, includeUnmodified, includeIgnored, descendInUnversioned, descendFurtherInIgnored, null); } public long status(String path, boolean remote, ISVNStatusHandler handler, boolean descend, boolean includeUnmodified, boolean includeIgnored, boolean descendInUnversioned, boolean descendFurtherInIgnored, ISVNProgressViewer progressViewer) throws SVNException { long start = System.currentTimeMillis(); if (getLocation() == null) { // throw new SVNException(getRoot().getID() + " does not contain // working copy files"); return -1; } if (path == null) { path = ""; } long revision = -1; SVNStatusEditor editor = null; ISVNEntry targetEntry = locateEntry(path, true); if (targetEntry == null) { return -1; } if (remote && targetEntry != null) { ISVNEntry entry = targetEntry; if (!entry.isDirectory()) { entry = locateParentEntry(path); } SVNRepository repository = SVNUtil.createRepository(this, entry .getPath()); String target = null; if (!targetEntry.isDirectory()) { target = targetEntry.getName(); } SVNLock[] locks = null; try { locks = repository.getLocks(target == null ? "" : target); } catch (SVNException e) { } editor = new SVNStatusEditor(entry.getPath(), locks); SVNReporterBaton reporterBaton = new SVNReporterBaton(null, entry, target, descend); repository.status(ISVNWorkspace.HEAD, target, descend, reporterBaton, editor); revision = editor.getTargetRevision(); } if (handler == null) { return revision; } Collection externals = createExternals(path); ISVNEntry parent = null; if (!"".equals(path)) { parent = locateParentEntry(path); } if (targetEntry != null && parent != null && parent.asDirectory().isIgnored(targetEntry.getName())) { includeIgnored = true; } SVNStatusUtil.doStatus(this, parent != null ? parent.asDirectory() : null, editor, handler, path, externals, descend, includeUnmodified, includeIgnored, descendInUnversioned, descendFurtherInIgnored, progressViewer); if (myExternalsHandler != null && externals != null) { Collection paths = new HashSet(); for (Iterator exts = externals.iterator(); exts.hasNext();) { SVNExternal external = (SVNExternal) exts.next(); if (paths.contains(external.getPath())) { continue; } paths.add(external.getPath()); if (!descend && !external.getPath().equals(path)) { DebugLog.log("SKIPPING EXTERNAL STATUS FOR " + external.getPath()); continue; } else if (!external.getPath().startsWith(path)) { DebugLog.log("SKIPPING EXTERNAL STATUS FOR " + external.getPath()); continue; } DebugLog.log("EXTERNAL STATUS FOR " + external.getPath()); ISVNWorkspace extWorkspace = createWorkspace(external); myExternalsHandler .handleStatus(this, external.getPath(), extWorkspace, handler, remote, descend, includeUnmodified, includeIgnored, descendInUnversioned); } } DebugLog.benchmark("STATUS COMPLETED IN " + (System.currentTimeMillis() - start)); return revision; } public SVNStatus status(final String filePath, boolean remote) throws SVNException { final SVNStatus[] result = new SVNStatus[1]; status(filePath, remote, new ISVNStatusHandler() { public void handleStatus(String path, SVNStatus status) { if (status.getPath().equals(filePath)) { result[0] = status; } } }, false, true, true); return result[0]; } public void log(String path, long startRevision, long endRevison, boolean stopOnCopy, boolean discoverPath, ISVNLogEntryHandler handler) throws SVNException { if (getLocation() == null) { throw new SVNException(getRoot().getID() + " does not contain working copy files"); } ISVNEntry entry = locateEntry(path); String targetPath = ""; SVNRepository repository; if (!entry.isDirectory()) { targetPath = entry.getName(); repository = SVNUtil.createRepository(this, PathUtil .removeTail(path)); } else { repository = SVNUtil.createRepository(this, path); } repository.log(new String[] { targetPath }, startRevision, endRevison, discoverPath, stopOnCopy, handler); } // import public long commit(SVNRepositoryLocation destination, String message) throws SVNException { return commit(destination, null, message); } public long commit(SVNRepositoryLocation destination, String fileName, String message) throws SVNException { if (fileName == null && getLocation() != null) { throw new SVNException(getRoot().getID() + " already contains working copy files"); } if (fileName != null && locateEntry(fileName) != null) { throw new SVNException("'" + fileName + "' already under version control"); } SVNRepository repository = SVNRepositoryFactory.create(destination); repository.setCredentialsProvider(getCredentialsProvider()); repository.testConnection(); String rootPath = PathUtil.decode(destination.getPath()); rootPath = rootPath.substring(repository.getRepositoryRoot().length()); if (!rootPath.startsWith("/")) { rootPath = "/" + rootPath; } rootPath = PathUtil.removeTrailingSlash(rootPath); List dirsList = new LinkedList(); DebugLog.log("IMPORT: ROOT PATH: " + rootPath); while (rootPath.lastIndexOf('/') >= 0) { SVNNodeKind nodeKind = repository.checkPath(rootPath, -1); if (nodeKind == SVNNodeKind.DIR) { break; } else if (nodeKind == SVNNodeKind.FILE) { throw new SVNException("'" + rootPath + "' is file, could not import into it"); } String dir = rootPath.substring(rootPath.lastIndexOf('/') + 1); dirsList.add(0, dir); rootPath = rootPath.substring(0, rootPath.lastIndexOf('/')); } destination = new SVNRepositoryLocation(destination.getProtocol(), destination.getHost(), destination.getPort(), PathUtil.append( repository.getRepositoryRoot(), rootPath)); repository = SVNRepositoryFactory.create(destination); repository.setCredentialsProvider(getCredentialsProvider()); DebugLog.log("IMPORT: REPOSITORY CREATED FOR: " + destination.toString()); ISVNEditor editor = repository.getCommitEditor(message, getRoot()); SVNCommitInfo info = null; try { String dir = ""; DebugLog.log("IMPORT: OPEN ROOT"); editor.openRoot(-1); for (Iterator dirs = dirsList.iterator(); dirs.hasNext();) { String nextDir = (String) dirs.next(); DebugLog.log("IMPORT: NEXT DIR: " + nextDir); dir = dir + '/' + nextDir; DebugLog.log("IMPORT: ADDING MISSING DIR: " + dir); editor.addDir(dir, null, -1); } if (fileName == null) { for (Iterator children = getRoot().asDirectory() .unmanagedChildEntries(false); children.hasNext();) { ISVNEntry child = (ISVNEntry) children.next(); doImport(dir, editor, getRoot(), child); } } else { ISVNEntry child = locateEntry(fileName, true); doImport(dir, editor, getRoot(), child); } for (Iterator dirs = dirsList.iterator(); dirs.hasNext();) { dirs.next(); editor.closeDir(); } editor.closeDir(); fireEntryCommitted(null, SVNStatus.ADDED); info = editor.closeEdit(); } catch (SVNException e) { try { editor.abortEdit(); } catch (SVNException inner) { } DebugLog.error(e); throw e; } finally { getRoot().dispose(); } return info != null ? info.getNewRevision() : -1; } // real commit public long commit(String message) throws SVNException { return commit("", message, true); } public long commit(String path, String message, boolean recursive) throws SVNException { return commit(new String[] { path }, message, recursive, true); } public long commit(String[] paths, final String message, boolean recursive) throws SVNException { return commit(paths, message, recursive, true); } public long commit(String[] paths, final String message, boolean recursive, boolean includeParents) throws SVNException { return commit(paths, new ISVNCommitHandler() { public String handleCommit(SVNStatus[] tobeCommited) { return message == null ? "" : message; } }, recursive, includeParents); } public long commit(String[] paths, ISVNCommitHandler handler, boolean recursive) throws SVNException { return commit(paths, handler, recursive, true); } public long commit(String[] paths, ISVNCommitHandler handler, boolean recursive, boolean includeParents) throws SVNException { if (handler == null) { handler = new ISVNCommitHandler() { public String handleCommit(SVNStatus[] tobeCommited) { return ""; } }; } final SVNCommitPacket packet = createCommitPacket(paths, recursive, includeParents); if (packet == null) { DebugLog.log("NOTHING TO COMMIT"); return -1; } return commit(packet, false, handler.handleCommit(packet.getStatuses())); } public SVNStatus[] getCommittables(String[] paths, boolean recursive, boolean includeParents) throws SVNException { long start = System.currentTimeMillis(); for (int i = 0; i < paths.length; i++) { ISVNEntry entry = locateEntry(paths[i]); if (entry == null || !entry.isManaged()) { throw new SVNException("'" + paths[i] + "' is not under version control"); } else if (entry != null && entry.getPropertyValue(SVNProperty.COPIED) != null && !entry.isScheduledForAddition()) { throw new SVNException( "'" + entry.getPath() + "' is marked as 'copied' but is not itself scheduled for addition. " + "Perhaps you're committing a target that is inside unversioned (or not-yet-versioned) directory?"); } } try { final String root = getCommitRoot(paths); final ISVNEntry rootEntry = locateEntry(root); if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) { throw new SVNException(root + " does not contain working copy files"); } DebugLog.log(""); DebugLog.log("COMMIT ROOT: " + root); for (int i = 0; i < paths.length; i++) { DebugLog.log("COMMIT PATH " + i + " :" + paths[i]); } Collection modified = new HashSet(); if (recursive) { SVNCommitUtil.harvestCommitables(rootEntry, paths, recursive, modified); } else { for (int i = 0; i < paths.length; i++) { String path = paths[i]; ISVNEntry entry = locateEntry(path); SVNCommitUtil.harvestCommitables(entry, paths, recursive, modified); } } Collection modifiedParents = new HashSet(); for (Iterator modifiedEntries = modified.iterator(); modifiedEntries .hasNext();) { ISVNEntry entry = (ISVNEntry) modifiedEntries.next(); if (!entry.isDirectory() && entry.asFile().isCorrupted()) { throw new SVNException("svn: Checksum of base file '" + entry.getPath() + "' is not valid"); } String p = entry.getPath(); if (entry.isScheduledForAddition()) { ISVNEntry parent = locateParentEntry(entry.getPath()); while (parent != null && parent.isScheduledForAddition() && !parent.isScheduledForDeletion()) { if (!includeParents) { if (!modified.contains(parent)) { throw new SVNException("'" + p + "' is not under version control"); } break; } modifiedParents.add(parent); DebugLog .log("HV: 'added' parent added to transaction: " + parent.getPath()); parent = locateParentEntry(parent.getPath()); } } } modified.addAll(modifiedParents); if (modified.isEmpty()) { return null; } SVNStatus[] statuses = new SVNStatus[modified.size()]; Map urls = new HashMap(); int index = 0; String uuid = null; for (Iterator entries = modified.iterator(); entries.hasNext();) { ISVNEntry entry = (ISVNEntry) entries.next(); String url = entry.getPropertyValue(SVNProperty.URL); String entryUUID = entry.getPropertyValue(SVNProperty.UUID); if (entryUUID != null) { if (uuid != null && !uuid.equals(entryUUID)) { throw new SVNException( - "commit contains entries from the different repositories '" - + entry.getPath() + "' and '" - + urls.get(url) + "'"); + "svn: Cannot commit both '" + entry.getPath() + + "' and '" + urls.get(url) + + "' as they refer to the same URL"); } uuid = entryUUID; } if (urls.containsKey(url)) { throw new SVNException( - "commit contains entries with the same url '" - + entry.getPath() + "' and '" - + urls.get(url) + "'"); + "svn: Cannot commit both '" + entry.getPath() + + "' and '" + urls.get(url) + + "' as they refer to the same URL"); } urls.put(url, entry.getPath()); if (entry.isConflict()) { throw new SVNException("resolve conflict in '" + entry.getPath() + "' before commit"); } statuses[index++] = SVNStatusUtil.createStatus(entry, -1, 0, 0, null); } DebugLog.log("Calculating committables took " + (System.currentTimeMillis() - start) + " ms."); return statuses; } finally { if (!myIsCopyCommit) { getRoot().dispose(); } } } public SVNCommitPacket createCommitPacket(String[] paths, boolean recursive, boolean includeParents) throws SVNException { final SVNStatus[] committables = getCommittables(paths, recursive, includeParents); return committables != null ? new SVNCommitPacket(getCommitRoot(paths), committables) : null; } public long commit(SVNCommitPacket packet, boolean keepLocks, String message) throws SVNException { final SVNStatus[] statuses = packet.getStatuses(); return commitPaths(getPathsFromStatuses(statuses), message, keepLocks, null); } public long commitPaths(List paths, String message, boolean keepLocks, ISVNProgressViewer progressViewer) throws SVNException { long start = System.currentTimeMillis(); try { final Set modified = new HashSet(); for (Iterator it = paths.iterator(); it.hasNext();) { final String path = (String) it.next(); ISVNEntry entry = locateEntry(path); modified.add(entry); } if (message == null || modified.isEmpty()) { DebugLog.log("NOTHING TO COMMIT"); return -1; } String root = getCommitRoot((String[]) paths .toArray(new String[paths.size()])); ISVNEntry rootEntry = locateEntry(root); if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) { throw new SVNException(root + " does not contain working copy files"); } DebugLog.log("COMMIT MESSAGE: " + message); Map tree = new HashMap(); Map locks = new HashMap(); String url = SVNCommitUtil.buildCommitTree(modified, tree, locks); for (Iterator treePaths = tree.keySet().iterator(); treePaths .hasNext();) { String treePath = (String) treePaths.next(); if (tree.get(treePath) != null) { DebugLog.log("TREE ENTRY : " + treePath + " : " + ((ISVNEntry) tree.get(treePath)).getPath()); } else { DebugLog.log("TREE ENTRY : " + treePath + " : null"); } } DebugLog.log("COMMIT ROOT RECALCULATED: " + url); DebugLog.log("COMMIT PREPARATIONS TOOK: " + (System.currentTimeMillis() - start) + " ms."); SVNRepositoryLocation location = SVNRepositoryLocation .parseURL(url); SVNRepository repository = SVNRepositoryFactory.create(location); repository.setCredentialsProvider(getCredentialsProvider()); repository.testConnection(); String host = location.getProtocol() + "://" + location.getHost() + ":" + location.getPort(); String rootURL = PathUtil.append(host, repository .getRepositoryRoot()); if (!locks.isEmpty()) { Map transaltedLocks = new HashMap(); for (Iterator lockedPaths = locks.keySet().iterator(); lockedPaths .hasNext();) { String lockedPath = (String) lockedPaths.next(); String relativePath = lockedPath .substring(rootURL.length()); if (!relativePath.startsWith("/")) { relativePath = "/" + relativePath; } transaltedLocks.put(relativePath, locks.get(lockedPath)); } locks = transaltedLocks; } else { locks = null; } DebugLog.log("LOCKS ready for commit: " + locks); ISVNEditor editor = repository .getCommitEditor(message, locks, keepLocks, new SVNWorkspaceMediatorAdapter(getRoot(), tree)); SVNCommitInfo info; try { SVNCommitUtil.doCommit("", rootURL, tree, editor, this, progressViewer); info = editor.closeEdit(); } catch (SVNException e) { DebugLog.error("error: " + e.getMessage()); if (e.getErrors() != null) { for (int i = 0; i < e.getErrors().length; i++) { SVNError error = e.getErrors()[i]; if (error != null) { DebugLog.error(error.toString()); } } } try { editor.abortEdit(); } catch (SVNException inner) { } throw e; } catch (Throwable th) { throw new SVNException(th); } DebugLog.log("COMMIT TOOK: " + (System.currentTimeMillis() - start) + " ms."); if (!myIsCopyCommit) { start = System.currentTimeMillis(); SVNCommitUtil.updateWorkingCopy(info, rootEntry .getPropertyValue(SVNProperty.UUID), tree, this, keepLocks); sleepForTimestamp(); DebugLog.log("POST COMMIT ACTIONS TOOK: " + (System.currentTimeMillis() - start) + " ms."); } return info != null ? info.getNewRevision() : -1; } finally { myIsCopyCommit = false; getRoot().dispose(); } } public void add(String path, boolean mkdir, boolean recurse) throws SVNException { try { ISVNEntry entry = locateParentEntry(path); String name = PathUtil.tail(path); if (entry == null || entry.isMissing() || !entry.isDirectory()) { throw new SVNException( "can't locate versioned parent entry for '" + path + "'"); } if (mkdir && entry != null && !entry.isManaged() && entry.isDirectory() && entry != getRoot()) { add(entry.getPath(), mkdir, recurse); getRoot().dispose(); entry = locateParentEntry(path); } if (entry != null && name != null && entry.isManaged() && !entry.isMissing() && entry.isDirectory()) { ISVNEntry child = entry.asDirectory().scheduleForAddition(name, mkdir, recurse); doApplyAutoProperties(child, recurse); fireEntryModified(child, SVNStatus.ADDED, true); entry.save(); entry.dispose(); } else { throw new SVNException( "can't locate versioned parent entry for '" + path + "'"); } } finally { getRoot().dispose(); } } private void doApplyAutoProperties(ISVNEntry addedEntry, boolean recurse) throws SVNException { applyAutoProperties(addedEntry, null); if (recurse && addedEntry.isDirectory()) { for (Iterator children = addedEntry.asDirectory().childEntries(); children .hasNext();) { ISVNEntry childEntry = (ISVNEntry) children.next(); if (childEntry.isScheduledForAddition()) { doApplyAutoProperties(childEntry, recurse); } } } } public void delete(String path) throws SVNException { delete(path, false); } public void delete(String path, boolean force) throws SVNException { try { ISVNEntry entry = locateParentEntry(path); String name = PathUtil.tail(path); if (entry != null && name != null) { if (!force) { // check if files are modified. assertNotModified(entry.asDirectory().getChild(name)); assertNotModified(entry.asDirectory().getUnmanagedChild( name)); } ISVNEntry child = entry.asDirectory().scheduleForDeletion(name, force); fireEntryModified(child, SVNStatus.DELETED, true); entry.save(); entry.dispose(); } else if (entry == null) { } } finally { getRoot().dispose(); } } private static void assertNotModified(ISVNEntry entry) throws SVNException { if (entry == null) { return; } if (!entry.isManaged()) { throw new SVNException( "'" + entry.getPath() + "' is unmanaged, use 'force' parameter to force deletion."); } else if (entry.isScheduledForAddition() && !entry.isMissing()) { throw new SVNException( "'" + entry.getPath() + "' is modified locally, use 'force' parameter to force deletion."); } if (entry.isPropertiesModified()) { throw new SVNException( "'" + entry.getPath() + "' is modified locally, use 'force' parameter to force deletion."); } if (!entry.isDirectory()) { if (entry.asFile().isContentsModified()) { throw new SVNException( "'" + entry.getPath() + "' is modified locally, use 'force' parameter to force deletion."); } } else { for (Iterator children = entry.asDirectory().unmanagedChildEntries( true); children.hasNext();) { assertNotModified((ISVNEntry) children.next()); } for (Iterator children = entry.asDirectory().childEntries(); children .hasNext();) { assertNotModified((ISVNEntry) children.next()); } } } public void copy(String source, String destination, boolean move) throws SVNException { copy(source, destination, move, false); } public void copy(String source, String destination, boolean move, boolean virtual) throws SVNException { try { if (virtual) { // check if unversioned destination is already there ISVNEntry dstEntry = locateEntry(destination, true); if (dstEntry != null && dstEntry.isManaged()) { throw new SVNException( "'" + destination + "' already exists in working copy and it is versioned"); } ISVNEntry srcEntry = locateEntry(source, false); if (move) { if (srcEntry == null || !srcEntry.isMissing()) { throw new SVNException( "'" + source + "' already exists in working copy and it is not missing"); } } else { if (srcEntry == null || !srcEntry.isManaged()) { throw new SVNException("'" + source + "' does not exist in working copy."); } } } else { ISVNEntry entry = locateEntry(destination); if (entry != null && entry.isScheduledForDeletion()) { throw new SVNException("'" + destination + "' is scheduled for deletion"); } if (locateEntry(destination, true) != null) { throw new SVNException("'" + destination + "' already exists in working copy"); } } ISVNEntry entry = locateParentEntry(destination); String name = PathUtil.tail(destination); ISVNEntry toCopyParent = locateParentEntry(source); ISVNEntry sourceEntry = locateEntry(source); if (entry == null || !entry.isDirectory()) { throw new SVNException("'" + destination + "' is not under version control"); } if (toCopyParent == null || !toCopyParent.isDirectory()) { throw new SVNException("'" + source + "' is not under version control"); } if (sourceEntry == null) { throw new SVNException("'" + source + "' is not under version control"); } String toCopyName = PathUtil.tail(source); ISVNEntry toCopy = toCopyParent.asDirectory().getChild(toCopyName); ISVNEntry copied = entry.asDirectory().copy(name, toCopy); fireEntryModified(copied, SVNStatus.ADDED, true); if (move && toCopyParent != null) { toCopyParent.asDirectory().scheduleForDeletion( toCopy.getName(), true); fireEntryModified(toCopy, SVNStatus.DELETED, false); toCopyParent.save(); toCopyParent.dispose(); } entry.save(); entry.dispose(); sleepForTimestamp(); } finally { getRoot().dispose(); } } public void copy(SVNRepositoryLocation source, String destination, long revision) throws SVNException { copy(source, destination, revision, null); } public void copy(SVNRepositoryLocation source, String destination, long revision, ISVNProgressViewer progressViewer) throws SVNException { File tmpFile = null; try { SVNRepository repository = SVNRepositoryFactory.create(source); repository.setCredentialsProvider(myCredentialsProvider); ISVNEntry entry = locateEntry(destination); if (entry != null) { if (!entry.isDirectory()) { throw new SVNException("can't copy over versioned file '" + entry.getPath() + "'"); } destination = PathUtil.append(destination, PathUtil.tail(source .getPath())); } SVNNodeKind srcKind = repository.checkPath("", revision); DebugLog.log("copy destination is : " + destination); if (srcKind == SVNNodeKind.DIR) { DebugLog.log("local uuid: " + getRoot().getPropertyValue(SVNProperty.UUID)); DebugLog.log("remote uuid: " + repository.getRepositoryUUID()); if (!repository.getRepositoryUUID().equals( getRoot().getPropertyValue(SVNProperty.UUID))) { throw new SVNException( "couldn't copy directory from another repository"); } String root = PathUtil.append(getID(), destination); DebugLog.log("checkout ws root : " + root); ISVNWorkspace ws = SVNWorkspaceManager.createWorkspace( getRoot().getType(), root); ws.setCredentials(myCredentialsProvider); ws.setAutoProperties(getAutoProperties()); ws.setExternalsHandler(myExternalsHandler); if (myListeners != null) { for (Iterator listeners = myListeners.iterator(); listeners .hasNext();) { ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners .next(); ws.addWorkspaceListener(listener); } } DebugLog.log("checking out revision: " + revision); revision = ws.checkout(source, revision, false, true, progressViewer); ISVNEntry dirEntry = locateEntry(PathUtil .removeTail(destination)); dirEntry.asDirectory().markAsCopied(PathUtil.tail(destination), source, revision); } else if (srcKind == SVNNodeKind.FILE) { Map properties = new HashMap(); tmpFile = File.createTempFile("svn.", ".tmp"); tmpFile.deleteOnExit(); OutputStream tmpStream = new FileOutputStream(tmpFile); repository.getFile("", revision, properties, tmpStream); tmpStream.close(); InputStream in = new FileInputStream(tmpFile); String name = PathUtil.tail(destination); ISVNEntry dirEntry = locateEntry(PathUtil .removeTail(destination)); if (repository.getRepositoryUUID().equals( getRoot().getPropertyValue(SVNProperty.UUID))) { dirEntry.asDirectory().markAsCopied(in, tmpFile.length(), properties, name, source); } else { dirEntry.asDirectory().markAsCopied(in, tmpFile.length(), properties, name, null); } in.close(); } else { throw new SVNException("can't copy from '" + source.toCanonicalForm() + "', location doesn't exist at revision " + revision); } } catch (IOException e) { DebugLog.error(e); } finally { if (tmpFile != null) { tmpFile.delete(); } getRoot().dispose(); } } public long copy(String src, SVNRepositoryLocation destination, String message) throws SVNException { return copy(src, destination, message, null); } public long copy(String src, SVNRepositoryLocation destination, String message, ISVNProgressViewer progressViewer) throws SVNException { ISVNEntry entry = locateEntry(src); ISVNEntry parent = locateParentEntry(src); if (entry == null) { throw new SVNException("no versioned entry found at '" + src + "'"); } try { String url = destination.toCanonicalForm(); String name = PathUtil.tail(src); SVNRepository repository = SVNRepositoryFactory.create(destination); repository.setCredentialsProvider(myCredentialsProvider); if (repository.checkPath("", -1) == SVNNodeKind.NONE) { name = PathUtil.tail(url); name = PathUtil.decode(name); url = PathUtil.removeTail(url); } entry.setAlias(name); DebugLog.log("entry path: " + entry.getPath()); DebugLog.log("entry aliased path: " + entry.getAlias()); // set copyfrom url to original source url and revision. entry.setPropertyValue(SVNProperty.COPYFROM_URL, entry .getPropertyValue(SVNProperty.URL)); entry.setPropertyValue(SVNProperty.COPYFROM_REVISION, entry .getPropertyValue(SVNProperty.REVISION)); entry.setPropertyValue(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_ADD); entry.setPropertyValue(SVNProperty.WC_URL, null); if (entry.isDirectory() && parent != null) { Map entryProps = ((FSDirEntry) parent).getChildEntryMap(entry .getName()); entryProps.put(SVNProperty.COPYFROM_URL, entry .getPropertyValue(SVNProperty.URL)); entryProps.put(SVNProperty.COPYFROM_REVISION, entry .getPropertyValue(SVNProperty.REVISION)); entryProps.put(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_ADD); entryProps.put(SVNProperty.COPIED, "true"); } FSDirEntry.updateURL(entry, url); FSDirEntry.setPropertyValueRecursively(entry, SVNProperty.COPIED, "true"); // commit without saving properties (no entry.save/commit calls). repository = SVNRepositoryFactory.create(SVNRepositoryLocation .parseURL(url)); repository.setCredentialsProvider(myCredentialsProvider); ISVNEditor editor = repository.getCommitEditor(message, getRoot()); myIsCopyCommit = true; SVNStatus[] committablePaths = getCommittables( new String[] { src }, true, false); return commitPaths(getPathsFromStatuses(committablePaths), message, false, progressViewer); } finally { getRoot().dispose(); myIsCopyCommit = false; } } public Iterator propertyNames(String path) throws SVNException { ISVNEntry entry = locateEntry(path); if (entry == null) { return Collections.EMPTY_LIST.iterator(); } Collection names = new LinkedList(); for (Iterator propNames = entry.propertyNames(); propNames.hasNext();) { names.add(propNames.next()); } return names.iterator(); } public String getPropertyValue(String path, String name) throws SVNException { ISVNEntry entry = locateEntry(path); if (entry == null) { return null; } return entry.getPropertyValue(name); } public Map getProperties(String path, boolean reposProps, boolean entryProps) throws SVNException { Map props = new HashMap(); ISVNEntry entry = locateEntry(path, true); if (entry == null) { return null; } boolean add = false; for (Iterator names = entry.propertyNames(); names.hasNext();) { String name = (String) names.next(); if (name.startsWith(SVNProperty.SVN_ENTRY_PREFIX)) { add = entryProps; } else { add = reposProps; } if (add) { props.put(name, entry.getPropertyValue(name)); add = false; } } return props; } public void setPropertyValue(String path, String name, String value) throws SVNException { setPropertyValue(path, name, value, false); } public void setPropertyValue(String path, String name, String value, boolean recurse) throws SVNException { try { ISVNEntry entry = locateEntry(path); if (entry == null) { return; } doSetProperty(entry, name, value, recurse); entry.save(); entry.dispose(); } finally { getRoot().dispose(); } } public void markResolved(String path, boolean recursive) throws SVNException { try { ISVNEntry entry = locateEntry(path); ISVNEntry parent = null; if (!entry.isDirectory()) { parent = locateParentEntry(path); } doMarkResolved(entry, recursive); fireEntryModified(entry, SVNStatus.RESOLVED, recursive); if (parent != null) { entry = parent; } entry.save(); entry.dispose(); sleepForTimestamp(); } finally { getRoot().dispose(); } } public void revert(String path, boolean recursive) throws SVNException { try { ISVNEntry entry = locateEntry(path); if (entry == null || (entry.isDirectory() && entry.isMissing())) { if (entry != null) { ISVNEntry parent = locateParentEntry(path); if (parent != null && parent.isDirectory()) { boolean reverted = parent.asDirectory().revert( entry.getName()); parent.save(); fireEntryModified(entry, reverted ? SVNStatus.REVERTED : SVNStatus.NOT_REVERTED, false); return; } } return; } ISVNDirectoryEntry parent = null; parent = (ISVNDirectoryEntry) locateParentEntry(path); doMarkResolved(entry, recursive); doRevert(parent, entry, entry.isDirectory() && entry.isScheduledForAddition(), recursive); if (parent == null && entry == getRoot()) { entry.asDirectory().revert(null); } if (parent != null) { entry = parent; } entry.save(); entry.dispose(); sleepForTimestamp(); } finally { getRoot().dispose(); } } public void revert(String srcPath, String dstPath, boolean recursive) throws SVNException { try { myIsCommandRunning = true; ISVNEntry src = locateEntry(srcPath); if (src != null && src.isScheduledForDeletion()) { revert(srcPath, recursive); } // copy props and contents from dst to source (for each file in src // that exists in dst). // revert dst. revert(dstPath, recursive); } finally { myIsCommandRunning = false; sleepForTimestamp(); getRoot().dispose(); } } public void unlock(String path, boolean force) throws SVNException { try { ISVNEntry entry = locateEntry(path); if (entry == null) { throw new SVNException("no versioned entry at '" + path + "'"); } String token = entry.getPropertyValue(SVNProperty.LOCK_TOKEN); if (token == null && !force) { throw new SVNException("'" + path + "' is not locked in this working copy"); } String name = ""; if (!entry.isDirectory()) { name = entry.getName(); path = PathUtil.removeTail(path); } SVNRepository repository = SVNUtil.createRepository(this, path); repository.removeLock(name, token, force); entry.setPropertyValue(SVNProperty.LOCK_TOKEN, null); entry.setPropertyValue(SVNProperty.LOCK_COMMENT, null); entry.setPropertyValue(SVNProperty.LOCK_CREATION_DATE, null); entry.setPropertyValue(SVNProperty.LOCK_OWNER, null); entry.save(); } finally { getRoot().dispose(); } } public SVNLock lock(String path, String comment, boolean force) throws SVNException { SVNLock lock = null; try { comment = comment == null ? "" : comment; ISVNEntry entry = locateEntry(path); if (entry == null) { throw new SVNException("no versioned entry at '" + path + "'"); } if (entry.isScheduledForAddition()) { throw new SVNException("'" + path + "' is not added to repository yet"); } String name = ""; if (!entry.isDirectory()) { name = entry.getName(); path = PathUtil.removeTail(path); } SVNRepository repository = SVNUtil.createRepository(this, path); long revision = SVNProperty.longValue(entry .getPropertyValue(SVNProperty.REVISION)); lock = repository.setLock(name, comment, force, revision); if (lock != null) { entry.setPropertyValue(SVNProperty.LOCK_TOKEN, lock.getID()); entry.setPropertyValue(SVNProperty.LOCK_COMMENT, comment); entry.setPropertyValue(SVNProperty.LOCK_CREATION_DATE, TimeUtil .formatDate(lock.getCreationDate())); entry.setPropertyValue(SVNProperty.LOCK_OWNER, lock.getOwner()); entry.save(false); if (!entry.isDirectory()) { locateParentEntry(entry.getPath()).save(false); } } } finally { getRoot().dispose(); } return lock; } public ISVNEntryContent getContent(String path) throws SVNException { ISVNEntry entry = locateEntry(path, true); if (entry == null) { throw new SVNException("Can't find entry for path " + path); } return entry.getContent(); } public ISVNFileContent getFileContent(String path) throws SVNException { ISVNEntry entry = locateEntry(path, true); if (entry == null) { throw new SVNException("Can't find entry for path " + path); } if (entry.isDirectory()) { return null; } return (ISVNFileContent) entry.getContent(); } protected void fireEntryCommitted(ISVNEntry entry, int kind) { if (myListeners == null || entry == null) { return; } for (Iterator listeners = myListeners.iterator(); listeners.hasNext();) { ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners .next(); listener.committed(entry.getPath(), kind); } } protected void fireEntryUpdated(ISVNEntry entry, int contentsStatus, int propsStatus, long revision) { if (myListeners == null || entry == null) { return; } for (Iterator listeners = myListeners.iterator(); listeners.hasNext();) { ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners .next(); listener.updated(entry.getPath(), contentsStatus, propsStatus, revision); } } protected void fireEntryModified(ISVNEntry entry, int kind, boolean recursive) { if (myListeners == null || entry == null) { return; } for (Iterator listeners = myListeners.iterator(); listeners.hasNext();) { ISVNWorkspaceListener listener = (ISVNWorkspaceListener) listeners .next(); listener.modified(entry.getPath(), kind); } if (entry.isDirectory() && recursive) { Iterator children = null; try { children = entry.asDirectory().childEntries(); } catch (SVNException e) { } while (children != null && children.hasNext()) { fireEntryModified((ISVNEntry) children.next(), kind, recursive); } } } private ISVNRootEntry getRoot() { return myRoot; } private void doRevert(ISVNDirectoryEntry parent, ISVNEntry entry, boolean dirsOnly, boolean recursive) throws SVNException { boolean restored = !entry.isDirectory() && entry.isMissing(); if (entry.isDirectory() && recursive) { Collection namesList = new LinkedList(); for (Iterator children = entry.asDirectory().childEntries(); children .hasNext();) { ISVNEntry child = (ISVNEntry) children.next(); if (dirsOnly && !child.isDirectory()) { continue; } namesList.add(child); } for (Iterator names = namesList.iterator(); names.hasNext();) { ISVNEntry child = (ISVNEntry) names.next(); doRevert(entry.asDirectory(), child, dirsOnly, recursive); } } if (parent != null) { boolean reverted = parent.revert(entry.getName()); if (!restored) { fireEntryModified(entry, reverted ? SVNStatus.REVERTED : SVNStatus.NOT_REVERTED, false); } else { fireEntryModified(entry, SVNStatus.RESTORED, false); } } if (!entry.isDirectory()) { entry.dispose(); } } private void doMarkResolved(ISVNEntry entry, boolean recursive) throws SVNException { if (entry.isDirectory() && recursive) { for (Iterator children = entry.asDirectory().childEntries(); children .hasNext();) { doMarkResolved((ISVNEntry) children.next(), recursive); } } entry.markResolved(); } private void doSetProperty(ISVNEntry entry, String name, String value, boolean recurse) throws SVNException { entry.setPropertyValue(name, value); fireEntryModified(entry, SVNStatus.MODIFIED, false); if (recurse && entry.isDirectory()) { for (Iterator entries = entry.asDirectory().childEntries(); entries .hasNext();) { ISVNEntry child = (ISVNEntry) entries.next(); doSetProperty(child, name, value, recurse); } } } private void doImport(String rootPath, ISVNEditor editor, ISVNDirectoryEntry parent, ISVNEntry entry) throws SVNException { if (rootPath.trim().length() > 0) { rootPath += "/"; } if (entry.isDirectory()) { DebugLog.log("IMPORT: ADDING DIR: " + rootPath + entry.getPath()); editor.addDir(rootPath + entry.getPath(), null, -1); applyAutoProperties(entry, editor); for (Iterator children = entry.asDirectory().unmanagedChildEntries( false); children.hasNext();) { ISVNEntry child = (ISVNEntry) children.next(); doImport(rootPath, editor, parent, child); } editor.closeDir(); } else { DebugLog.log("IMPORT: ADDING FILE: " + rootPath + entry.getPath()); editor.addFile(rootPath + entry.getPath(), null, -1); applyAutoProperties(entry, editor); entry.setPropertyValue(SVNProperty.SCHEDULE, SVNProperty.SCHEDULE_ADD); entry.asFile().generateDelta(editor); editor.closeFile(null); } fireEntryCommitted(entry, SVNStatus.ADDED); } private void applyAutoProperties(ISVNEntry entry, ISVNEditor editor) throws SVNException { if (myCompiledAutoProperties == null) { myCompiledAutoProperties = compileAutoProperties(myAutoProperties); } for (Iterator keys = myCompiledAutoProperties.keySet().iterator(); keys .hasNext();) { Pattern pattern = (Pattern) keys.next(); if (pattern.matcher(entry.getName().toLowerCase()).matches()) { Map properties = (Map) myCompiledAutoProperties.get(pattern); for (Iterator entries = properties.entrySet().iterator(); entries .hasNext();) { Map.Entry propEntry = (Map.Entry) entries.next(); String name = (String) propEntry.getKey(); String value = (String) propEntry.getValue(); entry.setPropertyValue(name, value); if (editor == null) { continue; } if (entry.isDirectory()) { editor.changeDirProperty(name, value); } else { editor.changeFileProperty(name, value); } } } } } private static Map compileAutoProperties(Map source) { Map result = new HashMap(); for (Iterator entries = source.entrySet().iterator(); entries.hasNext();) { Map.Entry entry = (Map.Entry) entries.next(); if (entry.getValue() == null) { continue; } String key = (String) entry.getKey(); StringBuffer regex = new StringBuffer(); regex.append('^'); // convert key wildcard into regexp for (int i = 0; i < key.length(); i++) { char ch = key.charAt(i); if (ch == '.') { regex.append("\\."); } else if (ch == '?') { regex.append('.'); } else if (ch == '*') { regex.append(".*"); } else { regex.append(ch); } } regex.append('$'); String properties = (String) entry.getValue(); Map parsedProperties = new HashMap(); for (StringTokenizer props = new StringTokenizer(properties, ";"); props .hasMoreTokens();) { String propset = props.nextToken(); int index = propset.indexOf('='); String value = ""; String name = null; if (index < 0) { name = propset; } else { name = propset.substring(0, index); value = propset.substring(index + 1); } parsedProperties.put(name, value); } if (!parsedProperties.isEmpty()) { result.put(Pattern.compile(regex.toString().toLowerCase()), parsedProperties); } } return result; } ISVNEntry locateEntry(String path) throws SVNException { return locateEntry(path, false); } ISVNEntry locateEntry(String path, boolean unmanaged) throws SVNException { ISVNEntry entry = getRoot(); for (StringTokenizer tokens = new StringTokenizer(path, "/"); tokens .hasMoreTokens();) { String token = tokens.nextToken(); if (entry == null) { return null; } entry = entry.asDirectory().getUnmanagedChild(token); } if (entry != null && !unmanaged && !entry.isManaged()) { return null; } return entry; } ISVNEntry locateParentEntry(String path) throws SVNException { ISVNEntry entry = getRoot(); if ("".equals(path)) { return null; } for (StringTokenizer tokens = new StringTokenizer(path, "/"); tokens .hasMoreTokens();) { String token = tokens.nextToken(); if (!tokens.hasMoreTokens()) { return entry; } entry = entry.asDirectory().getUnmanagedChild(token); } return null; } private static void updateURL(ISVNEntry target, String parentURL, boolean recursive) throws SVNException { parentURL = PathUtil.append(parentURL, PathUtil .encode(target.getName())); target.setPropertyValue(SVNProperty.URL, parentURL); target.setPropertyValue(SVNProperty.WC_URL, null); if (target.isDirectory() && recursive) { for (Iterator children = target.asDirectory().childEntries(); children .hasNext();) { ISVNEntry child = (ISVNEntry) children.next(); updateURL(child, parentURL, recursive); } } } private Collection createExternals(String path) throws SVNException { Collection externals = new HashSet(); ISVNEntry parent = null; if (!"".equals(path)) { parent = locateParentEntry(path); } if (parent == null || !parent.isDirectory()) { return externals; } ISVNDirectoryEntry current = parent.asDirectory(); while (current != null) { externals = SVNExternal.create(current, externals); current = (ISVNDirectoryEntry) locateParentEntry(current.getPath()); } return externals; } public void runCommand(ISVNRunnable runnable) throws SVNException { myIsCommandRunning = true; myIsNeedToSleepForTimestamp = false; try { runnable.run(this); } catch (Throwable th) { if (th instanceof SVNException) { throw ((SVNException) th); } throw new SVNException(th); } finally { myIsCommandRunning = false; if (myIsNeedToSleepForTimestamp) { sleepForTimestamp(); myIsNeedToSleepForTimestamp = false; } } } private void sleepForTimestamp() { if (myIsCommandRunning) { myIsNeedToSleepForTimestamp = true; return; } FSUtil.sleepForTimestamp(); } private String getCommitRoot(String[] paths) throws SVNException { String root = ""; if (paths.length == 1) { ISVNEntry entry = locateEntry(paths[0]); if (entry != null && entry.isDirectory() && entry.isManaged()) { root = entry.getPath(); } } if (root == null) { root = PathUtil.getCommonRoot(paths); if (root == null) { root = ""; } } return root; } private List getPathsFromStatuses(final SVNStatus[] statuses) { final List paths = new ArrayList(); for (int index = 0; index < statuses.length; index++) { if (statuses[index] != null) { final String path = statuses[index].getPath(); paths.add(path); } } return paths; } }
false
true
public SVNStatus[] getCommittables(String[] paths, boolean recursive, boolean includeParents) throws SVNException { long start = System.currentTimeMillis(); for (int i = 0; i < paths.length; i++) { ISVNEntry entry = locateEntry(paths[i]); if (entry == null || !entry.isManaged()) { throw new SVNException("'" + paths[i] + "' is not under version control"); } else if (entry != null && entry.getPropertyValue(SVNProperty.COPIED) != null && !entry.isScheduledForAddition()) { throw new SVNException( "'" + entry.getPath() + "' is marked as 'copied' but is not itself scheduled for addition. " + "Perhaps you're committing a target that is inside unversioned (or not-yet-versioned) directory?"); } } try { final String root = getCommitRoot(paths); final ISVNEntry rootEntry = locateEntry(root); if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) { throw new SVNException(root + " does not contain working copy files"); } DebugLog.log(""); DebugLog.log("COMMIT ROOT: " + root); for (int i = 0; i < paths.length; i++) { DebugLog.log("COMMIT PATH " + i + " :" + paths[i]); } Collection modified = new HashSet(); if (recursive) { SVNCommitUtil.harvestCommitables(rootEntry, paths, recursive, modified); } else { for (int i = 0; i < paths.length; i++) { String path = paths[i]; ISVNEntry entry = locateEntry(path); SVNCommitUtil.harvestCommitables(entry, paths, recursive, modified); } } Collection modifiedParents = new HashSet(); for (Iterator modifiedEntries = modified.iterator(); modifiedEntries .hasNext();) { ISVNEntry entry = (ISVNEntry) modifiedEntries.next(); if (!entry.isDirectory() && entry.asFile().isCorrupted()) { throw new SVNException("svn: Checksum of base file '" + entry.getPath() + "' is not valid"); } String p = entry.getPath(); if (entry.isScheduledForAddition()) { ISVNEntry parent = locateParentEntry(entry.getPath()); while (parent != null && parent.isScheduledForAddition() && !parent.isScheduledForDeletion()) { if (!includeParents) { if (!modified.contains(parent)) { throw new SVNException("'" + p + "' is not under version control"); } break; } modifiedParents.add(parent); DebugLog .log("HV: 'added' parent added to transaction: " + parent.getPath()); parent = locateParentEntry(parent.getPath()); } } } modified.addAll(modifiedParents); if (modified.isEmpty()) { return null; } SVNStatus[] statuses = new SVNStatus[modified.size()]; Map urls = new HashMap(); int index = 0; String uuid = null; for (Iterator entries = modified.iterator(); entries.hasNext();) { ISVNEntry entry = (ISVNEntry) entries.next(); String url = entry.getPropertyValue(SVNProperty.URL); String entryUUID = entry.getPropertyValue(SVNProperty.UUID); if (entryUUID != null) { if (uuid != null && !uuid.equals(entryUUID)) { throw new SVNException( "commit contains entries from the different repositories '" + entry.getPath() + "' and '" + urls.get(url) + "'"); } uuid = entryUUID; } if (urls.containsKey(url)) { throw new SVNException( "commit contains entries with the same url '" + entry.getPath() + "' and '" + urls.get(url) + "'"); } urls.put(url, entry.getPath()); if (entry.isConflict()) { throw new SVNException("resolve conflict in '" + entry.getPath() + "' before commit"); } statuses[index++] = SVNStatusUtil.createStatus(entry, -1, 0, 0, null); } DebugLog.log("Calculating committables took " + (System.currentTimeMillis() - start) + " ms."); return statuses; } finally { if (!myIsCopyCommit) { getRoot().dispose(); } } }
public SVNStatus[] getCommittables(String[] paths, boolean recursive, boolean includeParents) throws SVNException { long start = System.currentTimeMillis(); for (int i = 0; i < paths.length; i++) { ISVNEntry entry = locateEntry(paths[i]); if (entry == null || !entry.isManaged()) { throw new SVNException("'" + paths[i] + "' is not under version control"); } else if (entry != null && entry.getPropertyValue(SVNProperty.COPIED) != null && !entry.isScheduledForAddition()) { throw new SVNException( "'" + entry.getPath() + "' is marked as 'copied' but is not itself scheduled for addition. " + "Perhaps you're committing a target that is inside unversioned (or not-yet-versioned) directory?"); } } try { final String root = getCommitRoot(paths); final ISVNEntry rootEntry = locateEntry(root); if (rootEntry == null || rootEntry.getPropertyValue(SVNProperty.URL) == null) { throw new SVNException(root + " does not contain working copy files"); } DebugLog.log(""); DebugLog.log("COMMIT ROOT: " + root); for (int i = 0; i < paths.length; i++) { DebugLog.log("COMMIT PATH " + i + " :" + paths[i]); } Collection modified = new HashSet(); if (recursive) { SVNCommitUtil.harvestCommitables(rootEntry, paths, recursive, modified); } else { for (int i = 0; i < paths.length; i++) { String path = paths[i]; ISVNEntry entry = locateEntry(path); SVNCommitUtil.harvestCommitables(entry, paths, recursive, modified); } } Collection modifiedParents = new HashSet(); for (Iterator modifiedEntries = modified.iterator(); modifiedEntries .hasNext();) { ISVNEntry entry = (ISVNEntry) modifiedEntries.next(); if (!entry.isDirectory() && entry.asFile().isCorrupted()) { throw new SVNException("svn: Checksum of base file '" + entry.getPath() + "' is not valid"); } String p = entry.getPath(); if (entry.isScheduledForAddition()) { ISVNEntry parent = locateParentEntry(entry.getPath()); while (parent != null && parent.isScheduledForAddition() && !parent.isScheduledForDeletion()) { if (!includeParents) { if (!modified.contains(parent)) { throw new SVNException("'" + p + "' is not under version control"); } break; } modifiedParents.add(parent); DebugLog .log("HV: 'added' parent added to transaction: " + parent.getPath()); parent = locateParentEntry(parent.getPath()); } } } modified.addAll(modifiedParents); if (modified.isEmpty()) { return null; } SVNStatus[] statuses = new SVNStatus[modified.size()]; Map urls = new HashMap(); int index = 0; String uuid = null; for (Iterator entries = modified.iterator(); entries.hasNext();) { ISVNEntry entry = (ISVNEntry) entries.next(); String url = entry.getPropertyValue(SVNProperty.URL); String entryUUID = entry.getPropertyValue(SVNProperty.UUID); if (entryUUID != null) { if (uuid != null && !uuid.equals(entryUUID)) { throw new SVNException( "svn: Cannot commit both '" + entry.getPath() + "' and '" + urls.get(url) + "' as they refer to the same URL"); } uuid = entryUUID; } if (urls.containsKey(url)) { throw new SVNException( "svn: Cannot commit both '" + entry.getPath() + "' and '" + urls.get(url) + "' as they refer to the same URL"); } urls.put(url, entry.getPath()); if (entry.isConflict()) { throw new SVNException("resolve conflict in '" + entry.getPath() + "' before commit"); } statuses[index++] = SVNStatusUtil.createStatus(entry, -1, 0, 0, null); } DebugLog.log("Calculating committables took " + (System.currentTimeMillis() - start) + " ms."); return statuses; } finally { if (!myIsCopyCommit) { getRoot().dispose(); } } }
diff --git a/src/com/fsaravia/utilities/GUIMensajes.java b/src/com/fsaravia/utilities/GUIMensajes.java index 1727ae4..2211905 100644 --- a/src/com/fsaravia/utilities/GUIMensajes.java +++ b/src/com/fsaravia/utilities/GUIMensajes.java @@ -1,98 +1,102 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.fsaravia.utilities; import com.ib.HBCore.exceptions.ValidationException; import com.ib.mailing.reportes.ReportarErrores; import java.awt.Component; import java.awt.Container; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author Fede */ public class GUIMensajes extends JOptionPane { private static void mostrarError(Component padre, String error) { showMessageDialog(padre, error, "Error", JOptionPane.ERROR_MESSAGE); } private static void mostrarError(Component padre, Throwable error) { mostrarError(padre, error.getLocalizedMessage()); } // // private static void mostrarError(Component padreI, Throwable error, boolean reportar, String remitente) { // boolean enviar = true; // if (error instanceof ValidationException) { // enviar = false; // } // if (error.getCause() != null && error.getCause() instanceof ValidationException) { // enviar = false; // } // if (reportar && enviar) { // int op = showConfirmDialog(padre, error.getLocalizedMessage() + "\n\n¿Desea reportar este error?", "Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); // if (op == JOptionPane.YES_OPTION) { // //padre // ReportarErrores report = new ReportarErrores(null, error); // report.setLocationRelativeTo(padre); // report.setVisible(true); // } // } else { // mostrarError(padre, error); // } // } public static void mostrarErrorReportar(Component padre, Throwable error) { boolean enviar = true; if (error instanceof ValidationException) { enviar = false; } if (error.getCause() != null && error.getCause() instanceof ValidationException) { enviar = false; } if (enviar) { Logger.getLogger(padre.getClass().getName()).log(Level.SEVERE, null, error); int op = showConfirmDialog(padre, error.getLocalizedMessage() + "\n\n¿Desea reportar este error?", "Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if (op == JOptionPane.YES_OPTION) { //padre ReportarErrores report = new ReportarErrores(null, error); report.setLocationRelativeTo(padre); report.setVisible(true); } } else { - mostrarError(padre, error); + if (error instanceof ValidationException) { + mostrarMensaje(padre, error.getLocalizedMessage()); + } else { + mostrarError(padre, error); + } } } public static void mostrarMensaje(Component padre, String mensaje) { showMessageDialog(padre, mensaje, "Mensaje", JOptionPane.INFORMATION_MESSAGE); } public static boolean mostrarPregunta(Component padre, String pregunta) { int op = showConfirmDialog(padre, pregunta, "Pregunta", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); return op == JOptionPane.YES_OPTION; } public static JDialog mostrarMensaje(Component padre, String mensaje, String titulo) { JFrame ventana = null; try { ventana = (JFrame) padre; if (ventana == null) { ventana = (JFrame) ((Container) padre).getParent(); } } catch (ClassCastException cce) { ventana = null; } finally { Dialogo d = new Dialogo(ventana, false, titulo, mensaje); d.setLocationRelativeTo(padre); return d; } } }
true
true
public static void mostrarErrorReportar(Component padre, Throwable error) { boolean enviar = true; if (error instanceof ValidationException) { enviar = false; } if (error.getCause() != null && error.getCause() instanceof ValidationException) { enviar = false; } if (enviar) { Logger.getLogger(padre.getClass().getName()).log(Level.SEVERE, null, error); int op = showConfirmDialog(padre, error.getLocalizedMessage() + "\n\n¿Desea reportar este error?", "Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if (op == JOptionPane.YES_OPTION) { //padre ReportarErrores report = new ReportarErrores(null, error); report.setLocationRelativeTo(padre); report.setVisible(true); } } else { mostrarError(padre, error); } }
public static void mostrarErrorReportar(Component padre, Throwable error) { boolean enviar = true; if (error instanceof ValidationException) { enviar = false; } if (error.getCause() != null && error.getCause() instanceof ValidationException) { enviar = false; } if (enviar) { Logger.getLogger(padre.getClass().getName()).log(Level.SEVERE, null, error); int op = showConfirmDialog(padre, error.getLocalizedMessage() + "\n\n¿Desea reportar este error?", "Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE); if (op == JOptionPane.YES_OPTION) { //padre ReportarErrores report = new ReportarErrores(null, error); report.setLocationRelativeTo(padre); report.setVisible(true); } } else { if (error instanceof ValidationException) { mostrarMensaje(padre, error.getLocalizedMessage()); } else { mostrarError(padre, error); } } }