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/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java b/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java index 44a1fa8..7eae552 100644 --- a/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java +++ b/CodenameG/src/edu/chl/codenameg/model/levels/LevelFactory.java @@ -1,280 +1,273 @@ package edu.chl.codenameg.model.levels; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.newdawn.slick.SlickException; import org.newdawn.slick.tiled.TiledMap; import edu.chl.codenameg.model.Entity; import edu.chl.codenameg.model.Hitbox; import edu.chl.codenameg.model.Position; import edu.chl.codenameg.model.entity.Block; import edu.chl.codenameg.model.entity.CheckPoint; import edu.chl.codenameg.model.entity.GoalBlock; import edu.chl.codenameg.model.entity.LethalBlock; import edu.chl.codenameg.model.entity.LethalMovingBlock; import edu.chl.codenameg.model.entity.MovableBlock; import edu.chl.codenameg.model.entity.MovingBlock; import edu.chl.codenameg.model.entity.MovingWall; import edu.chl.codenameg.model.entity.Water; public class LevelFactory { private static LevelFactory instance; private LevelFactory() { } public static LevelFactory getInstance() { if (instance == null) { instance = new LevelFactory(); } return instance; } public Level getLevel(int i) throws IllegalArgumentException { Level l = loadLevelFromFile(getLevelFilePath(i)); if (l != null) { return l; } else { throw new IllegalArgumentException("The level does not exist"); } } public Level loadLevelFromFile(String path) { List<Entity> entities = new ArrayList<Entity>(); Map<Integer, Position> spawnPositions = new HashMap<Integer, Position>(); TiledMap tiledmap; int numberOfPlayers = 1; try { tiledmap = new TiledMap(path); for (int groupID = 0; groupID < tiledmap.getObjectGroupCount(); groupID++) { for (int objectID = 0; objectID < tiledmap .getObjectCount(groupID); objectID++) { String name = tiledmap.getObjectName(groupID, objectID); if (name.equals("Water")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity water = new Water(position, hitbox); entities.add(water); } if (name.equals("Block")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity block = new Block(position, hitbox); entities.add(block); } if (name.equals("LethalBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity lethalblock = new LethalBlock(position, hitbox); entities.add(lethalblock); } if (name.equals("MovableBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity movableblock = new MovableBlock(position, hitbox); entities.add(movableblock); } if (name.equals("MovingBlock") || name.equals("LethalMovingBlock") || name.equals("MovingWall")) { String direction = tiledmap.getObjectProperty(groupID, objectID, "Direction", "down"); Position endPosition = new Position(0, 0); Position startPosition = new Position(0, 0); Entity movingblock; String lethality = tiledmap.getObjectProperty(groupID, objectID, "lethality", "false"); int traveltime = Integer.parseInt(tiledmap .getObjectProperty(groupID, objectID, "traveltime", "1000")); if (name.equals(("MovingBlock"))) { movingblock = new MovingBlock(); } else if (name.equals("LethalMovingBlock")) { movingblock = new LethalMovingBlock(); } else { movingblock = new MovingWall(); } if (direction.equals("up")) { endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID) + tiledmap.getObjectHeight(groupID, objectID) - movingblock.getHitbox().getHeight()); } else if (direction.equals("down")) { startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID) + tiledmap.getObjectHeight(groupID, objectID) - movingblock.getHitbox().getHeight()); } else if (direction.equals("right")) { startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); endPosition = new Position( tiledmap.getObjectX(groupID, objectID) + tiledmap.getObjectWidth(groupID, objectID) - movingblock.getHitbox() .getWidth(), tiledmap.getObjectY(groupID, objectID)); } else if (direction.equals("left")) { endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); startPosition = new Position( tiledmap.getObjectX(groupID, objectID) + tiledmap.getObjectWidth(groupID, objectID) - movingblock.getHitbox() .getWidth(), tiledmap.getObjectY(groupID, objectID)); } if (name.equals(("MovingBlock"))) { movingblock = new MovingBlock(startPosition, endPosition, traveltime); } else if (name.equals("LethalMovingBlock")) { movingblock = new LethalMovingBlock(startPosition, endPosition, traveltime); - } else { - if (lethality.equals("false")) { - movingblock = new MovingWall(startPosition, - endPosition, traveltime, false); - ((MovingWall)movingblock).setHitbox(new Hitbox(32, - (tiledmap.getObjectHeight( - objectID, groupID)))); - } else { - movingblock = new MovingWall(startPosition, - endPosition, traveltime, true); - ((MovingWall) movingblock).setHitbox(new Hitbox(32, - (tiledmap.getObjectHeight( - objectID, groupID)))); - } + } else { // MovingWall + movingblock = new MovingWall(startPosition, + endPosition, traveltime, + lethality.equals("true")); + ((MovingWall) movingblock).setHitbox(new Hitbox(32, + (int) tiledmap.getObjectHeight(groupID, + objectID))); } entities.add(movingblock); } if (name.equals("GoalBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity lethalblock = new GoalBlock(position, hitbox); entities.add(lethalblock); } if (name.equals("SpawnPC1")) { spawnPositions.put( 1, new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID))); } if (name.equals("SpawnPC2")) { spawnPositions.put( 2, new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID))); } if (name.equals("CheckPoint")) { Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Entity checkpoint = new CheckPoint(position, hitbox, null); entities.add(checkpoint); } } } numberOfPlayers = Integer.parseInt(tiledmap.getMapProperty( "numberOfPlayers", "1")); } catch (SlickException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } Level level = new GeneratedLevel(entities, spawnPositions, numberOfPlayers); return level; } public String getLevelFilePath(int i) { return "levels/level" + i + ".tmx"; } private class GeneratedLevel implements Level { private List<Entity> entities; private Map<Integer, Position> spawnPositions; private int numberPlayers; public GeneratedLevel(List<Entity> entities, Map<Integer, Position> spawnPositions, int numberPlayers) { this.entities = entities; this.spawnPositions = spawnPositions; this.numberPlayers = numberPlayers; } @Override public List<Entity> getListOfEntities() { return entities; } @Override public Position getPlayerSpawnPosition(int playerno) { if (spawnPositions.get(playerno) != null) { return spawnPositions.get(playerno); } else { return new Position(0, 0); } } @Override public int getAmountOfPlayers() { return numberPlayers; } } }
true
true
public Level loadLevelFromFile(String path) { List<Entity> entities = new ArrayList<Entity>(); Map<Integer, Position> spawnPositions = new HashMap<Integer, Position>(); TiledMap tiledmap; int numberOfPlayers = 1; try { tiledmap = new TiledMap(path); for (int groupID = 0; groupID < tiledmap.getObjectGroupCount(); groupID++) { for (int objectID = 0; objectID < tiledmap .getObjectCount(groupID); objectID++) { String name = tiledmap.getObjectName(groupID, objectID); if (name.equals("Water")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity water = new Water(position, hitbox); entities.add(water); } if (name.equals("Block")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity block = new Block(position, hitbox); entities.add(block); } if (name.equals("LethalBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity lethalblock = new LethalBlock(position, hitbox); entities.add(lethalblock); } if (name.equals("MovableBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity movableblock = new MovableBlock(position, hitbox); entities.add(movableblock); } if (name.equals("MovingBlock") || name.equals("LethalMovingBlock") || name.equals("MovingWall")) { String direction = tiledmap.getObjectProperty(groupID, objectID, "Direction", "down"); Position endPosition = new Position(0, 0); Position startPosition = new Position(0, 0); Entity movingblock; String lethality = tiledmap.getObjectProperty(groupID, objectID, "lethality", "false"); int traveltime = Integer.parseInt(tiledmap .getObjectProperty(groupID, objectID, "traveltime", "1000")); if (name.equals(("MovingBlock"))) { movingblock = new MovingBlock(); } else if (name.equals("LethalMovingBlock")) { movingblock = new LethalMovingBlock(); } else { movingblock = new MovingWall(); } if (direction.equals("up")) { endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID) + tiledmap.getObjectHeight(groupID, objectID) - movingblock.getHitbox().getHeight()); } else if (direction.equals("down")) { startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID) + tiledmap.getObjectHeight(groupID, objectID) - movingblock.getHitbox().getHeight()); } else if (direction.equals("right")) { startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); endPosition = new Position( tiledmap.getObjectX(groupID, objectID) + tiledmap.getObjectWidth(groupID, objectID) - movingblock.getHitbox() .getWidth(), tiledmap.getObjectY(groupID, objectID)); } else if (direction.equals("left")) { endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); startPosition = new Position( tiledmap.getObjectX(groupID, objectID) + tiledmap.getObjectWidth(groupID, objectID) - movingblock.getHitbox() .getWidth(), tiledmap.getObjectY(groupID, objectID)); } if (name.equals(("MovingBlock"))) { movingblock = new MovingBlock(startPosition, endPosition, traveltime); } else if (name.equals("LethalMovingBlock")) { movingblock = new LethalMovingBlock(startPosition, endPosition, traveltime); } else { if (lethality.equals("false")) { movingblock = new MovingWall(startPosition, endPosition, traveltime, false); ((MovingWall)movingblock).setHitbox(new Hitbox(32, (tiledmap.getObjectHeight( objectID, groupID)))); } else { movingblock = new MovingWall(startPosition, endPosition, traveltime, true); ((MovingWall) movingblock).setHitbox(new Hitbox(32, (tiledmap.getObjectHeight( objectID, groupID)))); } } entities.add(movingblock); } if (name.equals("GoalBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity lethalblock = new GoalBlock(position, hitbox); entities.add(lethalblock); } if (name.equals("SpawnPC1")) { spawnPositions.put( 1, new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID))); } if (name.equals("SpawnPC2")) { spawnPositions.put( 2, new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID))); } if (name.equals("CheckPoint")) { Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Entity checkpoint = new CheckPoint(position, hitbox, null); entities.add(checkpoint); } } } numberOfPlayers = Integer.parseInt(tiledmap.getMapProperty( "numberOfPlayers", "1")); } catch (SlickException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } Level level = new GeneratedLevel(entities, spawnPositions, numberOfPlayers); return level; }
public Level loadLevelFromFile(String path) { List<Entity> entities = new ArrayList<Entity>(); Map<Integer, Position> spawnPositions = new HashMap<Integer, Position>(); TiledMap tiledmap; int numberOfPlayers = 1; try { tiledmap = new TiledMap(path); for (int groupID = 0; groupID < tiledmap.getObjectGroupCount(); groupID++) { for (int objectID = 0; objectID < tiledmap .getObjectCount(groupID); objectID++) { String name = tiledmap.getObjectName(groupID, objectID); if (name.equals("Water")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity water = new Water(position, hitbox); entities.add(water); } if (name.equals("Block")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity block = new Block(position, hitbox); entities.add(block); } if (name.equals("LethalBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity lethalblock = new LethalBlock(position, hitbox); entities.add(lethalblock); } if (name.equals("MovableBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity movableblock = new MovableBlock(position, hitbox); entities.add(movableblock); } if (name.equals("MovingBlock") || name.equals("LethalMovingBlock") || name.equals("MovingWall")) { String direction = tiledmap.getObjectProperty(groupID, objectID, "Direction", "down"); Position endPosition = new Position(0, 0); Position startPosition = new Position(0, 0); Entity movingblock; String lethality = tiledmap.getObjectProperty(groupID, objectID, "lethality", "false"); int traveltime = Integer.parseInt(tiledmap .getObjectProperty(groupID, objectID, "traveltime", "1000")); if (name.equals(("MovingBlock"))) { movingblock = new MovingBlock(); } else if (name.equals("LethalMovingBlock")) { movingblock = new LethalMovingBlock(); } else { movingblock = new MovingWall(); } if (direction.equals("up")) { endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID) + tiledmap.getObjectHeight(groupID, objectID) - movingblock.getHitbox().getHeight()); } else if (direction.equals("down")) { startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID) + tiledmap.getObjectHeight(groupID, objectID) - movingblock.getHitbox().getHeight()); } else if (direction.equals("right")) { startPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); endPosition = new Position( tiledmap.getObjectX(groupID, objectID) + tiledmap.getObjectWidth(groupID, objectID) - movingblock.getHitbox() .getWidth(), tiledmap.getObjectY(groupID, objectID)); } else if (direction.equals("left")) { endPosition = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); startPosition = new Position( tiledmap.getObjectX(groupID, objectID) + tiledmap.getObjectWidth(groupID, objectID) - movingblock.getHitbox() .getWidth(), tiledmap.getObjectY(groupID, objectID)); } if (name.equals(("MovingBlock"))) { movingblock = new MovingBlock(startPosition, endPosition, traveltime); } else if (name.equals("LethalMovingBlock")) { movingblock = new LethalMovingBlock(startPosition, endPosition, traveltime); } else { // MovingWall movingblock = new MovingWall(startPosition, endPosition, traveltime, lethality.equals("true")); ((MovingWall) movingblock).setHitbox(new Hitbox(32, (int) tiledmap.getObjectHeight(groupID, objectID))); } entities.add(movingblock); } if (name.equals("GoalBlock")) { Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Entity lethalblock = new GoalBlock(position, hitbox); entities.add(lethalblock); } if (name.equals("SpawnPC1")) { spawnPositions.put( 1, new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID))); } if (name.equals("SpawnPC2")) { spawnPositions.put( 2, new Position(tiledmap.getObjectX(groupID, objectID), tiledmap.getObjectY(groupID, objectID))); } if (name.equals("CheckPoint")) { Position position = new Position(tiledmap.getObjectX( groupID, objectID), tiledmap.getObjectY( groupID, objectID)); Hitbox hitbox = new Hitbox(tiledmap.getObjectWidth( groupID, objectID) - 1, tiledmap.getObjectHeight(groupID, objectID) - 1); Entity checkpoint = new CheckPoint(position, hitbox, null); entities.add(checkpoint); } } } numberOfPlayers = Integer.parseInt(tiledmap.getMapProperty( "numberOfPlayers", "1")); } catch (SlickException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } Level level = new GeneratedLevel(entities, spawnPositions, numberOfPlayers); return level; }
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/utils/DeadlockDetector.java b/AE-go_GameServer/src/com/aionemu/gameserver/utils/DeadlockDetector.java index 411547d8..d847100c 100644 --- a/AE-go_GameServer/src/com/aionemu/gameserver/utils/DeadlockDetector.java +++ b/AE-go_GameServer/src/com/aionemu/gameserver/utils/DeadlockDetector.java @@ -1,151 +1,151 @@ /* * This file is part of aion-unique <aion-unique.org>. * * aion-unique is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * aion-unique is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with aion-unique. If not, see <http://www.gnu.org/licenses/>. */ package com.aionemu.gameserver.utils; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import org.apache.log4j.Logger; /** * @author ATracer */ public class DeadlockDetector implements Runnable { private static final Logger log = Logger.getLogger(DeadlockDetector.class); private int checkInterval = 0; private static String INDENT = " "; private StringBuilder sb = null; public DeadlockDetector(int checkInterval) { this.checkInterval = checkInterval * 1000; } @Override public void run() { boolean noDeadLocks = true; while(noDeadLocks) { try { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] threadIds = bean.findDeadlockedThreads(); if (threadIds != null) { log.error("Deadlock detected!"); sb = new StringBuilder(); noDeadLocks = false; ThreadInfo[] infos = bean.getThreadInfo(threadIds); sb.append("\nTHREAD LOCK INFO: \n"); for (ThreadInfo threadInfo : infos) { printThreadInfo(threadInfo); LockInfo[] lockInfos = threadInfo.getLockedSynchronizers(); MonitorInfo[] monitorInfos = threadInfo.getLockedMonitors(); printLockInfo(lockInfos); printMonitorInfo(threadInfo, monitorInfos); } sb.append("\nTHREAD DUMPS: \n"); for (ThreadInfo ti : bean.dumpAllThreads(true, true)) { - printThread(ti); + printThreadInfo(ti); } log.error(sb.toString()); } Thread.sleep(checkInterval); } catch(Exception ex) { ex.printStackTrace(); } } } private void printThreadInfo(ThreadInfo threadInfo) { printThread(threadInfo); sb.append(INDENT + threadInfo.toString() + "\n"); StackTraceElement[] stacktrace = threadInfo.getStackTrace(); MonitorInfo[] monitors = threadInfo.getLockedMonitors(); for (int i = 0; i < stacktrace.length; i++) { StackTraceElement ste = stacktrace[i]; sb.append(INDENT + "at " + ste.toString() + "\n"); for (MonitorInfo mi : monitors) { if (mi.getLockedStackDepth() == i) { sb.append(INDENT + " - locked " + mi + "\n"); } } } } private void printThread(ThreadInfo ti) { sb.append("\nPrintThread\n"); sb.append("\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " in " + ti.getThreadState() + "\n"); if (ti.getLockName() != null) { sb.append(" on lock=" + ti.getLockName() + "\n"); } if (ti.isSuspended()) { sb.append(" (suspended)" + "\n"); } if (ti.isInNative()) { sb.append(" (running in native)" + "\n"); } if (ti.getLockOwnerName() != null) { sb.append(INDENT + " owned by " + ti.getLockOwnerName() + " Id=" + ti.getLockOwnerId() + "\n"); } } private void printMonitorInfo(ThreadInfo threadInfo, MonitorInfo[] monitorInfos) { sb.append(INDENT + "Locked monitors: count = " + monitorInfos.length + "\n"); for (MonitorInfo monitorInfo : monitorInfos) { sb.append(INDENT + " - " + monitorInfo + " locked at " + "\n"); sb.append(INDENT + " " + monitorInfo.getLockedStackDepth() + " " + monitorInfo.getLockedStackFrame() + "\n"); } } private void printLockInfo(LockInfo[] lockInfos) { sb.append(INDENT + "Locked synchronizers: count = " + lockInfos.length + "\n"); for (LockInfo lockInfo : lockInfos) { sb.append(INDENT + " - " + lockInfo + "\n"); } } }
true
true
public void run() { boolean noDeadLocks = true; while(noDeadLocks) { try { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] threadIds = bean.findDeadlockedThreads(); if (threadIds != null) { log.error("Deadlock detected!"); sb = new StringBuilder(); noDeadLocks = false; ThreadInfo[] infos = bean.getThreadInfo(threadIds); sb.append("\nTHREAD LOCK INFO: \n"); for (ThreadInfo threadInfo : infos) { printThreadInfo(threadInfo); LockInfo[] lockInfos = threadInfo.getLockedSynchronizers(); MonitorInfo[] monitorInfos = threadInfo.getLockedMonitors(); printLockInfo(lockInfos); printMonitorInfo(threadInfo, monitorInfos); } sb.append("\nTHREAD DUMPS: \n"); for (ThreadInfo ti : bean.dumpAllThreads(true, true)) { printThread(ti); } log.error(sb.toString()); } Thread.sleep(checkInterval); } catch(Exception ex) { ex.printStackTrace(); } } }
public void run() { boolean noDeadLocks = true; while(noDeadLocks) { try { ThreadMXBean bean = ManagementFactory.getThreadMXBean(); long[] threadIds = bean.findDeadlockedThreads(); if (threadIds != null) { log.error("Deadlock detected!"); sb = new StringBuilder(); noDeadLocks = false; ThreadInfo[] infos = bean.getThreadInfo(threadIds); sb.append("\nTHREAD LOCK INFO: \n"); for (ThreadInfo threadInfo : infos) { printThreadInfo(threadInfo); LockInfo[] lockInfos = threadInfo.getLockedSynchronizers(); MonitorInfo[] monitorInfos = threadInfo.getLockedMonitors(); printLockInfo(lockInfos); printMonitorInfo(threadInfo, monitorInfos); } sb.append("\nTHREAD DUMPS: \n"); for (ThreadInfo ti : bean.dumpAllThreads(true, true)) { printThreadInfo(ti); } log.error(sb.toString()); } Thread.sleep(checkInterval); } catch(Exception ex) { ex.printStackTrace(); } } }
diff --git a/src/main/java/com/hyperic/hudson/plugin/S3Profile.java b/src/main/java/com/hyperic/hudson/plugin/S3Profile.java index d80b1c7..1ecd181 100644 --- a/src/main/java/com/hyperic/hudson/plugin/S3Profile.java +++ b/src/main/java/com/hyperic/hudson/plugin/S3Profile.java @@ -1,127 +1,126 @@ package com.hyperic.hudson.plugin; import hudson.FilePath; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import org.jets3t.service.S3Service; import org.jets3t.service.S3ServiceException; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.jets3t.service.model.S3Bucket; import org.jets3t.service.model.S3Object; import org.jets3t.service.security.AWSCredentials; public class S3Profile { String name; String accessKey; String secretKey; private S3Service s3; public static final Logger LOGGER = Logger.getLogger(S3Profile.class.getName()); public S3Profile() { } public S3Profile(String name, String accessKey, String secretKey) { this.name = name; this.accessKey = accessKey; this.secretKey = secretKey; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public void login() throws S3ServiceException { if (this.s3 != null) { return; } try { AWSCredentials creds = new AWSCredentials(this.accessKey, this.secretKey); this.s3 = new RestS3Service(creds); } catch (S3ServiceException e) { LOGGER.log(Level.SEVERE, e.getMessage()); throw e; } } public void check() throws S3ServiceException { this.s3.listAllBuckets(); } public void logout() { this.s3 = null; } private S3Bucket getOrCreateBucket(String bucketName) throws S3ServiceException { S3Bucket bucket = this.s3.getBucket(bucketName); if (bucket == null) { bucket = this.s3.createBucket(new S3Bucket(bucketName)); } return bucket; } public void upload(String bucketName, FilePath filePath, Map<String, String> envVars, PrintStream logger) throws IOException, InterruptedException { if (filePath.isDirectory()) { throw new IOException(filePath + " is a directory"); } else { File file = new File(filePath.getName()); S3Bucket bucket; try { bucket = getOrCreateBucket(bucketName); } catch (S3ServiceException e) { throw new IOException(bucketName + " bucket: " + e); } try { - S3Object fileObject = - new S3Object(bucket, file.getName()); + S3Object fileObject = new S3Object(bucket, file.getName()); fileObject.setDataInputStream(filePath.read()); this.s3.putObject(bucket, fileObject); } catch (Exception e) { - throw new IOException("put " + file + ": " + e); + throw new IOException("put " + file + ": " + e, e); } } } protected void log(final PrintStream logger, final String message) { final String name = StringUtils.defaultString(S3BucketPublisher.DESCRIPTOR.getShortName()); logger.println(name + message); } }
false
true
public void upload(String bucketName, FilePath filePath, Map<String, String> envVars, PrintStream logger) throws IOException, InterruptedException { if (filePath.isDirectory()) { throw new IOException(filePath + " is a directory"); } else { File file = new File(filePath.getName()); S3Bucket bucket; try { bucket = getOrCreateBucket(bucketName); } catch (S3ServiceException e) { throw new IOException(bucketName + " bucket: " + e); } try { S3Object fileObject = new S3Object(bucket, file.getName()); fileObject.setDataInputStream(filePath.read()); this.s3.putObject(bucket, fileObject); } catch (Exception e) { throw new IOException("put " + file + ": " + e); } } }
public void upload(String bucketName, FilePath filePath, Map<String, String> envVars, PrintStream logger) throws IOException, InterruptedException { if (filePath.isDirectory()) { throw new IOException(filePath + " is a directory"); } else { File file = new File(filePath.getName()); S3Bucket bucket; try { bucket = getOrCreateBucket(bucketName); } catch (S3ServiceException e) { throw new IOException(bucketName + " bucket: " + e); } try { S3Object fileObject = new S3Object(bucket, file.getName()); fileObject.setDataInputStream(filePath.read()); this.s3.putObject(bucket, fileObject); } catch (Exception e) { throw new IOException("put " + file + ": " + e, e); } } }
diff --git a/src/com/android/settings/DreamSettings.java b/src/com/android/settings/DreamSettings.java index d59242a5e..d9953aafc 100644 --- a/src/com/android/settings/DreamSettings.java +++ b/src/com/android/settings/DreamSettings.java @@ -1,158 +1,159 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import static android.provider.Settings.Secure.SCREENSAVER_ENABLED; import static android.provider.Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK; import android.app.ActionBar; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.admin.DevicePolicyManager; import android.content.ContentResolver; import android.content.Context; import android.content.res.Configuration; import android.database.ContentObserver; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.os.ServiceManager; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.provider.Settings; import android.util.Log; import android.view.Gravity; import android.view.IWindowManager; import android.widget.CompoundButton; import android.widget.Switch; import java.util.ArrayList; public class DreamSettings extends SettingsPreferenceFragment { private static final String TAG = "DreamSettings"; private static final String KEY_ACTIVATE_ON_DOCK = "activate_on_dock"; private CheckBoxPreference mActivateOnDockPreference; private Switch mEnableSwitch; private Enabler mEnabler; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); addPreferencesFromResource(R.xml.dream_settings); mActivateOnDockPreference = (CheckBoxPreference) findPreference(KEY_ACTIVATE_ON_DOCK); final Activity activity = getActivity(); mEnableSwitch = new Switch(activity); if (activity instanceof PreferenceActivity) { PreferenceActivity preferenceActivity = (PreferenceActivity) activity; - if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) { - final int padding = activity.getResources().getDimensionPixelSize( - R.dimen.action_bar_switch_padding); - mEnableSwitch.setPadding(0, 0, padding, 0); - activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, - ActionBar.DISPLAY_SHOW_CUSTOM); - activity.getActionBar().setCustomView(mEnableSwitch, new ActionBar.LayoutParams( - ActionBar.LayoutParams.WRAP_CONTENT, - ActionBar.LayoutParams.WRAP_CONTENT, - Gravity.CENTER_VERTICAL | Gravity.RIGHT)); - activity.getActionBar().setTitle(R.string.screensaver_settings_title); - } + // note: we do not check onIsHidingHeaders() or onIsMultiPane() because there's no + // switch in the left-hand pane to control this; we need to show the ON/OFF in our + // fragment every time + final int padding = activity.getResources().getDimensionPixelSize( + R.dimen.action_bar_switch_padding); + mEnableSwitch.setPadding(0, 0, padding, 0); + activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, + ActionBar.DISPLAY_SHOW_CUSTOM); + activity.getActionBar().setCustomView(mEnableSwitch, new ActionBar.LayoutParams( + ActionBar.LayoutParams.WRAP_CONTENT, + ActionBar.LayoutParams.WRAP_CONTENT, + Gravity.CENTER_VERTICAL | Gravity.RIGHT)); + activity.getActionBar().setTitle(R.string.screensaver_settings_title); } mEnabler = new Enabler(activity, mEnableSwitch); } public static boolean isScreenSaverEnabled(Context context) { return 0 != Settings.Secure.getInt( context.getContentResolver(), SCREENSAVER_ENABLED, 1); } public static void setScreenSaverEnabled(Context context, boolean enabled) { Settings.Secure.putInt( context.getContentResolver(), SCREENSAVER_ENABLED, enabled ? 1 : 0); } public static class Enabler implements CompoundButton.OnCheckedChangeListener { private final Context mContext; private Switch mSwitch; public Enabler(Context context, Switch switch_) { mContext = context; setSwitch(switch_); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { setScreenSaverEnabled(mContext, isChecked); } public void setSwitch(Switch switch_) { if (mSwitch == switch_) return; if (mSwitch != null) mSwitch.setOnCheckedChangeListener(null); mSwitch = switch_; mSwitch.setOnCheckedChangeListener(this); final boolean enabled = isScreenSaverEnabled(mContext); mSwitch.setChecked(enabled); } public void pause() { mSwitch.setOnCheckedChangeListener(null); } public void resume() { mSwitch.setOnCheckedChangeListener(this); } } @Override public void onResume() { if (mEnabler != null) { mEnabler.resume(); } final boolean currentActivateOnDock = 0 != Settings.Secure.getInt(getContentResolver(), SCREENSAVER_ACTIVATE_ON_DOCK, 1); mActivateOnDockPreference.setChecked(currentActivateOnDock); super.onResume(); } @Override public void onPause() { if (mEnabler != null) { mEnabler.pause(); } super.onPause(); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mActivateOnDockPreference) { Settings.Secure.putInt(getContentResolver(), SCREENSAVER_ACTIVATE_ON_DOCK, mActivateOnDockPreference.isChecked() ? 1 : 0); } return super.onPreferenceTreeClick(preferenceScreen, preference); } }
true
true
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); addPreferencesFromResource(R.xml.dream_settings); mActivateOnDockPreference = (CheckBoxPreference) findPreference(KEY_ACTIVATE_ON_DOCK); final Activity activity = getActivity(); mEnableSwitch = new Switch(activity); if (activity instanceof PreferenceActivity) { PreferenceActivity preferenceActivity = (PreferenceActivity) activity; if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) { final int padding = activity.getResources().getDimensionPixelSize( R.dimen.action_bar_switch_padding); mEnableSwitch.setPadding(0, 0, padding, 0); activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM); activity.getActionBar().setCustomView(mEnableSwitch, new ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT)); activity.getActionBar().setTitle(R.string.screensaver_settings_title); } } mEnabler = new Enabler(activity, mEnableSwitch); }
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); addPreferencesFromResource(R.xml.dream_settings); mActivateOnDockPreference = (CheckBoxPreference) findPreference(KEY_ACTIVATE_ON_DOCK); final Activity activity = getActivity(); mEnableSwitch = new Switch(activity); if (activity instanceof PreferenceActivity) { PreferenceActivity preferenceActivity = (PreferenceActivity) activity; // note: we do not check onIsHidingHeaders() or onIsMultiPane() because there's no // switch in the left-hand pane to control this; we need to show the ON/OFF in our // fragment every time final int padding = activity.getResources().getDimensionPixelSize( R.dimen.action_bar_switch_padding); mEnableSwitch.setPadding(0, 0, padding, 0); activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM); activity.getActionBar().setCustomView(mEnableSwitch, new ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT)); activity.getActionBar().setTitle(R.string.screensaver_settings_title); } mEnabler = new Enabler(activity, mEnableSwitch); }
diff --git a/wflow-core/src/main/java/org/joget/apps/app/lib/EmailTool.java b/wflow-core/src/main/java/org/joget/apps/app/lib/EmailTool.java index 41d89853..3e010453 100755 --- a/wflow-core/src/main/java/org/joget/apps/app/lib/EmailTool.java +++ b/wflow-core/src/main/java/org/joget/apps/app/lib/EmailTool.java @@ -1,231 +1,231 @@ package org.joget.apps.app.lib; import java.io.File; import java.lang.String; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.activation.FileDataSource; import javax.mail.internet.MimeUtility; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.joget.apps.app.model.AppDefinition; import org.joget.apps.app.service.AppService; import org.joget.apps.app.service.AppUtil; import org.joget.apps.form.model.Element; import org.joget.apps.form.model.Form; import org.joget.apps.form.model.FormData; import org.joget.apps.form.service.FileUtil; import org.joget.apps.form.service.FormUtil; import org.joget.commons.util.DynamicDataSourceManager; import org.joget.commons.util.HostManager; import org.joget.commons.util.LogUtil; import org.joget.plugin.base.DefaultApplicationPlugin; import org.joget.plugin.base.PluginException; import org.joget.plugin.base.PluginManager; import org.joget.workflow.model.WorkflowAssignment; import org.joget.workflow.util.WorkflowUtil; public class EmailTool extends DefaultApplicationPlugin { public String getName() { return "Email Tool"; } public String getDescription() { return "Sends email message to targeted recipient(s)"; } public String getVersion() { return "3.0.0"; } public Object execute(Map properties) { PluginManager pluginManager = (PluginManager) properties.get("pluginManager"); String formDataTable = (String) properties.get("formDataTable"); String smtpHost = (String) properties.get("host"); String smtpPort = (String) properties.get("port"); String smtpUsername = (String) properties.get("username"); String smtpPassword = (String) properties.get("password"); String security = (String) properties.get("security"); final String from = (String) properties.get("from"); final String cc = (String) properties.get("cc"); String toParticipantId = (String) properties.get("toParticipantId"); String toSpecific = (String) properties.get("toSpecific"); String emailSubject = (String) properties.get("subject"); String emailMessage = (String) properties.get("message"); String isHtml = (String) properties.get("isHtml"); WorkflowAssignment wfAssignment = (WorkflowAssignment) properties.get("workflowAssignment"); AppDefinition appDef = (AppDefinition) properties.get("appDef"); try { Map<String, String> replaceMap = null; if ("true".equalsIgnoreCase(isHtml)) { replaceMap = new HashMap<String, String>(); replaceMap.put("\\n", "<br/>"); } emailSubject = WorkflowUtil.processVariable(emailSubject, formDataTable, wfAssignment); emailMessage = AppUtil.processHashVariable(emailMessage, wfAssignment, null, replaceMap); smtpHost = AppUtil.processHashVariable(smtpHost, wfAssignment, null, null); smtpPort = AppUtil.processHashVariable(smtpPort, wfAssignment, null, null); smtpUsername = AppUtil.processHashVariable(smtpUsername, wfAssignment, null, null); smtpPassword = AppUtil.processHashVariable(smtpPassword, wfAssignment, null, null); security = AppUtil.processHashVariable(security, wfAssignment, null, null); // create the email message final HtmlEmail email = new HtmlEmail(); email.setHostName(smtpHost); if (smtpPort != null && smtpPort.length() != 0) { email.setSmtpPort(Integer.parseInt(smtpPort)); } if (smtpUsername != null && !smtpUsername.isEmpty()) { email.setAuthentication(smtpUsername, smtpPassword); } if(security!= null){ if(security.equalsIgnoreCase("SSL") ){ email.setSSL(true); }else if(security.equalsIgnoreCase("TLS")){ email.setTLS(true); } } if (cc != null && cc.length() != 0) { Collection<String> ccs = AppUtil.getEmailList(null, cc, wfAssignment, appDef); for (String address : ccs) { email.addCc(address); } } final String fromStr = WorkflowUtil.processVariable(from, formDataTable, wfAssignment); email.setFrom(fromStr); email.setSubject(emailSubject); email.setCharset("UTF-8"); if ("true".equalsIgnoreCase(isHtml)) { email.setHtmlMsg(emailMessage); } else { email.setMsg(emailMessage); } String emailToOutput = ""; if ((toParticipantId != null && toParticipantId.trim().length() != 0) || (toSpecific != null && toSpecific.trim().length() != 0)) { Collection<String> tss = AppUtil.getEmailList(toParticipantId, toSpecific, wfAssignment, appDef); for (String address : tss) { email.addTo(address); emailToOutput += address + ", "; } } else { throw new PluginException("no email specified"); } final String to = emailToOutput; final String profile = DynamicDataSourceManager.getCurrentProfile(); //handle file attachment String formDefId = (String) properties.get("formDefId"); Object[] fields = null; if (properties.get("fields") instanceof Object[]){ fields = (Object[]) properties.get("fields"); } if (formDefId != null && !formDefId.isEmpty() && fields != null && fields.length > 0) { AppService appService = (AppService) AppUtil.getApplicationContext().getBean("appService"); FormData formData = new FormData(); String primaryKey = appService.getOriginProcessId(wfAssignment.getProcessId()); formData.setPrimaryKeyValue(primaryKey); Form loadForm = appService.viewDataForm(appDef.getId(), appDef.getVersion().toString(), formDefId, null, null, null, formData, null, null); for (Object o : fields) { Map mapping = (HashMap) o; String fieldId = mapping.get("field").toString(); try { Element el = FormUtil.findElement(fieldId, loadForm, formData); String value = FormUtil.getElementPropertyValue(el, formData); if (value != null && !value.isEmpty()) { File file = FileUtil.getFile(value, loadForm, primaryKey); if (file != null) { FileDataSource fds = new FileDataSource(file); email.attach(fds, MimeUtility.encodeText(file.getName()), ""); } } } catch(Exception e){ LogUtil.info("EmailTool", "Attached file fail from field \"" + fieldId + "\" in form \"" + formDefId + "\""); } } } Object[] files = null; if (properties.get("files") instanceof Object[]){ files = (Object[]) properties.get("files"); } if (files != null && files.length > 0) { for (Object o : files) { Map mapping = (HashMap) o; String path = mapping.get("path").toString(); String fileName = mapping.get("fileName").toString(); String type = mapping.get("type").toString(); try { if ("system".equals(type)) { EmailAttachment attachment = new EmailAttachment(); attachment.setPath(path); attachment.setName(MimeUtility.encodeText(fileName)); email.attach(attachment); } else { URL u = new URL(path); - email.attach(u, fileName, ""); + email.attach(u, MimeUtility.encodeText(fileName), ""); } } catch(Exception e){ LogUtil.info("EmailTool", "Attached file fail from path \"" + path + "\""); e.printStackTrace(); } } } Thread emailThread = new Thread(new Runnable() { public void run() { try { HostManager.setCurrentProfile(profile); LogUtil.info(getClass().getName(), "EmailTool: Sending email from=" + fromStr + ", to=" + to + "cc=" + cc + ", subject=" + email.getSubject()); email.send(); LogUtil.info(getClass().getName(), "EmailTool: Sending email completed for subject=" + email.getSubject()); } catch (EmailException ex) { LogUtil.error(getClass().getName(), ex, ""); } } }); emailThread.setDaemon(true); emailThread.start(); } catch (Exception e) { LogUtil.error(getClass().getName(), e, ""); } return null; } public String getLabel() { return "Email Tool"; } public String getClassName() { return getClass().getName(); } public String getPropertyOptions() { return AppUtil.readPluginResource(getClass().getName(), "/properties/app/emailTool.json", null, true, null); } }
true
true
public Object execute(Map properties) { PluginManager pluginManager = (PluginManager) properties.get("pluginManager"); String formDataTable = (String) properties.get("formDataTable"); String smtpHost = (String) properties.get("host"); String smtpPort = (String) properties.get("port"); String smtpUsername = (String) properties.get("username"); String smtpPassword = (String) properties.get("password"); String security = (String) properties.get("security"); final String from = (String) properties.get("from"); final String cc = (String) properties.get("cc"); String toParticipantId = (String) properties.get("toParticipantId"); String toSpecific = (String) properties.get("toSpecific"); String emailSubject = (String) properties.get("subject"); String emailMessage = (String) properties.get("message"); String isHtml = (String) properties.get("isHtml"); WorkflowAssignment wfAssignment = (WorkflowAssignment) properties.get("workflowAssignment"); AppDefinition appDef = (AppDefinition) properties.get("appDef"); try { Map<String, String> replaceMap = null; if ("true".equalsIgnoreCase(isHtml)) { replaceMap = new HashMap<String, String>(); replaceMap.put("\\n", "<br/>"); } emailSubject = WorkflowUtil.processVariable(emailSubject, formDataTable, wfAssignment); emailMessage = AppUtil.processHashVariable(emailMessage, wfAssignment, null, replaceMap); smtpHost = AppUtil.processHashVariable(smtpHost, wfAssignment, null, null); smtpPort = AppUtil.processHashVariable(smtpPort, wfAssignment, null, null); smtpUsername = AppUtil.processHashVariable(smtpUsername, wfAssignment, null, null); smtpPassword = AppUtil.processHashVariable(smtpPassword, wfAssignment, null, null); security = AppUtil.processHashVariable(security, wfAssignment, null, null); // create the email message final HtmlEmail email = new HtmlEmail(); email.setHostName(smtpHost); if (smtpPort != null && smtpPort.length() != 0) { email.setSmtpPort(Integer.parseInt(smtpPort)); } if (smtpUsername != null && !smtpUsername.isEmpty()) { email.setAuthentication(smtpUsername, smtpPassword); } if(security!= null){ if(security.equalsIgnoreCase("SSL") ){ email.setSSL(true); }else if(security.equalsIgnoreCase("TLS")){ email.setTLS(true); } } if (cc != null && cc.length() != 0) { Collection<String> ccs = AppUtil.getEmailList(null, cc, wfAssignment, appDef); for (String address : ccs) { email.addCc(address); } } final String fromStr = WorkflowUtil.processVariable(from, formDataTable, wfAssignment); email.setFrom(fromStr); email.setSubject(emailSubject); email.setCharset("UTF-8"); if ("true".equalsIgnoreCase(isHtml)) { email.setHtmlMsg(emailMessage); } else { email.setMsg(emailMessage); } String emailToOutput = ""; if ((toParticipantId != null && toParticipantId.trim().length() != 0) || (toSpecific != null && toSpecific.trim().length() != 0)) { Collection<String> tss = AppUtil.getEmailList(toParticipantId, toSpecific, wfAssignment, appDef); for (String address : tss) { email.addTo(address); emailToOutput += address + ", "; } } else { throw new PluginException("no email specified"); } final String to = emailToOutput; final String profile = DynamicDataSourceManager.getCurrentProfile(); //handle file attachment String formDefId = (String) properties.get("formDefId"); Object[] fields = null; if (properties.get("fields") instanceof Object[]){ fields = (Object[]) properties.get("fields"); } if (formDefId != null && !formDefId.isEmpty() && fields != null && fields.length > 0) { AppService appService = (AppService) AppUtil.getApplicationContext().getBean("appService"); FormData formData = new FormData(); String primaryKey = appService.getOriginProcessId(wfAssignment.getProcessId()); formData.setPrimaryKeyValue(primaryKey); Form loadForm = appService.viewDataForm(appDef.getId(), appDef.getVersion().toString(), formDefId, null, null, null, formData, null, null); for (Object o : fields) { Map mapping = (HashMap) o; String fieldId = mapping.get("field").toString(); try { Element el = FormUtil.findElement(fieldId, loadForm, formData); String value = FormUtil.getElementPropertyValue(el, formData); if (value != null && !value.isEmpty()) { File file = FileUtil.getFile(value, loadForm, primaryKey); if (file != null) { FileDataSource fds = new FileDataSource(file); email.attach(fds, MimeUtility.encodeText(file.getName()), ""); } } } catch(Exception e){ LogUtil.info("EmailTool", "Attached file fail from field \"" + fieldId + "\" in form \"" + formDefId + "\""); } } } Object[] files = null; if (properties.get("files") instanceof Object[]){ files = (Object[]) properties.get("files"); } if (files != null && files.length > 0) { for (Object o : files) { Map mapping = (HashMap) o; String path = mapping.get("path").toString(); String fileName = mapping.get("fileName").toString(); String type = mapping.get("type").toString(); try { if ("system".equals(type)) { EmailAttachment attachment = new EmailAttachment(); attachment.setPath(path); attachment.setName(MimeUtility.encodeText(fileName)); email.attach(attachment); } else { URL u = new URL(path); email.attach(u, fileName, ""); } } catch(Exception e){ LogUtil.info("EmailTool", "Attached file fail from path \"" + path + "\""); e.printStackTrace(); } } } Thread emailThread = new Thread(new Runnable() { public void run() { try { HostManager.setCurrentProfile(profile); LogUtil.info(getClass().getName(), "EmailTool: Sending email from=" + fromStr + ", to=" + to + "cc=" + cc + ", subject=" + email.getSubject()); email.send(); LogUtil.info(getClass().getName(), "EmailTool: Sending email completed for subject=" + email.getSubject()); } catch (EmailException ex) { LogUtil.error(getClass().getName(), ex, ""); } } }); emailThread.setDaemon(true); emailThread.start(); } catch (Exception e) { LogUtil.error(getClass().getName(), e, ""); } return null; }
public Object execute(Map properties) { PluginManager pluginManager = (PluginManager) properties.get("pluginManager"); String formDataTable = (String) properties.get("formDataTable"); String smtpHost = (String) properties.get("host"); String smtpPort = (String) properties.get("port"); String smtpUsername = (String) properties.get("username"); String smtpPassword = (String) properties.get("password"); String security = (String) properties.get("security"); final String from = (String) properties.get("from"); final String cc = (String) properties.get("cc"); String toParticipantId = (String) properties.get("toParticipantId"); String toSpecific = (String) properties.get("toSpecific"); String emailSubject = (String) properties.get("subject"); String emailMessage = (String) properties.get("message"); String isHtml = (String) properties.get("isHtml"); WorkflowAssignment wfAssignment = (WorkflowAssignment) properties.get("workflowAssignment"); AppDefinition appDef = (AppDefinition) properties.get("appDef"); try { Map<String, String> replaceMap = null; if ("true".equalsIgnoreCase(isHtml)) { replaceMap = new HashMap<String, String>(); replaceMap.put("\\n", "<br/>"); } emailSubject = WorkflowUtil.processVariable(emailSubject, formDataTable, wfAssignment); emailMessage = AppUtil.processHashVariable(emailMessage, wfAssignment, null, replaceMap); smtpHost = AppUtil.processHashVariable(smtpHost, wfAssignment, null, null); smtpPort = AppUtil.processHashVariable(smtpPort, wfAssignment, null, null); smtpUsername = AppUtil.processHashVariable(smtpUsername, wfAssignment, null, null); smtpPassword = AppUtil.processHashVariable(smtpPassword, wfAssignment, null, null); security = AppUtil.processHashVariable(security, wfAssignment, null, null); // create the email message final HtmlEmail email = new HtmlEmail(); email.setHostName(smtpHost); if (smtpPort != null && smtpPort.length() != 0) { email.setSmtpPort(Integer.parseInt(smtpPort)); } if (smtpUsername != null && !smtpUsername.isEmpty()) { email.setAuthentication(smtpUsername, smtpPassword); } if(security!= null){ if(security.equalsIgnoreCase("SSL") ){ email.setSSL(true); }else if(security.equalsIgnoreCase("TLS")){ email.setTLS(true); } } if (cc != null && cc.length() != 0) { Collection<String> ccs = AppUtil.getEmailList(null, cc, wfAssignment, appDef); for (String address : ccs) { email.addCc(address); } } final String fromStr = WorkflowUtil.processVariable(from, formDataTable, wfAssignment); email.setFrom(fromStr); email.setSubject(emailSubject); email.setCharset("UTF-8"); if ("true".equalsIgnoreCase(isHtml)) { email.setHtmlMsg(emailMessage); } else { email.setMsg(emailMessage); } String emailToOutput = ""; if ((toParticipantId != null && toParticipantId.trim().length() != 0) || (toSpecific != null && toSpecific.trim().length() != 0)) { Collection<String> tss = AppUtil.getEmailList(toParticipantId, toSpecific, wfAssignment, appDef); for (String address : tss) { email.addTo(address); emailToOutput += address + ", "; } } else { throw new PluginException("no email specified"); } final String to = emailToOutput; final String profile = DynamicDataSourceManager.getCurrentProfile(); //handle file attachment String formDefId = (String) properties.get("formDefId"); Object[] fields = null; if (properties.get("fields") instanceof Object[]){ fields = (Object[]) properties.get("fields"); } if (formDefId != null && !formDefId.isEmpty() && fields != null && fields.length > 0) { AppService appService = (AppService) AppUtil.getApplicationContext().getBean("appService"); FormData formData = new FormData(); String primaryKey = appService.getOriginProcessId(wfAssignment.getProcessId()); formData.setPrimaryKeyValue(primaryKey); Form loadForm = appService.viewDataForm(appDef.getId(), appDef.getVersion().toString(), formDefId, null, null, null, formData, null, null); for (Object o : fields) { Map mapping = (HashMap) o; String fieldId = mapping.get("field").toString(); try { Element el = FormUtil.findElement(fieldId, loadForm, formData); String value = FormUtil.getElementPropertyValue(el, formData); if (value != null && !value.isEmpty()) { File file = FileUtil.getFile(value, loadForm, primaryKey); if (file != null) { FileDataSource fds = new FileDataSource(file); email.attach(fds, MimeUtility.encodeText(file.getName()), ""); } } } catch(Exception e){ LogUtil.info("EmailTool", "Attached file fail from field \"" + fieldId + "\" in form \"" + formDefId + "\""); } } } Object[] files = null; if (properties.get("files") instanceof Object[]){ files = (Object[]) properties.get("files"); } if (files != null && files.length > 0) { for (Object o : files) { Map mapping = (HashMap) o; String path = mapping.get("path").toString(); String fileName = mapping.get("fileName").toString(); String type = mapping.get("type").toString(); try { if ("system".equals(type)) { EmailAttachment attachment = new EmailAttachment(); attachment.setPath(path); attachment.setName(MimeUtility.encodeText(fileName)); email.attach(attachment); } else { URL u = new URL(path); email.attach(u, MimeUtility.encodeText(fileName), ""); } } catch(Exception e){ LogUtil.info("EmailTool", "Attached file fail from path \"" + path + "\""); e.printStackTrace(); } } } Thread emailThread = new Thread(new Runnable() { public void run() { try { HostManager.setCurrentProfile(profile); LogUtil.info(getClass().getName(), "EmailTool: Sending email from=" + fromStr + ", to=" + to + "cc=" + cc + ", subject=" + email.getSubject()); email.send(); LogUtil.info(getClass().getName(), "EmailTool: Sending email completed for subject=" + email.getSubject()); } catch (EmailException ex) { LogUtil.error(getClass().getName(), ex, ""); } } }); emailThread.setDaemon(true); emailThread.start(); } catch (Exception e) { LogUtil.error(getClass().getName(), e, ""); } return null; }
diff --git a/src/com/jme/scene/batch/SharedBatch.java b/src/com/jme/scene/batch/SharedBatch.java index fc2398aab..04a77e244 100755 --- a/src/com/jme/scene/batch/SharedBatch.java +++ b/src/com/jme/scene/batch/SharedBatch.java @@ -1,455 +1,455 @@ /* * Copyright (c) 2003-2006 jMonkeyEngine * 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 'jMonkeyEngine' 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.jme.scene.batch; import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.logging.Level; import com.jme.bounding.BoundingVolume; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.SceneElement; import com.jme.scene.VBOInfo; import com.jme.scene.state.RenderState; import com.jme.util.LoggingSystem; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; /** * <code>SharedBatch</code> allows the sharing of data between multiple nodes. * A provided TriMesh is used as the model for this node. This allows the user * to place multiple copies of the same object throughout the scene without * having to duplicate data. It should be known that any change to the provided * target mesh will affect the appearance of this mesh, including animations. * Secondly, the SharedBatch is read only. Any attempt to write to the mesh data * via set* methods, will result in a warning being logged and nothing else. Any * changes to the mesh should happened to the target mesh being shared. * <br> * If you plan to use collisions with a <code>SharedBatch</code> it is * recommended that you disable passing of <code>updateCollisionTree</code> * calls to the target mesh. This is to prevent multiple calls to the target's * <code>updateCollisionTree</code> method, from different shared meshes. * Instead of this method being called from the scenegraph, you can now invoke it * directly on the target mesh, thus ensuring it will only be invoked once. * <br> * <b>Important:</b> It is highly recommended that the Target mesh is NOT * placed into the scenegraph, as it's translation, rotation and scale are * replaced by the shared meshes using it before they are rendered. <br> * <b>Note:</b> Special thanks to Kevin Glass. * * @author Mark Powell * @version $id$ */ public class SharedBatch extends TriangleBatch { private static final long serialVersionUID = 1L; private TriangleBatch target; private boolean updatesCollisionTree; public SharedBatch() { super(); } public SharedBatch(TriangleBatch target) { super(); if((target.getType() & SceneElement.SHAREDBATCH) != 0) { setTarget(((SharedBatch)target).getTarget()); } else { setTarget(target); } } public int getType() { return super.getType() | SceneElement.SHAREDBATCH; } /** * <code>setTarget</code> sets the shared data mesh. * * @param target * the TriMesh to share the data. */ public void setTarget(TriangleBatch target) { this.target = target; for (int i = 0; i < RenderState.RS_MAX_STATE; i++) { RenderState renderState = this.target.getRenderState( i ); if (renderState != null) { setRenderState(renderState ); } } setCullMode(target.getLocalCullMode()); setLightCombineMode(target.getLocalLightCombineMode()); setRenderQueueMode(target.getLocalRenderQueueMode()); setTextureCombineMode(target.getLocalTextureCombineMode()); setZOrder(target.getZOrder()); } /** * <code>getTarget</code> returns the mesh that is being shared by * this object. * @return the mesh being shared. */ public TriangleBatch getTarget() { return target; } /** * <code>reconstruct</code> is not supported in SharedBatch. * * @param vertices * the new vertices to use. * @param normals * the new normals to use. * @param colors * the new colors to use. * @param textureCoords * the new texture coordinates to use (position 0). */ public void reconstruct(FloatBuffer vertices, FloatBuffer normals, FloatBuffer colors, FloatBuffer textureCoords) { LoggingSystem.getLogger().log(Level.INFO, "SharedBatch will ignore reconstruct."); } /** * <code>setVBOInfo</code> is not supported in SharedBatch. */ public void setVBOInfo(VBOInfo info) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>getVBOInfo</code> returns the target mesh's vbo info. */ public VBOInfo getVBOInfo() { return target.getVBOInfo(); } /** * * <code>setSolidColor</code> is not supported by SharedBatch. * * @param color * the color to set. */ public void setSolidColor(ColorRGBA color) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>setRandomColors</code> is not supported by SharedBatch. */ public void setRandomColors() { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>getVertexBuffer</code> returns the float buffer that * contains the target geometry's vertex information. * * @return the float buffer that contains the target geometry's vertex * information. */ public FloatBuffer getVertexBuffer() { return target.getVertexBuffer(); } /** * <code>setVertexBuffer</code> is not supported by SharedBatch. * * @param buff * the new vertex buffer. */ public void setVertexBuffer(FloatBuffer buff) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>getNormalBuffer</code> retrieves the target geometry's normal * information as a float buffer. * * @return the float buffer containing the target geometry information. */ public FloatBuffer getNormalBuffer() { return target.getNormalBuffer(); } /** * <code>setNormalBuffer</code> is not supported by SharedBatch. * * @param buff * the new normal buffer. */ public void setNormalBuffer(FloatBuffer buff) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>getColorBuffer</code> retrieves the float buffer that * contains the target geometry's color information. * * @return the buffer that contains the target geometry's color information. */ public FloatBuffer getColorBuffer() { return target.getColorBuffer(); } /** * <code>setColorBuffer</code> is not supported by SharedBatch. * * @param buff * the new color buffer. */ public void setColorBuffer( FloatBuffer buff) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * * <code>getIndexAsBuffer</code> retrieves the target's indices array as an * <code>IntBuffer</code>. * * @return the indices array as an <code>IntBuffer</code>. */ public IntBuffer getIndexBuffer() { return target.getIndexBuffer(); } /** * * <code>setIndexBuffer</code> is not supported by SharedBatch. * * @param indices * the index array as an IntBuffer. */ public void setIndexBuffer( IntBuffer indices) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } public int getVertexCount() { return target.getVertexCount(); } /** * Returns the number of triangles the target TriMesh contains. * * @return The current number of triangles. */ public int getTriangleCount() { return target.getTriangleCount(); } public void getTriangle(int index, int[] storage) { target.getTriangle(index, storage); } /** * * <code>copyTextureCoords</code> is not supported by SharedBatch. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. */ public void copyTextureCoords( int fromIndex, int toIndex) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>getTextureBuffers</code> retrieves the target geometry's texture * information contained within a float buffer array. * * @return the float buffers that contain the target geometry's texture * information. */ public ArrayList<FloatBuffer> getTextureBuffers() { return target.getTextureBuffers(); } /** * * <code>getTextureAsFloatBuffer</code> retrieves the texture buffer of a * given texture unit. * * @param textureUnit * the texture unit to check. * @return the texture coordinates at the given texture unit. */ public FloatBuffer getTextureBuffer(int textureUnit) { return target.getTextureBuffer(textureUnit); } /** * <code>setTextureBuffer</code> is not supported by SharedBatch. * * @param buff * the new vertex buffer. */ public void setTextureBuffer( FloatBuffer buff) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>setTextureBuffer</code> not supported by SharedBatch * * @param buff * the new vertex buffer. */ public void setTextureBuffer( FloatBuffer buff, int position) { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * clearBuffers is not supported by SharedBatch */ public void clearBuffers() { LoggingSystem.getLogger().log(Level.WARNING, "SharedBatch does not allow the manipulation" + "of the the mesh data."); } /** * <code>updateWorldBound</code> updates the bounding volume that contains * this geometry. The location of the geometry is based on the location of * all this node's parents. * * @see com.jme.scene.Spatial#updateWorldBound() */ public void updateWorldBound() { if (target.getModelBound() != null) { worldBound = target.getModelBound().transform(parentGeom.getWorldRotation(), parentGeom.getWorldTranslation(), parentGeom.getWorldScale(), worldBound); } } /** * <code>updateBound</code> recalculates the bounding object assigned to * the geometry. This resets it parameters to adjust for any changes to the * vertex information. * */ public void updateModelBound() { if (target.getModelBound() != null) { target.updateModelBound(); updateWorldBound(); } } /** * returns the model bound of the target object. */ public BoundingVolume getModelBound() { return target.getModelBound(); } /** * draw renders the target mesh, at the translation, rotation and scale of * this shared mesh. * * @see com.jme.scene.Spatial#draw(com.jme.renderer.Renderer) */ public void draw(Renderer r) { if (!r.isProcessingQueue()) { if (r.checkAndAdd(this)) return; } - target.parentGeom.setLocalTranslation(parentGeom.getWorldTranslation()); - target.parentGeom.setLocalRotation(parentGeom.getWorldRotation()); - target.parentGeom.setLocalScale(parentGeom.getWorldScale()); + target.parentGeom.getWorldTranslation().set(parentGeom.getWorldTranslation()); + target.parentGeom.getWorldRotation().set(parentGeom.getWorldRotation()); + target.parentGeom.getWorldScale().set(parentGeom.getWorldScale()); target.setDefaultColor(getDefaultColor()); for(int i = 0; i < states.length; i++) { target.states[i] = this.states[i]; } r.draw(target); } /** * <code>getUpdatesCollisionTree</code> returns wether calls to * <code>updateCollisionTree</code> will be passed to the target mesh. * * @return true if these method calls are forwared. */ public boolean getUpdatesCollisionTree() { return updatesCollisionTree; } /** * code>setUpdatesCollisionTree</code> sets wether calls to * <code>updateCollisionTree</code> are passed to the target mesh. * * @param updatesCollisionTree * true to enable. */ public void setUpdatesCollisionTree(boolean updatesCollisionTree) { this.updatesCollisionTree = updatesCollisionTree; } public void write(JMEExporter e) throws IOException { OutputCapsule capsule = e.getCapsule(this); capsule.write(target, "target", null); capsule.write(updatesCollisionTree, "updatesCollisionTree", false); super.write(e); } public void read(JMEImporter e) throws IOException { InputCapsule capsule = e.getCapsule(this); target = (TriangleBatch)capsule.readSavable("target", null); updatesCollisionTree = capsule.readBoolean("updatesCollisionTree", false); super.read(e); } @Override public void lockMeshes(Renderer r) { target.lockMeshes(r); } }
true
true
public void draw(Renderer r) { if (!r.isProcessingQueue()) { if (r.checkAndAdd(this)) return; } target.parentGeom.setLocalTranslation(parentGeom.getWorldTranslation()); target.parentGeom.setLocalRotation(parentGeom.getWorldRotation()); target.parentGeom.setLocalScale(parentGeom.getWorldScale()); target.setDefaultColor(getDefaultColor()); for(int i = 0; i < states.length; i++) { target.states[i] = this.states[i]; } r.draw(target); }
public void draw(Renderer r) { if (!r.isProcessingQueue()) { if (r.checkAndAdd(this)) return; } target.parentGeom.getWorldTranslation().set(parentGeom.getWorldTranslation()); target.parentGeom.getWorldRotation().set(parentGeom.getWorldRotation()); target.parentGeom.getWorldScale().set(parentGeom.getWorldScale()); target.setDefaultColor(getDefaultColor()); for(int i = 0; i < states.length; i++) { target.states[i] = this.states[i]; } r.draw(target); }
diff --git a/src/edu/berkeley/cs162/KVClient.java b/src/edu/berkeley/cs162/KVClient.java index 48b171e..75767a9 100644 --- a/src/edu/berkeley/cs162/KVClient.java +++ b/src/edu/berkeley/cs162/KVClient.java @@ -1,188 +1,188 @@ /** * Client component for generating load for the KeyValue store. * This is also used by the Master server to reach the slave nodes. * * @author Mosharaf Chowdhury (http://www.mosharaf.com) * @author Prashanth Mohan (http://www.cs.berkeley.edu/~prmohan) * * Copyright (c) 2012, University of California at Berkeley * 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 University of California, Berkeley 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 AUTHORS 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 edu.berkeley.cs162; package edu.berkeley.cs162; import java.net.Socket; /** Part II */ import edu.berkeley.cs162.KVMessage; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; /** Part II END */ /** * This class is used to communicate with (appropriately marshalling and unmarshalling) * objects implementing the {@link KeyValueInterface}. * * @param <K> Java Generic type for the Key * @param <V> Java Generic type for the Value */ public class KVClient implements KeyValueInterface { //Fields private String server = null; private int port = 0; //Constructor /** * @param server is the DNS reference to the Key-Value server * @param port is the port on which the Key-Value server is listening */ public KVClient(String server, int port) { this.server = server; this.port = port; } //Helper Methods public String getServer() { return this.server; } public int getPort() { return this.port; } //Action Methods /** Part II */ private Socket connectHost() throws KVException { Socket socket; try { socket = new Socket(this.server, this.port); } catch (Exception e) { throw new KVException(new KVMessage("resp", "Network Error: Could not create socket")); } return socket; } private void closeHost(Socket sock) throws KVException { try { sock.close(); } catch (Exception e) { throw new KVException(new KVMessage("resp", "Unknown Error: Could not close socket")); } } public void put(String key, String value) throws KVException { if (key.length() > 256) throw new KVException(new KVMessage("resp", "Oversized key")); if (value.length() > 256*1024) throw new KVException(new KVMessage("resp", "Oversized value")); Socket socket = connectHost(); KVMessage request = null; KVMessage response = null; InputStream is = null; request = new KVMessage("putreq"); request.setKey(key); request.setValue(value); request.sendMessage(socket); try { is = socket.getInputStream(); } catch (IOException e){ throw new KVException(new KVMessage("resp", "Network Error: Could not receive data")); } response = new KVMessage(is); if (response.getMessage().equals("Success")) { closeHost(socket); } - //throw new KVException(response); + throw new KVException(response); } public String get(String key) throws KVException { if (key.length() > 256) throw new KVException(new KVMessage("resp", "Oversized key")); Socket socket = connectHost(); String value = null; KVMessage request = null; KVMessage response = null; InputStream is = null; request = new KVMessage("getreq"); request.setKey(key); request.sendMessage(socket); try { is = socket.getInputStream(); } catch (IOException e) { throw new KVException(new KVMessage("resp", "Network Error: Could not receive data")); } response = new KVMessage(is); value = response.getValue(); if (value != null) { closeHost(socket); return value; } throw new KVException(response); } public void del(String key) throws KVException { if (key.length() > 256) throw new KVException(new KVMessage("resp", "Oversized value")); Socket socket = connectHost(); KVMessage request = null; KVMessage response = null; InputStream is = null; request = new KVMessage("delreq"); request.setKey(key); request.sendMessage(socket); try { is = socket.getInputStream(); } catch (IOException e) { throw new KVException(new KVMessage("resp", "Network Error: Could not receive data")); } response = new KVMessage(is); if (response.getMessage().equals("Success")) { closeHost(socket); return; } throw new KVException(response); } /** Part II END */ }
true
true
public void put(String key, String value) throws KVException { if (key.length() > 256) throw new KVException(new KVMessage("resp", "Oversized key")); if (value.length() > 256*1024) throw new KVException(new KVMessage("resp", "Oversized value")); Socket socket = connectHost(); KVMessage request = null; KVMessage response = null; InputStream is = null; request = new KVMessage("putreq"); request.setKey(key); request.setValue(value); request.sendMessage(socket); try { is = socket.getInputStream(); } catch (IOException e){ throw new KVException(new KVMessage("resp", "Network Error: Could not receive data")); } response = new KVMessage(is); if (response.getMessage().equals("Success")) { closeHost(socket); } //throw new KVException(response); }
public void put(String key, String value) throws KVException { if (key.length() > 256) throw new KVException(new KVMessage("resp", "Oversized key")); if (value.length() > 256*1024) throw new KVException(new KVMessage("resp", "Oversized value")); Socket socket = connectHost(); KVMessage request = null; KVMessage response = null; InputStream is = null; request = new KVMessage("putreq"); request.setKey(key); request.setValue(value); request.sendMessage(socket); try { is = socket.getInputStream(); } catch (IOException e){ throw new KVException(new KVMessage("resp", "Network Error: Could not receive data")); } response = new KVMessage(is); if (response.getMessage().equals("Success")) { closeHost(socket); } throw new KVException(response); }
diff --git a/graphe-mobile/src/com/utc/graphemobile/element/LeftMenu.java b/graphe-mobile/src/com/utc/graphemobile/element/LeftMenu.java index fb59f08..04adc14 100644 --- a/graphe-mobile/src/com/utc/graphemobile/element/LeftMenu.java +++ b/graphe-mobile/src/com/utc/graphemobile/element/LeftMenu.java @@ -1,134 +1,134 @@ package com.utc.graphemobile.element; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.utc.graphemobile.input.ShowLeftMenuEventListener; import com.utc.graphemobile.input.UIEventListener; import com.utc.graphemobile.screen.IGrapheScreen; import com.utc.graphemobile.utils.Utils; public class LeftMenu extends Table { public static final float WIDTH = 200; public static final float PADDING = 10; public static final float CLOSE_SIZE = 50; private Image img; private IGrapheScreen screen = null; private Table table; public LeftMenu(IGrapheScreen screen) { this.screen = screen; this.table = new Table(); UIEventListener listener = new UIEventListener(screen); this.top().left(); table.top().left(); TextureRegion deleteTR = screen.getSkin().getRegion("seeMore"); img = new Image(deleteTR); img.setHeight(Utils.toDp(CLOSE_SIZE)); img.setWidth(Utils.toDp(CLOSE_SIZE)); img.setPosition(Utils.toDp(WIDTH), Gdx.graphics.getHeight() - img.getHeight()); img.addListener(new ShowLeftMenuEventListener(this)); this.addActor(img); TextButton bt = new TextButton("open", "Open", screen.getSkin() .getRegion("open"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("center", "Center", screen.getSkin().getRegion( "center"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); - bt = new TextButton("spatial", "Spatialisation", screen.getSkin() + bt = new TextButton("spatial", "Spatialization", screen.getSkin() .getRegion("spatial"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("label", "Label", screen.getSkin().getRegion( "label"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("edit", "Normal", screen.getSkin().getRegion("edit"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("edge", "Type edge", screen.getSkin().getRegion( "edge"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("about", "About", screen.getSkin().getRegion( "about"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); this.setWidth(Utils.toDp(WIDTH)); this.setHeight(Gdx.graphics.getHeight()); setBackground(screen.getSkin().getDrawable("gray-pixel")); this.setX(Utils.toDp(-WIDTH)); table.setX(Utils.toDp(-WIDTH)); this.add(table); } public void onResize() { setHeight(Gdx.graphics.getHeight()); invalidate(); img.setY(getHeight() - img.getHeight()); } public boolean pan(float x, float y, float deltaX, float deltaY) { if(this.getHeight() > table.getHeight()) return true; table.setY(table.getY() - deltaY); return false; } public boolean containsX(float x) { return this.getX() < x && this.getX() + this.getWidth() > x; } public boolean containsY(float y) { return this.getY() < y && this.getY() + this.getHeight() > y; } public boolean contains(float x, float y) { return containsX(x) && containsY(y); } public boolean fling(float velocityX, float velocityY, int button) { if(this.getHeight() > table.getHeight()) return true; if(velocityY > 0) { table.addAction(Actions.moveTo(table.getX(), this.getHeight() - table.getHeight(), (float)(0.4f + Math.log10(velocityY) / 10), Interpolation.fade)); } else if(velocityY != 0) { table.addAction(Actions.moveTo(table.getX(), 0, (float)(0.4f + Math.log10(-velocityY) / 10), Interpolation.fade)); } return false; } }
true
true
public LeftMenu(IGrapheScreen screen) { this.screen = screen; this.table = new Table(); UIEventListener listener = new UIEventListener(screen); this.top().left(); table.top().left(); TextureRegion deleteTR = screen.getSkin().getRegion("seeMore"); img = new Image(deleteTR); img.setHeight(Utils.toDp(CLOSE_SIZE)); img.setWidth(Utils.toDp(CLOSE_SIZE)); img.setPosition(Utils.toDp(WIDTH), Gdx.graphics.getHeight() - img.getHeight()); img.addListener(new ShowLeftMenuEventListener(this)); this.addActor(img); TextButton bt = new TextButton("open", "Open", screen.getSkin() .getRegion("open"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("center", "Center", screen.getSkin().getRegion( "center"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("spatial", "Spatialisation", screen.getSkin() .getRegion("spatial"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("label", "Label", screen.getSkin().getRegion( "label"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("edit", "Normal", screen.getSkin().getRegion("edit"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("edge", "Type edge", screen.getSkin().getRegion( "edge"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("about", "About", screen.getSkin().getRegion( "about"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); this.setWidth(Utils.toDp(WIDTH)); this.setHeight(Gdx.graphics.getHeight()); setBackground(screen.getSkin().getDrawable("gray-pixel")); this.setX(Utils.toDp(-WIDTH)); table.setX(Utils.toDp(-WIDTH)); this.add(table); }
public LeftMenu(IGrapheScreen screen) { this.screen = screen; this.table = new Table(); UIEventListener listener = new UIEventListener(screen); this.top().left(); table.top().left(); TextureRegion deleteTR = screen.getSkin().getRegion("seeMore"); img = new Image(deleteTR); img.setHeight(Utils.toDp(CLOSE_SIZE)); img.setWidth(Utils.toDp(CLOSE_SIZE)); img.setPosition(Utils.toDp(WIDTH), Gdx.graphics.getHeight() - img.getHeight()); img.addListener(new ShowLeftMenuEventListener(this)); this.addActor(img); TextButton bt = new TextButton("open", "Open", screen.getSkin() .getRegion("open"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("center", "Center", screen.getSkin().getRegion( "center"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("spatial", "Spatialization", screen.getSkin() .getRegion("spatial"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("label", "Label", screen.getSkin().getRegion( "label"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("edit", "Normal", screen.getSkin().getRegion("edit"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("edge", "Type edge", screen.getSkin().getRegion( "edge"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); table.row(); bt = new TextButton("about", "About", screen.getSkin().getRegion( "about"), screen.getSkin()); bt.addListener(listener); table.add(bt).pad(Utils.toDp(PADDING)).left() .width(Utils.toDp(WIDTH - PADDING * 2)); this.setWidth(Utils.toDp(WIDTH)); this.setHeight(Gdx.graphics.getHeight()); setBackground(screen.getSkin().getDrawable("gray-pixel")); this.setX(Utils.toDp(-WIDTH)); table.setX(Utils.toDp(-WIDTH)); this.add(table); }
diff --git a/plugins/org.eclipse.recommenders.rcp/src/org/eclipse/recommenders/internal/rcp/wiring/RecommendersModule.java b/plugins/org.eclipse.recommenders.rcp/src/org/eclipse/recommenders/internal/rcp/wiring/RecommendersModule.java index 041d2a66b..d45dc96f6 100644 --- a/plugins/org.eclipse.recommenders.rcp/src/org/eclipse/recommenders/internal/rcp/wiring/RecommendersModule.java +++ b/plugins/org.eclipse.recommenders.rcp/src/org/eclipse/recommenders/internal/rcp/wiring/RecommendersModule.java @@ -1,206 +1,206 @@ /** * Copyright (c) 2010 Darmstadt University of Technology. * 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: * Marcel Bruch - initial API and implementation. */ package org.eclipse.recommenders.internal.rcp.wiring; import static java.lang.Thread.MIN_PRIORITY; import static org.eclipse.recommenders.utils.Checks.ensureIsNotNull; import static org.eclipse.recommenders.utils.Executors.coreThreadsTimoutExecutor; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.core.JavaModelManager; import org.eclipse.recommenders.internal.rcp.providers.CachingAstProvider; import org.eclipse.recommenders.internal.rcp.providers.JavaModelEventsProvider; import org.eclipse.recommenders.internal.rcp.providers.JavaSelectionProvider; import org.eclipse.recommenders.rcp.IAstProvider; import org.eclipse.recommenders.rcp.RecommendersPlugin; import org.eclipse.recommenders.utils.rcp.JavaElementResolver; import org.eclipse.recommenders.utils.rcp.ast.ASTNodeUtils; import org.eclipse.recommenders.utils.rcp.ast.ASTStringUtils; import org.eclipse.recommenders.utils.rcp.ast.BindingUtils; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.ISelectionService; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.UIJob; import com.google.common.eventbus.AsyncEventBus; import com.google.common.eventbus.EventBus; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.Scopes; @SuppressWarnings("restriction") public class RecommendersModule extends AbstractModule implements Module { @Override protected void configure() { configureJavaElementResolver(); configureAstProvider(); initalizeSingletonServices(); } private void configureJavaElementResolver() { bind(JavaElementResolver.class).in(Scopes.SINGLETON); requestStaticInjection(ASTStringUtils.class); requestStaticInjection(ASTNodeUtils.class); requestStaticInjection(BindingUtils.class); } private void configureAstProvider() { final CachingAstProvider p = new CachingAstProvider(); JavaCore.addElementChangedListener(p); bind(IAstProvider.class).toInstance(p); } private void initalizeSingletonServices() { bind(ServicesInitializer.class).asEagerSingleton(); } @Singleton @Provides protected JavaModelEventsProvider provideJavaModelEventsProvider(final EventBus bus, final IWorkspaceRoot workspace) { final JavaModelEventsProvider p = new JavaModelEventsProvider(bus, workspace); JavaCore.addElementChangedListener(p); return p; } @Singleton @Provides // @Workspace protected EventBus provideWorkspaceEventBus() { final int numberOfCores = Runtime.getRuntime().availableProcessors(); final ExecutorService pool = coreThreadsTimoutExecutor(numberOfCores + 1, MIN_PRIORITY, "Recommenders-Bus-Thread-", 1L, TimeUnit.MINUTES); final EventBus bus = new AsyncEventBus("Code Recommenders asychronous Workspace Event Bus", pool); return bus; } @Provides @Singleton protected JavaSelectionProvider provideJavaSelectionProvider(final EventBus bus) { final JavaSelectionProvider provider = new JavaSelectionProvider(bus); - new UIJob("Register workbench selection lister") { + new UIJob("Registering workbench selection listener.") { { schedule(); } @Override public IStatus runInUIThread(final IProgressMonitor monitor) { final IWorkbenchWindow ww = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final ISelectionService service = (ISelectionService) ww.getService(ISelectionService.class); service.addPostSelectionListener(provider); return Status.OK_STATUS; } }; return provider; } @Provides protected IWorkspaceRoot provideWorkspaceRoot() { return ResourcesPlugin.getWorkspace().getRoot(); } @Provides protected IWorkspace provideWorkspace() { return ResourcesPlugin.getWorkspace(); } @Provides protected IWorkbench provideWorkbench() { return PlatformUI.getWorkbench(); } @Provides protected IWorkbenchPage provideActiveWorkbenchPage(final IWorkbench wb) { if (isRunningInUiThread()) { return wb.getActiveWorkbenchWindow().getActivePage(); } return runUiFinder().activePage; } private ActivePageFinder runUiFinder() { final ActivePageFinder finder = new ActivePageFinder(); try { if (isRunningInUiThread()) { finder.call(); } else { final FutureTask<IWorkbenchPage> task = new FutureTask(finder); Display.getDefault().asyncExec(task); task.get(2, TimeUnit.SECONDS); } } catch (final Exception e) { RecommendersPlugin.logError(e, "Could not run 'active page finder' that early!"); } return finder; } private boolean isRunningInUiThread() { return Display.getCurrent() != null; } @Provides protected IJavaModel provideJavaModel() { return JavaModelManager.getJavaModelManager().getJavaModel(); } @Provides protected JavaModelManager provideJavaModelManger() { return JavaModelManager.getJavaModelManager(); } private final class ActivePageFinder implements Callable<IWorkbenchPage> { private IWorkbench workbench; private IWorkbenchWindow activeWorkbenchWindow; private IWorkbenchPage activePage; @Override public IWorkbenchPage call() throws Exception { workbench = PlatformUI.getWorkbench(); activeWorkbenchWindow = workbench.getActiveWorkbenchWindow(); activePage = activeWorkbenchWindow.getActivePage(); return activePage; } } /* * this is a bit odd. Used to initialize complex wired elements such as JavaElementsProvider etc. */ public static class ServicesInitializer { @Inject private ServicesInitializer(final IAstProvider astProvider, final JavaModelEventsProvider eventsProvider, final JavaSelectionProvider selectionProvider) { ensureIsNotNull(astProvider); ensureIsNotNull(eventsProvider); } } }
true
true
protected JavaSelectionProvider provideJavaSelectionProvider(final EventBus bus) { final JavaSelectionProvider provider = new JavaSelectionProvider(bus); new UIJob("Register workbench selection lister") { { schedule(); } @Override public IStatus runInUIThread(final IProgressMonitor monitor) { final IWorkbenchWindow ww = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final ISelectionService service = (ISelectionService) ww.getService(ISelectionService.class); service.addPostSelectionListener(provider); return Status.OK_STATUS; } }; return provider; }
protected JavaSelectionProvider provideJavaSelectionProvider(final EventBus bus) { final JavaSelectionProvider provider = new JavaSelectionProvider(bus); new UIJob("Registering workbench selection listener.") { { schedule(); } @Override public IStatus runInUIThread(final IProgressMonitor monitor) { final IWorkbenchWindow ww = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); final ISelectionService service = (ISelectionService) ww.getService(ISelectionService.class); service.addPostSelectionListener(provider); return Status.OK_STATUS; } }; return provider; }
diff --git a/src/ch/blinkenlights/battery/BlinkenlightsBatteryService.java b/src/ch/blinkenlights/battery/BlinkenlightsBatteryService.java index 9775bf4..1a73c5f 100644 --- a/src/ch/blinkenlights/battery/BlinkenlightsBatteryService.java +++ b/src/ch/blinkenlights/battery/BlinkenlightsBatteryService.java @@ -1,222 +1,222 @@ /******************************************************* * * Part of ch.blinkenlights.battery * * (C) 2011 Adrian Ulrich * * Licensed under the GPLv2 * *******************************************************/ package ch.blinkenlights.battery; import android.app.Service; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.content.Intent; import android.text.format.DateFormat; import java.util.Date; import java.text.SimpleDateFormat; public class BlinkenlightsBatteryService extends Service { private final static String T = "BlinkenlightsBatteryService.class: "; // Log Token private final IBinder bb_binder = new LocalBinder(); private int[] battery_state = new int[4]; private NotificationManager notify_manager; private ConfigUtil bconfig; @Override public IBinder onBind(Intent i) { return bb_binder; } public class LocalBinder extends Binder { public BlinkenlightsBatteryService getService() { return BlinkenlightsBatteryService.this; } } @Override public void onCreate() { bconfig = new ConfigUtil(getApplicationContext()); /* create notification manager stuff and register ourself as a service */ notify_manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); registerReceiver(bb_bcreceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); Log.d(T,"+++++ onCreate() finished - broadcaster registered +++++"); } public void onDestory() { unregisterReceiver(bb_bcreceiver); } /* Receives battery_changed events */ private final BroadcastReceiver bb_bcreceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int level = intent.getIntExtra("level", 0); int scale = intent.getIntExtra("scale", 100); battery_state[0] = level*100/scale; /* capacity percent */ battery_state[1] = ( intent.getIntExtra("plugged",0) == 0 ? 0 : 1 ); /* plug status */ battery_state[2] = intent.getIntExtra("voltage",0); /* voltage */ battery_state[3] = intent.getIntExtra("temperature", 0); /* temperature */ /* trigger update with new values */ updateNotifyIcon(); }}; public void updateNotifyIcon() { Context ctx = getApplicationContext(); int prcnt = battery_state[0]; int curplug = battery_state[1]; int voltage = battery_state[2]; int temp = battery_state[3]; /* TRY to get old values. -1 if failed */ int oldprcnt = bconfig.GetPercentage(); int oldplug = bconfig.GetPlugStatus(); int oldts = bconfig.GetTimestamp(); /* defy (and other stupid-as-heck motorola phones return the capacity in 10% steps. ..but sysfs knows the real 1%-res value */ if(bconfig.IsMotorola() && bconfig.GetMotorolaPercent() != 0) { prcnt = bconfig.GetMotorolaPercent(); } /* absolute dummy tests for defy and co: */ if(prcnt > 100) { prcnt = 100; } if(prcnt < 0) { prcnt = 0; } /* percentage is now good in any case: check current status */ /* plug changed OR we reached 100 percent */ if( (curplug != oldplug) || (prcnt == 100) ) { Log.d(T, "++ STATUS CHANGE ++: oldplug="+oldplug+", curplug="+curplug+", percentage="+prcnt); oldprcnt = prcnt; oldts = unixtimeAsInt(); bconfig.SetPlugStatus(curplug); bconfig.SetPercentage(prcnt); bconfig.SetTimestamp(oldts); } // prepare interface texts String vx = String.valueOf(voltage/1000.0); String ntext = ""; String ntitle = ((prcnt == 100 && curplug == 1) ? gtx(R.string.fully_charged) : (curplug == 0 ? gtx(R.string.discharging_from)+" "+oldprcnt+"%" : gtx(R.string.charging_from)+" "+oldprcnt+"%")); /* Discharging from 99% */ String timetxt = getTimeString(oldts); /* 12 hours */ int icon_id = bconfig.GetIconFor(prcnt, (curplug!=0 && bconfig.ChargeGlow()) ); // set details text if(bconfig.ShowDetails()) { /* create temperature string in celsius or fareinheit */ String dgtmp = String.valueOf(temp/10.0)+gtx(R.string.degree)+"C"; if(bconfig.TempInFahrenheit()) { dgtmp = String.valueOf( ( (int)((temp * 1.8)+320) )/10.0 )+gtx(R.string.degree)+"F"; } ntext += vx+"V, "+dgtmp; ntext += _ICSFILTER_( ", "+gtx(R.string.capacity_at)+" "+prcnt+"%" ); /* capacity is not displayed on ICS */ } else { ntext += (voltage == 0 ? "" : gtx(R.string.voltage)+" "+vx+" V"); ntext += _ICSFILTER_( " // "+gtx(R.string.capacity_at)+" "+prcnt+"%" ); /* same here: no capacity on ICS */ } // end details text if(isICS() == true) { - ntext = "...since "+timetxt+" / "+ntext; /* 'since' is located in the text section on ICS */ + ntext = "..."+gtx(R.string.since)+" "+timetxt+" / "+ntext; /* 'since' is located in the text section on ICS */ } else { ntitle += " "+gtx(R.string.since)+": "+timetxt; /* add 'since' info to title */ ntext += " "+gtx(R.string.since)+":"; /* add 'since' before event TS */ } // Log.d(T,"Showing icon for "+prcnt+"% - using icon "+icon_id); /* create new notify with updated icon: icons are sorted integers :-) */ Notification this_notify = new Notification(icon_id, null, System.currentTimeMillis()); this_notify.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; this_notify.setLatestEventInfo(ctx, ntitle, ntext, getConfiguredIntent() ); notify_manager.notify(0, this_notify); } private final String gtx(int resid) { return (String) getResources().getText(resid); } private final int unixtimeAsInt() { return (int) (System.currentTimeMillis() / 1000L); } /* Returns a 'human friendly' time */ private String getTimeString(int tstamp) { String s = ""; int timediff = unixtimeAsInt() - tstamp; if(timediff > 60*60*2) { s = ""+(int)(timediff/60/60)+" "+gtx(R.string.hours); } else { String fmt_style = (DateFormat.is24HourFormat(getApplicationContext()) ? "HH:mm" : "h:mm aa"); SimpleDateFormat sdf = new SimpleDateFormat(fmt_style); s = ""+sdf.format( new Date( (long)tstamp*1000 ) ); } return s; } /* Return an empty string on ICS */ private String _ICSFILTER_(String s) { if(isICS() == true) { return ""; } else { return s; } } /* Returns TRUE if we are running on Android 4 */ private boolean isICS() { return (android.os.Build.VERSION.SDK_INT >= 14); } public void harakiri() { Log.d(T, "terminating myself - unregistering receiver"); unregisterReceiver(bb_bcreceiver); notify_manager.cancelAll(); } public void debug() { Log.d(T, "+++ dumping status ++++"); } public PendingIntent getConfiguredIntent() { PendingIntent ret = null; if(bconfig.NotifyClickOpensPowerUsage()) { ret = PendingIntent.getActivity(this, 0, (new Intent(Intent.ACTION_POWER_USAGE_SUMMARY)), PendingIntent.FLAG_UPDATE_CURRENT); } else { ret = PendingIntent.getActivity(this, 0, (new Intent(this, BlinkenlightsBattery.class)), 0); } return ret; } }
true
true
public void updateNotifyIcon() { Context ctx = getApplicationContext(); int prcnt = battery_state[0]; int curplug = battery_state[1]; int voltage = battery_state[2]; int temp = battery_state[3]; /* TRY to get old values. -1 if failed */ int oldprcnt = bconfig.GetPercentage(); int oldplug = bconfig.GetPlugStatus(); int oldts = bconfig.GetTimestamp(); /* defy (and other stupid-as-heck motorola phones return the capacity in 10% steps. ..but sysfs knows the real 1%-res value */ if(bconfig.IsMotorola() && bconfig.GetMotorolaPercent() != 0) { prcnt = bconfig.GetMotorolaPercent(); } /* absolute dummy tests for defy and co: */ if(prcnt > 100) { prcnt = 100; } if(prcnt < 0) { prcnt = 0; } /* percentage is now good in any case: check current status */ /* plug changed OR we reached 100 percent */ if( (curplug != oldplug) || (prcnt == 100) ) { Log.d(T, "++ STATUS CHANGE ++: oldplug="+oldplug+", curplug="+curplug+", percentage="+prcnt); oldprcnt = prcnt; oldts = unixtimeAsInt(); bconfig.SetPlugStatus(curplug); bconfig.SetPercentage(prcnt); bconfig.SetTimestamp(oldts); } // prepare interface texts String vx = String.valueOf(voltage/1000.0); String ntext = ""; String ntitle = ((prcnt == 100 && curplug == 1) ? gtx(R.string.fully_charged) : (curplug == 0 ? gtx(R.string.discharging_from)+" "+oldprcnt+"%" : gtx(R.string.charging_from)+" "+oldprcnt+"%")); /* Discharging from 99% */ String timetxt = getTimeString(oldts); /* 12 hours */ int icon_id = bconfig.GetIconFor(prcnt, (curplug!=0 && bconfig.ChargeGlow()) ); // set details text if(bconfig.ShowDetails()) { /* create temperature string in celsius or fareinheit */ String dgtmp = String.valueOf(temp/10.0)+gtx(R.string.degree)+"C"; if(bconfig.TempInFahrenheit()) { dgtmp = String.valueOf( ( (int)((temp * 1.8)+320) )/10.0 )+gtx(R.string.degree)+"F"; } ntext += vx+"V, "+dgtmp; ntext += _ICSFILTER_( ", "+gtx(R.string.capacity_at)+" "+prcnt+"%" ); /* capacity is not displayed on ICS */ } else { ntext += (voltage == 0 ? "" : gtx(R.string.voltage)+" "+vx+" V"); ntext += _ICSFILTER_( " // "+gtx(R.string.capacity_at)+" "+prcnt+"%" ); /* same here: no capacity on ICS */ } // end details text if(isICS() == true) { ntext = "...since "+timetxt+" / "+ntext; /* 'since' is located in the text section on ICS */ } else { ntitle += " "+gtx(R.string.since)+": "+timetxt; /* add 'since' info to title */ ntext += " "+gtx(R.string.since)+":"; /* add 'since' before event TS */ } // Log.d(T,"Showing icon for "+prcnt+"% - using icon "+icon_id); /* create new notify with updated icon: icons are sorted integers :-) */ Notification this_notify = new Notification(icon_id, null, System.currentTimeMillis()); this_notify.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; this_notify.setLatestEventInfo(ctx, ntitle, ntext, getConfiguredIntent() ); notify_manager.notify(0, this_notify); }
public void updateNotifyIcon() { Context ctx = getApplicationContext(); int prcnt = battery_state[0]; int curplug = battery_state[1]; int voltage = battery_state[2]; int temp = battery_state[3]; /* TRY to get old values. -1 if failed */ int oldprcnt = bconfig.GetPercentage(); int oldplug = bconfig.GetPlugStatus(); int oldts = bconfig.GetTimestamp(); /* defy (and other stupid-as-heck motorola phones return the capacity in 10% steps. ..but sysfs knows the real 1%-res value */ if(bconfig.IsMotorola() && bconfig.GetMotorolaPercent() != 0) { prcnt = bconfig.GetMotorolaPercent(); } /* absolute dummy tests for defy and co: */ if(prcnt > 100) { prcnt = 100; } if(prcnt < 0) { prcnt = 0; } /* percentage is now good in any case: check current status */ /* plug changed OR we reached 100 percent */ if( (curplug != oldplug) || (prcnt == 100) ) { Log.d(T, "++ STATUS CHANGE ++: oldplug="+oldplug+", curplug="+curplug+", percentage="+prcnt); oldprcnt = prcnt; oldts = unixtimeAsInt(); bconfig.SetPlugStatus(curplug); bconfig.SetPercentage(prcnt); bconfig.SetTimestamp(oldts); } // prepare interface texts String vx = String.valueOf(voltage/1000.0); String ntext = ""; String ntitle = ((prcnt == 100 && curplug == 1) ? gtx(R.string.fully_charged) : (curplug == 0 ? gtx(R.string.discharging_from)+" "+oldprcnt+"%" : gtx(R.string.charging_from)+" "+oldprcnt+"%")); /* Discharging from 99% */ String timetxt = getTimeString(oldts); /* 12 hours */ int icon_id = bconfig.GetIconFor(prcnt, (curplug!=0 && bconfig.ChargeGlow()) ); // set details text if(bconfig.ShowDetails()) { /* create temperature string in celsius or fareinheit */ String dgtmp = String.valueOf(temp/10.0)+gtx(R.string.degree)+"C"; if(bconfig.TempInFahrenheit()) { dgtmp = String.valueOf( ( (int)((temp * 1.8)+320) )/10.0 )+gtx(R.string.degree)+"F"; } ntext += vx+"V, "+dgtmp; ntext += _ICSFILTER_( ", "+gtx(R.string.capacity_at)+" "+prcnt+"%" ); /* capacity is not displayed on ICS */ } else { ntext += (voltage == 0 ? "" : gtx(R.string.voltage)+" "+vx+" V"); ntext += _ICSFILTER_( " // "+gtx(R.string.capacity_at)+" "+prcnt+"%" ); /* same here: no capacity on ICS */ } // end details text if(isICS() == true) { ntext = "..."+gtx(R.string.since)+" "+timetxt+" / "+ntext; /* 'since' is located in the text section on ICS */ } else { ntitle += " "+gtx(R.string.since)+": "+timetxt; /* add 'since' info to title */ ntext += " "+gtx(R.string.since)+":"; /* add 'since' before event TS */ } // Log.d(T,"Showing icon for "+prcnt+"% - using icon "+icon_id); /* create new notify with updated icon: icons are sorted integers :-) */ Notification this_notify = new Notification(icon_id, null, System.currentTimeMillis()); this_notify.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; this_notify.setLatestEventInfo(ctx, ntitle, ntext, getConfiguredIntent() ); notify_manager.notify(0, this_notify); }
diff --git a/src/de/freinsberg/pomecaloco/ObjectDetector.java b/src/de/freinsberg/pomecaloco/ObjectDetector.java index fe5ae37..91b71af 100644 --- a/src/de/freinsberg/pomecaloco/ObjectDetector.java +++ b/src/de/freinsberg/pomecaloco/ObjectDetector.java @@ -1,714 +1,711 @@ package de.freinsberg.pomecaloco; import java.io.File; import java.util.ArrayList; import java.util.List; import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame; import org.opencv.android.Utils; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Range; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; import android.graphics.Bitmap; import android.os.Environment; import android.support.v4.app.Fragment; import android.util.Log; import android.view.Display; import android.widget.Toast; public class ObjectDetector{ private static final int ORIENTATION_0 = 0; private static final int ORIENTATION_90 = 90; private static final int ORIENTATION_270 = 270; private static final int LEFT_LANE = 1; private static final int RIGHT_LANE = 2; final public static int NO_CAR = 0x00; final public static int RIGHT_CAR = 0x01; final public static int LEFT_CAR = 0x10; final public static int BOTH_CAR = 0x11; private static Mat mInputFrame; private static Mat mInputFramePortrait; private Mat mStaticImage = null; private Mat mRgba = null; private Mat mGray = null; private Mat mHSV = null; private Mat mEdges = null; private Mat mHoughLines = null; private int mHLthreshold = 30; private int mHLminLineSize = 200; private int mHLlineGap = 20; private Point mLowerPoint; private Scalar mUpperLaneColor; private Scalar mLowerLaneColor; private Point mSeparatorPoint; private Point mUpperPoint; private boolean mFoundSeparatorLine; private boolean mFoundUpperLine; private boolean mFoundLowerLine; private boolean mDrawedLinesOnFrame; private boolean mColorsOnLeftLane; private boolean mColorsOnRightLane; private int mLowerThreshold; private int mUpperThreshold; private Mat mThreshed = null; private Mat mLowerRangeImage = null; private Mat mUpperRangeImage = null; private Mat mEmptyTrack = null; private Mat track_overlay = null; private Bitmap mTrackOverlay= null; private Mat mCarRecognizerOverlay; private Bitmap mCarRecognizer; private Scalar mLeftCarColorScalar; private Scalar mRightCarColorScalar; private Mat mLeftCarColor; private Mat mRightCarColor; private Bitmap mLeftCarColorImage; private Bitmap mRightCarColorImage; private Bitmap[] mCarColorImages; double[] mScannedTrackPixelColor; double[] mEmptyTrackPixelColor; List <double[]> mFoundColors = new ArrayList<double[]>(); private int avg_gray; private File mStorageDir; private File mHoughLinesImage; private File mCannyEdgeImage; private File mTrackColor; private String mPath; private static ObjectDetector mObjectDetector = new ObjectDetector(); private ObjectDetector(){ } public static ObjectDetector getInstance(Mat inputFrame){ mInputFrame = inputFrame; mInputFramePortrait = inputFrame.t(); Core.flip(mInputFramePortrait, mInputFramePortrait, 1); return mObjectDetector; } public static ObjectDetector getInstance() { return mObjectDetector; } private Mat correct_rotation(Display d, Mat m){ //Log.i("debug", "Jetzt wird rotiert!"); //Mat gray = new Mat(m.size(), m.type()); //Mat rotated = new Mat(new Size(m.rows(),m.cols()), m.type()); //Imgproc.cvtColor(m, gray, Imgproc.COLOR_RGB2GRAY); //Log.i("debug", "Found rotation: "+d.getRotation()); int screenOrientation = d.getRotation(); switch (screenOrientation){ default: case ORIENTATION_0: // Portrait /*Log.i("debug", "Original Channels: "+m.channels()); Log.i("debug", "Original Size: "+m.size().toString()); Log.i("debug", "Original Type: "+m.type()); Log.i("debug", "Grayscale Channels: "+gray.channels()); Log.i("debug", "Grayscale Size: "+gray.size().toString()); Log.i("debug", "Grayscale Type: "+gray.type()); Core.flip(gray.t(), gray, 1); Log.i("debug", "Grayscale after transpose Channels: "+gray.channels()); Log.i("debug", "Grayscale after transpose Size: "+gray.size().toString()); Log.i("debug", "Grayscale after transpose Type: "+gray.type()); Imgproc.cvtColor(gray, rotated, Imgproc.COLOR_GRAY2RGB, 4); Log.i("debug", "Rotated after cvt Channels: "+rotated.channels()); Log.i("debug", "Rotated after cvt Size: "+rotated.size().toString()); Log.i("debug", "Rotated after cvt Type: "+rotated.type());*/ //Log.i("debug", "Depth: "+m.depth()+ "Height: "+m.height()+"Width: "+m.width()); //Core.flip(m.t(), rotated, 1); //Log.i("debug", "Depth: "+rotated.depth()+ "Height: "+rotated.height()+"Width: "+rotated.width()); //Log.i("debug", "to Portrait"); //rotated.release(); break; case ORIENTATION_90: // Landscape right // do smth. break; case ORIENTATION_270: // Landscape left // do smth. break; } return m; } // public Mat draw_colorrange_on_frame (Display d, Scalar lowerLimit, Scalar upperLimit){ // //Log.i("debug", "onCameraFrame"); // mRgba = correct_rotation(d, mInputFrame.rgba()); // if(mThreshed != null) // mThreshed.release(); // mThreshed = new Mat(mRgba.size(),mRgba.type()); // //Log.i("debug",Integer.toString(mRgba.cols())); // //mEdges = new Mat(mRgba.size(),mRgba.type()); // mHSV = new Mat(mRgba.size(),mRgba.type()); // Imgproc.cvtColor(mRgba, mHSV, Imgproc.COLOR_RGB2HSV); // Core.inRange(mHSV, lowerLimit, upperLimit, mThreshed); // // mHSV.release(); // /* Imgproc.cvtColor((Mat) inputFrame, mColoredFrame, Imgproc.COLOR_RGB2HSV); // Log.i("debug", "Color to HSV"); // Core.inRange(mColoredFrame, lowerColorLimit, upperColorLimit, mColoredResult); // Log.i("debug", "Colored Frame!"); // mFilteredFrame.setTo(new Scalar(0, 0, 0)); // Log.i("debug", "cleared new Frame"); // ((Mat) inputFrame).copyTo(mFilteredFrame, mColoredResult); // Log.i("debug", "Result!");*/ // //Log.i("debug", "Grayscaled"); // return mThreshed; // } public boolean getFoundLines(){ return mFoundSeparatorLine && mFoundUpperLine && mFoundLowerLine; } public int[] getCenterOfLanes(){ int[] arr = new int[2]; arr[0] = (int) (((mSeparatorPoint.x - mUpperPoint.x) / 2) + mUpperPoint.x); arr[1] = (int) (((mLowerPoint.x -mSeparatorPoint.x) /2)+mSeparatorPoint.x); return arr; } public Bitmap draw_car_recognizer(){ try{ mCarRecognizerOverlay = new Mat(new Size(mInputFramePortrait.cols(), mInputFramePortrait.rows()), mInputFramePortrait.type(), new Scalar(0, 0, 0, 0)); Core.rectangle(mCarRecognizerOverlay, new Point(getCenterOfLanes()[0] - 15, (mInputFramePortrait.rows()/2) - 15), new Point(getCenterOfLanes()[0] + 15, (mInputFramePortrait.rows()/2) + 15), new Scalar(255,255,255,255)); Core.rectangle(mCarRecognizerOverlay, new Point(getCenterOfLanes()[1] - 15, (mInputFramePortrait.rows()/2) - 15), new Point(getCenterOfLanes()[1] + 15, (mInputFramePortrait.rows()/2) + 15), new Scalar(255,255,255,255)); mCarRecognizer = Bitmap.createBitmap(mCarRecognizerOverlay.cols(), mCarRecognizerOverlay.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(mCarRecognizerOverlay, mCarRecognizer); }catch(Exception e){ e.printStackTrace(); return null; } return mCarRecognizer; } public Rect[] getLanesToScanColor(){ Rect[] arr = new Rect[2]; arr[0] = new Rect(new Point(getCenterOfLanes()[0] - 15, (mInputFramePortrait.rows()/2) - 15), new Point(getCenterOfLanes()[0] + 15, (mInputFramePortrait.rows()/2) + 15)); arr[1] = new Rect(new Point(getCenterOfLanes()[1] - 15, (mInputFramePortrait.rows()/2) - 15), new Point(getCenterOfLanes()[1] + 15, (mInputFramePortrait.rows()/2) + 15)); return arr; } public Scalar getCarColor(int lane) { if (lane == LEFT_LANE) return mLeftCarColorScalar; else return mRightCarColorScalar; } public Bitmap getColorInOffset(int x_offset, int y_offset, int lane){ Log.i("debug", "Into getColorInOffset for lane :"+lane); if(mInputFramePortrait.empty()) Log.i("debug","mInputFramePortrait is empty!"); mRgba = mInputFramePortrait; double[] oldColors = new double[4]; double[] newColors = new double[4]; double[] avg_oldColors = new double[4]; double[] avg_newColors = new double[4]; double[] foundColor = new double[4]; int scan_counter = 0; if(lane == LEFT_LANE) mColorsOnLeftLane = false; else if(lane == RIGHT_LANE) mColorsOnRightLane = false; Log.i("debug", "Before FOR getColorInOffset for lane :"+lane); for(int x = x_offset;x< x_offset +30;x++){ for (int y = y_offset;y < y_offset+30;y++){ if(mEmptyTrack.empty()) Log.i("debug","mEmptyTrack is empty"); if(mRgba.empty()) Log.i("debug","mRgba is empty"); mEmptyTrackPixelColor = mEmptyTrack.get(y, x); mScannedTrackPixelColor = mRgba.get(y, x); if(mScannedTrackPixelColor == null) Log.i("debug", "mScannedTrackPixelColor == null, at: "+x+", "+y); if(mEmptyTrackPixelColor == null) Log.i("debug","mEmptyTrackPixelColor == null, at: "+x+", "+y); scan_counter++; // double min = 256; // double max = -1; // // for(int k = 0; k < 3; k++) { // if(mScannedTrackPixelColor[k] < min) // min = mScannedTrackPixelColor[k]; // if(mScannedTrackPixelColor[k] > max) // max = mScannedTrackPixelColor[k]; // } // // double min2 = 256; // double max2 = -1; // // for(int k = 0; k < 3; k++) { // if(mEmptyTrackPixelColor[k] < min2) // min2 = mEmptyTrackPixelColor[k]; // if(mEmptyTrackPixelColor[k] > max2) // max2 = mEmptyTrackPixelColor[k]; // } for(int i = 0; i <= 3; i++) { newColors[i] += mScannedTrackPixelColor[i]; } for(int i = 0; i <= 3; i++) { oldColors[i] += mEmptyTrackPixelColor[i]; } } } Log.i("debug", "Between FOR getColorInOffset for lane :"+lane); for(int i = 0; i <= 3; i++) { avg_oldColors[i] = oldColors[i] / scan_counter; avg_newColors[i] = newColors[i] / scan_counter; } Log.i("debug", "After FOR getColorInOffset for lane :"+lane); Log.i("debug", "avg_Old: r"+avg_oldColors[0]+ ", g"+avg_oldColors[1]+ ", b"+avg_oldColors[2]); Log.i("debug", "avg_New: r"+avg_newColors[0]+ ", g"+avg_newColors[1]+ ", b"+avg_newColors[2]); boolean colorDetected = isDifferent(avg_newColors, avg_oldColors); Log.i("farbeee", "color on left lane AFTER for loop and BEFORE ifelses: "+ mLeftCarColorScalar); Log.i("farbeee", "color on right lane AFTER for loop and BEFORE ifelses: "+ mRightCarColorScalar); if(lane == LEFT_LANE) { if(!colorDetected) mColorsOnLeftLane = false; else{ mColorsOnLeftLane = true; mLeftCarColorScalar = new Scalar(avg_newColors); Log.i("farbeee", "color on left lane IN ifelses: "+ mLeftCarColorScalar); mLeftCarColor = new Mat(getLanesToScanColor()[0].x,getLanesToScanColor()[0].y, mInputFramePortrait.type(),mLeftCarColorScalar); mLeftCarColorImage = Bitmap.createBitmap(mLeftCarColor.cols(), mLeftCarColor.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(mLeftCarColor, mLeftCarColorImage); mFoundColors.clear(); if(mColorsOnLeftLane) Log.i("debug", "color on leftlane"); return mLeftCarColorImage; } }else if(lane == RIGHT_LANE) { if(!colorDetected) mColorsOnRightLane = false; else{ mColorsOnRightLane = true; mRightCarColorScalar = new Scalar(avg_newColors); Log.i("farbeee", "color on right lane IN ifelses: "+ mRightCarColorScalar); mRightCarColor = new Mat(getLanesToScanColor()[0].x,getLanesToScanColor()[0].y, mInputFramePortrait.type(),mRightCarColorScalar); mRightCarColorImage = Bitmap.createBitmap(mRightCarColor.cols(), mRightCarColor.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(mRightCarColor, mRightCarColorImage); mFoundColors.clear(); if(mColorsOnRightLane) Log.i("debug", "color on rightlane"); return mRightCarColorImage; } } return null; } public Bitmap generate_track_overlay() { // Load an Image to try operations on local stored files mFoundSeparatorLine = false; mFoundUpperLine = false; mFoundLowerLine = false; mGray = new Mat(); mEdges = new Mat(); mHoughLines = new Mat(); mEmptyTrack = new Mat(); mStaticImage = Highgui .imread(Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "track.jpg"); track_overlay = new Mat(new Size(mInputFramePortrait.cols(), mInputFramePortrait .rows()), mInputFramePortrait.type(), new Scalar(0, 0, 0, 0)); Log.i("debug", "Channels: " + track_overlay.channels()); Imgproc.cvtColor(mInputFramePortrait, mGray, Imgproc.COLOR_RGBA2GRAY); double[] grays = null; double wert; double count = 0; double divider = 0; for (int i = 0; i < mGray.rows(); i++) { for (int j = 0; j < mGray.cols(); j++) { if (grays != null) grays = null; grays = mGray.get(i, j); wert = grays[0]; divider++; count = count + wert; } } avg_gray = (int) (count / divider); Log.i("debug", "avg_gray: " + avg_gray); mLowerThreshold = (int) (avg_gray * 0.66); mUpperThreshold = (int) (avg_gray * 1.33); Imgproc.Canny(mGray, mEdges, mLowerThreshold, mUpperThreshold); //mGray.release(); // Highgui.imwrite("/houghlines.png", mHoughLines); - Log.i("debug", - "Status Sd-Karte: " - + Environment.getExternalStorageState()); - mStorageDir = Environment - .getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); + Log.i("debug","Status Sd-Karte: "+ Environment.getExternalStorageState()); + mStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); // mCannyEdgeImage = new File(mStorageDir, "canny.bmp"); // mPath = mCannyEdgeImage.toString(); // Boolean bool = Highgui.imwrite(mPath, mEdges); // if (bool) // Log.i("debug", "SUCCESS writing canny.bmp to external storage"); // else // Log.i("debug", "Fail writing canny.bmp to external storage"); if((!mEdges.empty() && !mInputFramePortrait.empty())) { Imgproc.HoughLinesP(mEdges, mHoughLines, 1, Math.PI / 180, mHLthreshold, mHLminLineSize, mHLlineGap); for (int x = 0; x < mHoughLines.cols(); x++) { double[] vec = mHoughLines.get(0, x); double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3]; if (x1 > mInputFramePortrait.cols() / 2 - 30 && x1 < mInputFramePortrait.cols() / 2 + 30 && x2 > mInputFramePortrait.cols() / 2 - 30 && x2 < mInputFramePortrait.cols() / 2 + 30) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mSeparatorPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundSeparatorLine = true; } else if(x1 < 50 && x2 < 50) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mUpperPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundUpperLine = true; } else if(x1 > mInputFramePortrait.cols() - 50 && x2 > mInputFramePortrait.cols() - 50) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mLowerPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundLowerLine = true; } } mTrackOverlay = Bitmap.createBitmap(track_overlay.cols(), track_overlay.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(track_overlay, mTrackOverlay); mInputFramePortrait.copyTo(mEmptyTrack); } //mHoughLinesImage = new File(mStorageDir, "houghed.png"); //mPath = mHoughLinesImage.toString(); //Highgui.imwrite(mPath, track_overlay); //Getting average color for every lane double[] rgba = null; double R, G, B, A; double RCount = 0; double GCount = 0; double BCount = 0; double ACount = 0; double avgR = 0; double avgG = 0; double avgB = 0; double avgA = 0; //Upper lane // if(mFoundUpperLine){ // for(int i = ((int)mUpperPoint.y+10); i < mSeparatorPoint.y-10; i++){ // for (int j = 0;j < mEmptyTrack.cols();j++){ // if (rgba != null) // rgba = null; // rgba = mEmptyTrack.get(i, j); // R = rgba[0]; // G = rgba[1]; // B = rgba[2]; // A = rgba[3]; // divider++; // RCount += R; // GCount += G; // BCount += B; // ACount += A; // } // } // // mUpperLaneColor = new Scalar(avgR,avgG,avgB,avgA); // avgR = RCount /divider; // avgG = GCount /divider; // avgB = BCount/divider; // avgA = ACount/ divider; // Log.i("debug", "Start: "+mUpperPoint.y); // Log.i("debug", "Ende: "+mSeparatorPoint.y); // Log.i("debug", "UPPER LANE: "); // Log.i("debug", "avg R: "+avgR); // Log.i("debug", "avg G: "+avgG); // Log.i("debug", "avg B: "+avgB); // Log.i("debug", "avg Alpha: "+avgA); // // } // //Lower lane // //TODO Null Pointer Exception when line was found before --> but other lines not and then when this line not found this option is still true from before // if(mFoundLowerLine){ // for(int i = ((int)mLowerPoint.y-10); i > mSeparatorPoint.y+10; i--){ // for (int j = 0;j < mEmptyTrack.cols();j++){ // if (rgba != null) // rgba = null; // rgba = mEmptyTrack.get(i, j); // R = rgba[0]; // G = rgba[1]; // B = rgba[2]; // A = rgba[3]; // divider++; // RCount += R; // GCount += G; // BCount += B; // ACount += A; // } // } // // mLowerLaneColor = new Scalar(avgR,avgG,avgB,avgA); // avgR = RCount /divider; // avgG = GCount /divider; // avgB = BCount/divider; // avgA = ACount/ divider; // Log.i("debug", "Start: "+mLowerPoint.y); // Log.i("debug", "Ende: "+mSeparatorPoint.y); // Log.i("debug", "LOWER LANE: "); // Log.i("debug", "avg R: "+avgR); // Log.i("debug", "avg G: "+avgG); // Log.i("debug", "avg B: "+avgB); // Log.i("debug", "avg Alpha: "+avgA); // } //Core.flip(track_overlay.t(), track_overlay, 1); return mTrackOverlay; } public boolean isDifferent(double[] avg_oldColors, double[] avg_newColors){ for(int i = 0; i < 4; i++) { if(avg_newColors[i] > avg_oldColors[i] + 50 ||avg_newColors[i] < avg_oldColors[i] - 50) return true; } return false; } public int car_status(){ int carStatus = 0; if(mColorsOnLeftLane && mColorsOnRightLane) carStatus = BOTH_CAR; else if(mColorsOnLeftLane) carStatus = LEFT_CAR; else if(mColorsOnRightLane) carStatus = RIGHT_CAR; else carStatus = NO_CAR; Log.i("debug", "carStatus: "+carStatus); return carStatus; } public int getNumberOfCars() { if(mColorsOnLeftLane && mColorsOnRightLane) return 2; else if(mColorsOnLeftLane) return 1; else if(mColorsOnRightLane) return 1; else return 0; } public Bitmap[] get_cars_colors (){ Log.i("debug", "Into get_car_colors!"); int x_offset_left = getCenterOfLanes()[0]-15; int y_offset_left = (mInputFramePortrait.rows()/2)-15; int x_offset_right = getCenterOfLanes()[1]-15; int y_offset_right = (mInputFramePortrait.rows()/2)-15; mCarColorImages = new Bitmap[2]; Log.i("debug", "In the middle of get_car_colors!"); mCarColorImages[0] = getColorInOffset(x_offset_left, y_offset_left, LEFT_LANE); mCarColorImages[1] = getColorInOffset(x_offset_right, y_offset_right, RIGHT_LANE); Log.i("debug", "Tschüss get_car_colors!"); return mCarColorImages; // Mat mDiff = new Mat(); // Mat hsva = new Mat(); // Mat hsvb = new Mat(); // // Imgproc.cvtColor(mRgba, hsva, Imgproc.COLOR_BGR2HSV, 3); // //Imgproc.cvtColor(mEmptyTrack, hsvb, Imgproc.COLOR_BGR2HSV, 3); // //Core.absdiff(hsva, hsvb, mDiff); // Imgproc.cvtColor(mDiff, mDiff, Imgproc.COLOR_HSV2BGR); // //Imgproc.cvtColor(mDiff, mDiff, Imgproc.COLOR_BGR2RGB); // // Highgui.imwrite(new File(mStorageDir, "mDiff.png").toString(), mDiff); // Highgui.imwrite(new File(mStorageDir, "hsva.png").toString(), hsva); // Highgui.imwrite(new File(mStorageDir, "hsvb.png").toString(), hsvb); // Highgui.imwrite(new File(mStorageDir, "mRgba.png").toString(), mRgba); // Highgui.imwrite(new File(mStorageDir, "mEmptyTrack.png").toString(), mEmptyTrack); // for(int x = x_offset_right;x< x_offset_right +30;x++){ // for (int y = y_offset_right;y < y_offset_right+30;y++){ // Log.i("debug", "x_offset(col): "+x); // Log.i("debug", "y_offset(row): "+y); // mEmptyTrackPixelColor = mEmptyTrack.get(y, x); // mScannedTrackPixelColor = mRgba.get(y, x); // // double min = 256; // double max = -1; // // for(int k = 0; k < 3; k++) { // if(mScannedTrackPixelColor[k] < min) // min = mScannedTrackPixelColor[k]; // if(mScannedTrackPixelColor[k] > max) // max = mScannedTrackPixelColor[k]; // } // // double min2 = 256; // double max2 = -1; // // for(int k = 0; k < 3; k++) { // if(mEmptyTrackPixelColor[k] < min2) // min2 = mEmptyTrackPixelColor[k]; // if(mEmptyTrackPixelColor[k] > max2) // max2 = mEmptyTrackPixelColor[k]; // } // // if((max - min) > (max2 - min2) + 10){ // mRgba.put(y, x, new double[]{0,0,255,255}); // mFoundColors.add(mScannedTrackPixelColor); // } // } // } // int counter_right = 0; // int blue_right = 0; // int yellow_right = 0; // int red_right = 0; // for(double[] d : mFoundColors){ // counter_right++; // blue_right += d[0]; // yellow_right += d[1]; // red_right += d[2]; // } // if(counter_right == 0) // mColorsOnRightLane = false; // else{ // mColorsOnRightLane = true; // Scalar right_car_color = new Scalar(red_right/counter_right,yellow_right/counter_right, blue_right/counter_right,255); // mRightCarColor = new Mat(getLanesToScanColor()[0].x,getLanesToScanColor()[0].y, mInputFramePortrait.type(),right_car_color); // mRightCarColorImage = Bitmap.createBitmap(mRightCarColor.cols(), mRightCarColor.rows(), Bitmap.Config.ARGB_8888); // Utils.matToBitmap(mRightCarColor, mRightCarColorImage); // mCarColorImages[1] = mRightCarColorImage; // mFoundColors.clear(); // } // for(double[] d: foundcolors) // Log.i("debug","Different Colors: "+d[0]+", "+d[1]+", "+d[2]); // mHSV = new Mat(); // mLowerRangeImage = new Mat(); // mUpperRangeImage = new Mat(); // mThreshed = new Mat(); // Imgproc.cvtColor(mEmptyTrack, mHSV, Imgproc.COLOR_BGR2HSV); // double[] rgba = null; // double R, G, B, A; // double RCount = 0; // double GCount = 0; // double BCount = 0; // double ACount = 0; // double avgR = 0; // double avgG = 0; // double avgB = 0; // double avgA = 0; // // double divider = 0; // for (int i = 0; i < mHSV.rows(); i++) { // for (int j = 0; j < mHSV.cols(); j++) { // if (rgba != null) // rgba = null; // rgba = mEmptyTrack.get(i, j); // R = rgba[0]; // G = rgba[1]; // B = rgba[2]; // A = rgba[3]; // divider++; // RCount += R; // GCount += G; // BCount += B; // ACount += A; // // } // // } // avgR = RCount /divider; // avgG = GCount /divider; // avgB = BCount/divider; // avgA = ACount/ divider; // Log.i("debug", "avg R: "+avgR); // Log.i("debug", "avg G: "+avgG); // Log.i("debug", "avg B: "+avgB); // Log.i("debug", "avg Alpha: "+avgA); // // // Core.inRange(mHSV, new Scalar(0,0,0), new Scalar(avgR-10,1,1), mLowerRangeImage); // Core.inRange(mHSV, new Scalar(avgR+10,0,0), new Scalar(255,1,1), mUpperRangeImage); // Core.add(mLowerRangeImage, mUpperRangeImage, mThreshed); // // mTrackColor = new File(mStorageDir, "track.png"); // mPath = mTrackColor.toString(); // Boolean bool = Highgui.imwrite(mPath, mThreshed); // if (bool) // Log.i("debug", "SUCCESS writing track.png to external storage"); // else // Log.i("debug", "Fail writing track.png to external storage"); // //Hier muss ein Bild mit den Fahrzeugen auf dem Streckenausschnitt ankommen //Dann werden die Positionen gesetzt. } }
true
true
public Bitmap generate_track_overlay() { // Load an Image to try operations on local stored files mFoundSeparatorLine = false; mFoundUpperLine = false; mFoundLowerLine = false; mGray = new Mat(); mEdges = new Mat(); mHoughLines = new Mat(); mEmptyTrack = new Mat(); mStaticImage = Highgui .imread(Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "track.jpg"); track_overlay = new Mat(new Size(mInputFramePortrait.cols(), mInputFramePortrait .rows()), mInputFramePortrait.type(), new Scalar(0, 0, 0, 0)); Log.i("debug", "Channels: " + track_overlay.channels()); Imgproc.cvtColor(mInputFramePortrait, mGray, Imgproc.COLOR_RGBA2GRAY); double[] grays = null; double wert; double count = 0; double divider = 0; for (int i = 0; i < mGray.rows(); i++) { for (int j = 0; j < mGray.cols(); j++) { if (grays != null) grays = null; grays = mGray.get(i, j); wert = grays[0]; divider++; count = count + wert; } } avg_gray = (int) (count / divider); Log.i("debug", "avg_gray: " + avg_gray); mLowerThreshold = (int) (avg_gray * 0.66); mUpperThreshold = (int) (avg_gray * 1.33); Imgproc.Canny(mGray, mEdges, mLowerThreshold, mUpperThreshold); //mGray.release(); // Highgui.imwrite("/houghlines.png", mHoughLines); Log.i("debug", "Status Sd-Karte: " + Environment.getExternalStorageState()); mStorageDir = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); // mCannyEdgeImage = new File(mStorageDir, "canny.bmp"); // mPath = mCannyEdgeImage.toString(); // Boolean bool = Highgui.imwrite(mPath, mEdges); // if (bool) // Log.i("debug", "SUCCESS writing canny.bmp to external storage"); // else // Log.i("debug", "Fail writing canny.bmp to external storage"); if((!mEdges.empty() && !mInputFramePortrait.empty())) { Imgproc.HoughLinesP(mEdges, mHoughLines, 1, Math.PI / 180, mHLthreshold, mHLminLineSize, mHLlineGap); for (int x = 0; x < mHoughLines.cols(); x++) { double[] vec = mHoughLines.get(0, x); double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3]; if (x1 > mInputFramePortrait.cols() / 2 - 30 && x1 < mInputFramePortrait.cols() / 2 + 30 && x2 > mInputFramePortrait.cols() / 2 - 30 && x2 < mInputFramePortrait.cols() / 2 + 30) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mSeparatorPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundSeparatorLine = true; } else if(x1 < 50 && x2 < 50) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mUpperPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundUpperLine = true; } else if(x1 > mInputFramePortrait.cols() - 50 && x2 > mInputFramePortrait.cols() - 50) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mLowerPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundLowerLine = true; } } mTrackOverlay = Bitmap.createBitmap(track_overlay.cols(), track_overlay.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(track_overlay, mTrackOverlay); mInputFramePortrait.copyTo(mEmptyTrack); } //mHoughLinesImage = new File(mStorageDir, "houghed.png"); //mPath = mHoughLinesImage.toString(); //Highgui.imwrite(mPath, track_overlay); //Getting average color for every lane double[] rgba = null; double R, G, B, A; double RCount = 0; double GCount = 0; double BCount = 0; double ACount = 0; double avgR = 0; double avgG = 0; double avgB = 0; double avgA = 0; //Upper lane // if(mFoundUpperLine){ // for(int i = ((int)mUpperPoint.y+10); i < mSeparatorPoint.y-10; i++){ // for (int j = 0;j < mEmptyTrack.cols();j++){ // if (rgba != null) // rgba = null; // rgba = mEmptyTrack.get(i, j); // R = rgba[0]; // G = rgba[1]; // B = rgba[2]; // A = rgba[3]; // divider++; // RCount += R; // GCount += G; // BCount += B; // ACount += A; // } // } // // mUpperLaneColor = new Scalar(avgR,avgG,avgB,avgA); // avgR = RCount /divider; // avgG = GCount /divider; // avgB = BCount/divider; // avgA = ACount/ divider; // Log.i("debug", "Start: "+mUpperPoint.y); // Log.i("debug", "Ende: "+mSeparatorPoint.y); // Log.i("debug", "UPPER LANE: "); // Log.i("debug", "avg R: "+avgR); // Log.i("debug", "avg G: "+avgG); // Log.i("debug", "avg B: "+avgB); // Log.i("debug", "avg Alpha: "+avgA); // // } // //Lower lane // //TODO Null Pointer Exception when line was found before --> but other lines not and then when this line not found this option is still true from before // if(mFoundLowerLine){ // for(int i = ((int)mLowerPoint.y-10); i > mSeparatorPoint.y+10; i--){ // for (int j = 0;j < mEmptyTrack.cols();j++){ // if (rgba != null) // rgba = null; // rgba = mEmptyTrack.get(i, j); // R = rgba[0]; // G = rgba[1]; // B = rgba[2]; // A = rgba[3]; // divider++; // RCount += R; // GCount += G; // BCount += B; // ACount += A; // } // } // // mLowerLaneColor = new Scalar(avgR,avgG,avgB,avgA); // avgR = RCount /divider; // avgG = GCount /divider; // avgB = BCount/divider; // avgA = ACount/ divider; // Log.i("debug", "Start: "+mLowerPoint.y); // Log.i("debug", "Ende: "+mSeparatorPoint.y); // Log.i("debug", "LOWER LANE: "); // Log.i("debug", "avg R: "+avgR); // Log.i("debug", "avg G: "+avgG); // Log.i("debug", "avg B: "+avgB); // Log.i("debug", "avg Alpha: "+avgA); // } //Core.flip(track_overlay.t(), track_overlay, 1); return mTrackOverlay; }
public Bitmap generate_track_overlay() { // Load an Image to try operations on local stored files mFoundSeparatorLine = false; mFoundUpperLine = false; mFoundLowerLine = false; mGray = new Mat(); mEdges = new Mat(); mHoughLines = new Mat(); mEmptyTrack = new Mat(); mStaticImage = Highgui .imread(Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "track.jpg"); track_overlay = new Mat(new Size(mInputFramePortrait.cols(), mInputFramePortrait .rows()), mInputFramePortrait.type(), new Scalar(0, 0, 0, 0)); Log.i("debug", "Channels: " + track_overlay.channels()); Imgproc.cvtColor(mInputFramePortrait, mGray, Imgproc.COLOR_RGBA2GRAY); double[] grays = null; double wert; double count = 0; double divider = 0; for (int i = 0; i < mGray.rows(); i++) { for (int j = 0; j < mGray.cols(); j++) { if (grays != null) grays = null; grays = mGray.get(i, j); wert = grays[0]; divider++; count = count + wert; } } avg_gray = (int) (count / divider); Log.i("debug", "avg_gray: " + avg_gray); mLowerThreshold = (int) (avg_gray * 0.66); mUpperThreshold = (int) (avg_gray * 1.33); Imgproc.Canny(mGray, mEdges, mLowerThreshold, mUpperThreshold); //mGray.release(); // Highgui.imwrite("/houghlines.png", mHoughLines); Log.i("debug","Status Sd-Karte: "+ Environment.getExternalStorageState()); mStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); // mCannyEdgeImage = new File(mStorageDir, "canny.bmp"); // mPath = mCannyEdgeImage.toString(); // Boolean bool = Highgui.imwrite(mPath, mEdges); // if (bool) // Log.i("debug", "SUCCESS writing canny.bmp to external storage"); // else // Log.i("debug", "Fail writing canny.bmp to external storage"); if((!mEdges.empty() && !mInputFramePortrait.empty())) { Imgproc.HoughLinesP(mEdges, mHoughLines, 1, Math.PI / 180, mHLthreshold, mHLminLineSize, mHLlineGap); for (int x = 0; x < mHoughLines.cols(); x++) { double[] vec = mHoughLines.get(0, x); double x1 = vec[0], y1 = vec[1], x2 = vec[2], y2 = vec[3]; if (x1 > mInputFramePortrait.cols() / 2 - 30 && x1 < mInputFramePortrait.cols() / 2 + 30 && x2 > mInputFramePortrait.cols() / 2 - 30 && x2 < mInputFramePortrait.cols() / 2 + 30) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mSeparatorPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundSeparatorLine = true; } else if(x1 < 50 && x2 < 50) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mUpperPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundUpperLine = true; } else if(x1 > mInputFramePortrait.cols() - 50 && x2 > mInputFramePortrait.cols() - 50) { Point start = new Point(x1, y1); Point end = new Point(x2, y2); Core.line(track_overlay, start, end,new Scalar(0, 0, 255, 255), 3); mLowerPoint = new Point(x1,y1); mDrawedLinesOnFrame = true; mFoundLowerLine = true; } } mTrackOverlay = Bitmap.createBitmap(track_overlay.cols(), track_overlay.rows(), Bitmap.Config.ARGB_8888); Utils.matToBitmap(track_overlay, mTrackOverlay); mInputFramePortrait.copyTo(mEmptyTrack); } //mHoughLinesImage = new File(mStorageDir, "houghed.png"); //mPath = mHoughLinesImage.toString(); //Highgui.imwrite(mPath, track_overlay); //Getting average color for every lane double[] rgba = null; double R, G, B, A; double RCount = 0; double GCount = 0; double BCount = 0; double ACount = 0; double avgR = 0; double avgG = 0; double avgB = 0; double avgA = 0; //Upper lane // if(mFoundUpperLine){ // for(int i = ((int)mUpperPoint.y+10); i < mSeparatorPoint.y-10; i++){ // for (int j = 0;j < mEmptyTrack.cols();j++){ // if (rgba != null) // rgba = null; // rgba = mEmptyTrack.get(i, j); // R = rgba[0]; // G = rgba[1]; // B = rgba[2]; // A = rgba[3]; // divider++; // RCount += R; // GCount += G; // BCount += B; // ACount += A; // } // } // // mUpperLaneColor = new Scalar(avgR,avgG,avgB,avgA); // avgR = RCount /divider; // avgG = GCount /divider; // avgB = BCount/divider; // avgA = ACount/ divider; // Log.i("debug", "Start: "+mUpperPoint.y); // Log.i("debug", "Ende: "+mSeparatorPoint.y); // Log.i("debug", "UPPER LANE: "); // Log.i("debug", "avg R: "+avgR); // Log.i("debug", "avg G: "+avgG); // Log.i("debug", "avg B: "+avgB); // Log.i("debug", "avg Alpha: "+avgA); // // } // //Lower lane // //TODO Null Pointer Exception when line was found before --> but other lines not and then when this line not found this option is still true from before // if(mFoundLowerLine){ // for(int i = ((int)mLowerPoint.y-10); i > mSeparatorPoint.y+10; i--){ // for (int j = 0;j < mEmptyTrack.cols();j++){ // if (rgba != null) // rgba = null; // rgba = mEmptyTrack.get(i, j); // R = rgba[0]; // G = rgba[1]; // B = rgba[2]; // A = rgba[3]; // divider++; // RCount += R; // GCount += G; // BCount += B; // ACount += A; // } // } // // mLowerLaneColor = new Scalar(avgR,avgG,avgB,avgA); // avgR = RCount /divider; // avgG = GCount /divider; // avgB = BCount/divider; // avgA = ACount/ divider; // Log.i("debug", "Start: "+mLowerPoint.y); // Log.i("debug", "Ende: "+mSeparatorPoint.y); // Log.i("debug", "LOWER LANE: "); // Log.i("debug", "avg R: "+avgR); // Log.i("debug", "avg G: "+avgG); // Log.i("debug", "avg B: "+avgB); // Log.i("debug", "avg Alpha: "+avgA); // } //Core.flip(track_overlay.t(), track_overlay, 1); return mTrackOverlay; }
diff --git a/modules/rampart-core/src/main/java/org/apache/rampart/handler/WSDoAllReceiver.java b/modules/rampart-core/src/main/java/org/apache/rampart/handler/WSDoAllReceiver.java index 3c34f78b8..4b8548fef 100644 --- a/modules/rampart-core/src/main/java/org/apache/rampart/handler/WSDoAllReceiver.java +++ b/modules/rampart-core/src/main/java/org/apache/rampart/handler/WSDoAllReceiver.java @@ -1,383 +1,383 @@ /* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rampart.handler; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axiom.soap.SOAPHeader; import org.apache.axiom.soap.SOAPHeaderBlock; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.addressing.AddressingConstants; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.OperationContext; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.rampart.RampartConstants; import org.apache.rampart.util.Axis2Util; import org.apache.rampart.util.HandlerParameterDecoder; import org.apache.ws.security.SOAPConstants; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSSecurityEngineResult; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.handler.RequestData; import org.apache.ws.security.handler.WSHandlerConstants; import org.apache.ws.security.handler.WSHandlerResult; import org.apache.ws.security.message.token.Timestamp; import org.apache.ws.security.util.WSSecurityUtil; import org.w3c.dom.Document; import javax.security.auth.callback.CallbackHandler; import javax.xml.namespace.QName; import java.security.cert.X509Certificate; import java.util.Iterator; import java.util.Vector; /** * @deprecated */ public class WSDoAllReceiver extends WSDoAllHandler { private static final Log log = LogFactory.getLog(WSDoAllReceiver.class); private static Log mlog = LogFactory.getLog(RampartConstants.MESSAGE_LOG); public WSDoAllReceiver() { super(); inHandler = true; } public void processMessage(MessageContext msgContext) throws AxisFault { if(mlog.isDebugEnabled()){ mlog.debug("*********************** WSDoAllReceiver recieved \n"+msgContext.getEnvelope()); } boolean doDebug = log.isDebugEnabled(); if (doDebug) { log.debug("WSDoAllReceiver: enter invoke() "); } String useDoomValue = (String) getProperty(msgContext, WSSHandlerConstants.USE_DOOM); boolean useDoom = useDoomValue != null && Constants.VALUE_TRUE.equalsIgnoreCase(useDoomValue); RequestData reqData = new RequestData(); try { this.processBasic(msgContext, useDoom, reqData); } catch (AxisFault axisFault) { setAddressingInformationOnFault(msgContext); throw axisFault; } catch (Exception e) { setAddressingInformationOnFault(msgContext); throw new AxisFault(e.getMessage(), e); } finally { if (reqData != null) { reqData.clear(); reqData = null; } if (doDebug) { log.debug("WSDoAllReceiver: exit invoke()"); } } } private void processBasic(MessageContext msgContext, boolean useDoom, RequestData reqData) throws Exception { // populate the properties try { HandlerParameterDecoder.processParameters(msgContext, true); } catch (Exception e) { throw new AxisFault("Configuration error", e); } reqData = new RequestData(); reqData.setMsgContext(msgContext); if (((getOption(WSSHandlerConstants.INFLOW_SECURITY)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY)) == null)) { if (msgContext.isServerSide() && ((getOption(WSSHandlerConstants.INFLOW_SECURITY_SERVER)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY_SERVER)) == null)) { return; } else if (((getOption(WSSHandlerConstants.INFLOW_SECURITY_CLIENT)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY_CLIENT)) == null)) { return; } } Vector actions = new Vector(); String action = null; if ((action = (String) getOption(WSSHandlerConstants.ACTION_ITEMS)) == null) { action = (String) getProperty(msgContext, WSSHandlerConstants.ACTION_ITEMS); } if (action == null) { throw new AxisFault("WSDoAllReceiver: No action items defined"); } int doAction = WSSecurityUtil.decodeAction(action, actions); if (doAction == WSConstants.NO_SECURITY) { return; } String actor = (String) getOption(WSHandlerConstants.ACTOR); Document doc = null; try { doc = Axis2Util.getDocumentFromSOAPEnvelope(msgContext .getEnvelope(), useDoom); } catch (WSSecurityException wssEx) { throw new AxisFault( "WSDoAllReceiver: Error in converting to Document", wssEx); } // Do not process faults SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc .getDocumentElement()); if (WSSecurityUtil.findElement(doc.getDocumentElement(), "Fault", soapConstants.getEnvelopeURI()) != null) { return; } /* * To check a UsernameToken or to decrypt an encrypted message we need a * password. */ CallbackHandler cbHandler = null; if ((doAction & (WSConstants.ENCR | WSConstants.UT)) != 0) { cbHandler = getPasswordCB(reqData); } // Copy the WSHandlerConstants.SEND_SIGV over to the new message // context - if it exists, if signatureConfirmation in the response msg String sigConfEnabled = null; if ((sigConfEnabled = (String) getOption(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION)) == null) { sigConfEnabled = (String) getProperty(msgContext, WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION); } // To handle sign confirmation of a sync response // TODO Async response if (!msgContext.isServerSide() && !"false".equalsIgnoreCase(sigConfEnabled)) { OperationContext opCtx = msgContext.getOperationContext(); MessageContext outMsgCtx = opCtx .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); if (outMsgCtx != null) { msgContext.setProperty(WSHandlerConstants.SEND_SIGV, outMsgCtx .getProperty(WSHandlerConstants.SEND_SIGV)); } else { throw new WSSecurityException( "Cannot obtain request message context"); } } /* * Get and check the Signature specific parameters first because they * may be used for encryption too. */ doReceiverAction(doAction, reqData); Vector wsResult = null; try { wsResult = secEngine.processSecurityHeader(doc, actor, cbHandler, reqData.getSigCrypto(), reqData.getDecCrypto()); } catch (WSSecurityException ex) { throw new AxisFault("WSDoAllReceiver: security processing failed", ex); } if (wsResult == null) { // no security header found if (doAction == WSConstants.NO_SECURITY) { return; } else { throw new AxisFault( "WSDoAllReceiver: Incoming message does not contain required Security header"); } } if (reqData.getWssConfig().isEnableSignatureConfirmation() && !msgContext.isServerSide()) { checkSignatureConfirmation(reqData, wsResult); } /** * Set the new SOAPEnvelope */ msgContext.setEnvelope(Axis2Util.getSOAPEnvelopeFromDOMDocument(doc, useDoom)); /* * After setting the new current message, probably modified because of * decryption, we need to locate the security header. That is, we force * Axis (with getSOAPEnvelope()) to parse the string, build the new * header. Then we examine, look up the security header and set the * header as processed. * * Please note: find all header elements that contain the same actor * that was given to processSecurityHeader(). Then check if there is a * security header with this actor. */ SOAPHeader header = null; try { header = msgContext.getEnvelope().getHeader(); } catch (OMException ex) { throw new AxisFault( "WSDoAllReceiver: cannot get SOAP header after security processing", ex); } Iterator headers = header.examineHeaderBlocks(actor); SOAPHeaderBlock headerBlock = null; while (headers.hasNext()) { // Find the wsse header SOAPHeaderBlock hb = (SOAPHeaderBlock) headers.next(); if (hb.getLocalName().equals(WSConstants.WSSE_LN) && hb.getNamespace().getNamespaceURI().equals(WSConstants.WSSE_NS)) { headerBlock = hb; break; } } headerBlock.setProcessed(); /* * Now we can check the certificate used to sign the message. In the * following implementation the certificate is only trusted if either it * itself or the certificate of the issuer is installed in the keystore. * * Note: the method verifyTrust(X509Certificate) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the signature action result from the action vector WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult( wsResult, WSConstants.SIGN); if (actionResult != null) { X509Certificate returnCert = actionResult.getCertificate(); if (returnCert != null) { if (!verifyTrust(returnCert, reqData)) { throw new AxisFault( "WSDoAllReceiver: The certificate used for the signature is not trusted"); } } } /* * Perform further checks on the timestamp that was transmitted in the * header. In the following implementation the timestamp is valid if it * was created after (now-ttl), where ttl is set on server side, not by * the client. * * Note: the method verifyTimestamp(Timestamp) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the timestamp action result from the action vector actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS); if (actionResult != null) { Timestamp timestamp = actionResult.getTimestamp(); if (timestamp != null) { String ttl = null; if ((ttl = (String) getOption(WSHandlerConstants.TTL_TIMESTAMP)) == null) { ttl = (String) getProperty(msgContext, WSHandlerConstants.TTL_TIMESTAMP); } int ttl_i = 0; if (ttl != null) { try { ttl_i = Integer.parseInt(ttl); } catch (NumberFormatException e) { ttl_i = reqData.getTimeToLive(); } } if (ttl_i <= 0) { ttl_i = reqData.getTimeToLive(); } - if (!verifyTimestamp(timestamp, reqData.getTimeToLive())) { + if (!verifyTimestamp(timestamp, ttl_i)) { throw new AxisFault( "WSDoAllReceiver: The timestamp could not be validated"); } } } /* * now check the security actions: do they match, in right order? */ if (!checkReceiverResults(wsResult, actions)) { throw new AxisFault( "WSDoAllReceiver: security processing failed (actions mismatch)"); } /* * All ok up to this point. Now construct and setup the security result * structure. The service may fetch this and check it. Also the * DoAllSender will use this in certain situations such as: * USE_REQ_SIG_CERT to encrypt */ Vector results = null; if ((results = (Vector) getProperty(msgContext, WSHandlerConstants.RECV_RESULTS)) == null) { results = new Vector(); msgContext.setProperty(WSHandlerConstants.RECV_RESULTS, results); } WSHandlerResult rResult = new WSHandlerResult(actor, wsResult); results.add(0, rResult); } private void setAddressingInformationOnFault(MessageContext msgContext) { SOAPEnvelope env = msgContext.getEnvelope(); SOAPHeader header = env.getHeader(); if (header != null) { OMElement msgIdElem = header.getFirstChildWithName(new QName( AddressingConstants.Final.WSA_NAMESPACE, AddressingConstants.WSA_MESSAGE_ID)); if (msgIdElem == null) { msgIdElem = header.getFirstChildWithName(new QName( AddressingConstants.Submission.WSA_NAMESPACE, AddressingConstants.WSA_MESSAGE_ID)); } if (msgIdElem != null && msgIdElem.getText() != null) { msgContext.getOptions().setMessageId(msgIdElem.getText()); } } } }
true
true
private void processBasic(MessageContext msgContext, boolean useDoom, RequestData reqData) throws Exception { // populate the properties try { HandlerParameterDecoder.processParameters(msgContext, true); } catch (Exception e) { throw new AxisFault("Configuration error", e); } reqData = new RequestData(); reqData.setMsgContext(msgContext); if (((getOption(WSSHandlerConstants.INFLOW_SECURITY)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY)) == null)) { if (msgContext.isServerSide() && ((getOption(WSSHandlerConstants.INFLOW_SECURITY_SERVER)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY_SERVER)) == null)) { return; } else if (((getOption(WSSHandlerConstants.INFLOW_SECURITY_CLIENT)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY_CLIENT)) == null)) { return; } } Vector actions = new Vector(); String action = null; if ((action = (String) getOption(WSSHandlerConstants.ACTION_ITEMS)) == null) { action = (String) getProperty(msgContext, WSSHandlerConstants.ACTION_ITEMS); } if (action == null) { throw new AxisFault("WSDoAllReceiver: No action items defined"); } int doAction = WSSecurityUtil.decodeAction(action, actions); if (doAction == WSConstants.NO_SECURITY) { return; } String actor = (String) getOption(WSHandlerConstants.ACTOR); Document doc = null; try { doc = Axis2Util.getDocumentFromSOAPEnvelope(msgContext .getEnvelope(), useDoom); } catch (WSSecurityException wssEx) { throw new AxisFault( "WSDoAllReceiver: Error in converting to Document", wssEx); } // Do not process faults SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc .getDocumentElement()); if (WSSecurityUtil.findElement(doc.getDocumentElement(), "Fault", soapConstants.getEnvelopeURI()) != null) { return; } /* * To check a UsernameToken or to decrypt an encrypted message we need a * password. */ CallbackHandler cbHandler = null; if ((doAction & (WSConstants.ENCR | WSConstants.UT)) != 0) { cbHandler = getPasswordCB(reqData); } // Copy the WSHandlerConstants.SEND_SIGV over to the new message // context - if it exists, if signatureConfirmation in the response msg String sigConfEnabled = null; if ((sigConfEnabled = (String) getOption(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION)) == null) { sigConfEnabled = (String) getProperty(msgContext, WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION); } // To handle sign confirmation of a sync response // TODO Async response if (!msgContext.isServerSide() && !"false".equalsIgnoreCase(sigConfEnabled)) { OperationContext opCtx = msgContext.getOperationContext(); MessageContext outMsgCtx = opCtx .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); if (outMsgCtx != null) { msgContext.setProperty(WSHandlerConstants.SEND_SIGV, outMsgCtx .getProperty(WSHandlerConstants.SEND_SIGV)); } else { throw new WSSecurityException( "Cannot obtain request message context"); } } /* * Get and check the Signature specific parameters first because they * may be used for encryption too. */ doReceiverAction(doAction, reqData); Vector wsResult = null; try { wsResult = secEngine.processSecurityHeader(doc, actor, cbHandler, reqData.getSigCrypto(), reqData.getDecCrypto()); } catch (WSSecurityException ex) { throw new AxisFault("WSDoAllReceiver: security processing failed", ex); } if (wsResult == null) { // no security header found if (doAction == WSConstants.NO_SECURITY) { return; } else { throw new AxisFault( "WSDoAllReceiver: Incoming message does not contain required Security header"); } } if (reqData.getWssConfig().isEnableSignatureConfirmation() && !msgContext.isServerSide()) { checkSignatureConfirmation(reqData, wsResult); } /** * Set the new SOAPEnvelope */ msgContext.setEnvelope(Axis2Util.getSOAPEnvelopeFromDOMDocument(doc, useDoom)); /* * After setting the new current message, probably modified because of * decryption, we need to locate the security header. That is, we force * Axis (with getSOAPEnvelope()) to parse the string, build the new * header. Then we examine, look up the security header and set the * header as processed. * * Please note: find all header elements that contain the same actor * that was given to processSecurityHeader(). Then check if there is a * security header with this actor. */ SOAPHeader header = null; try { header = msgContext.getEnvelope().getHeader(); } catch (OMException ex) { throw new AxisFault( "WSDoAllReceiver: cannot get SOAP header after security processing", ex); } Iterator headers = header.examineHeaderBlocks(actor); SOAPHeaderBlock headerBlock = null; while (headers.hasNext()) { // Find the wsse header SOAPHeaderBlock hb = (SOAPHeaderBlock) headers.next(); if (hb.getLocalName().equals(WSConstants.WSSE_LN) && hb.getNamespace().getNamespaceURI().equals(WSConstants.WSSE_NS)) { headerBlock = hb; break; } } headerBlock.setProcessed(); /* * Now we can check the certificate used to sign the message. In the * following implementation the certificate is only trusted if either it * itself or the certificate of the issuer is installed in the keystore. * * Note: the method verifyTrust(X509Certificate) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the signature action result from the action vector WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult( wsResult, WSConstants.SIGN); if (actionResult != null) { X509Certificate returnCert = actionResult.getCertificate(); if (returnCert != null) { if (!verifyTrust(returnCert, reqData)) { throw new AxisFault( "WSDoAllReceiver: The certificate used for the signature is not trusted"); } } } /* * Perform further checks on the timestamp that was transmitted in the * header. In the following implementation the timestamp is valid if it * was created after (now-ttl), where ttl is set on server side, not by * the client. * * Note: the method verifyTimestamp(Timestamp) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the timestamp action result from the action vector actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS); if (actionResult != null) { Timestamp timestamp = actionResult.getTimestamp(); if (timestamp != null) { String ttl = null; if ((ttl = (String) getOption(WSHandlerConstants.TTL_TIMESTAMP)) == null) { ttl = (String) getProperty(msgContext, WSHandlerConstants.TTL_TIMESTAMP); } int ttl_i = 0; if (ttl != null) { try { ttl_i = Integer.parseInt(ttl); } catch (NumberFormatException e) { ttl_i = reqData.getTimeToLive(); } } if (ttl_i <= 0) { ttl_i = reqData.getTimeToLive(); } if (!verifyTimestamp(timestamp, reqData.getTimeToLive())) { throw new AxisFault( "WSDoAllReceiver: The timestamp could not be validated"); } } } /* * now check the security actions: do they match, in right order? */ if (!checkReceiverResults(wsResult, actions)) { throw new AxisFault( "WSDoAllReceiver: security processing failed (actions mismatch)"); } /* * All ok up to this point. Now construct and setup the security result * structure. The service may fetch this and check it. Also the * DoAllSender will use this in certain situations such as: * USE_REQ_SIG_CERT to encrypt */ Vector results = null; if ((results = (Vector) getProperty(msgContext, WSHandlerConstants.RECV_RESULTS)) == null) { results = new Vector(); msgContext.setProperty(WSHandlerConstants.RECV_RESULTS, results); } WSHandlerResult rResult = new WSHandlerResult(actor, wsResult); results.add(0, rResult); }
private void processBasic(MessageContext msgContext, boolean useDoom, RequestData reqData) throws Exception { // populate the properties try { HandlerParameterDecoder.processParameters(msgContext, true); } catch (Exception e) { throw new AxisFault("Configuration error", e); } reqData = new RequestData(); reqData.setMsgContext(msgContext); if (((getOption(WSSHandlerConstants.INFLOW_SECURITY)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY)) == null)) { if (msgContext.isServerSide() && ((getOption(WSSHandlerConstants.INFLOW_SECURITY_SERVER)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY_SERVER)) == null)) { return; } else if (((getOption(WSSHandlerConstants.INFLOW_SECURITY_CLIENT)) == null) && ((getProperty(msgContext, WSSHandlerConstants.INFLOW_SECURITY_CLIENT)) == null)) { return; } } Vector actions = new Vector(); String action = null; if ((action = (String) getOption(WSSHandlerConstants.ACTION_ITEMS)) == null) { action = (String) getProperty(msgContext, WSSHandlerConstants.ACTION_ITEMS); } if (action == null) { throw new AxisFault("WSDoAllReceiver: No action items defined"); } int doAction = WSSecurityUtil.decodeAction(action, actions); if (doAction == WSConstants.NO_SECURITY) { return; } String actor = (String) getOption(WSHandlerConstants.ACTOR); Document doc = null; try { doc = Axis2Util.getDocumentFromSOAPEnvelope(msgContext .getEnvelope(), useDoom); } catch (WSSecurityException wssEx) { throw new AxisFault( "WSDoAllReceiver: Error in converting to Document", wssEx); } // Do not process faults SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc .getDocumentElement()); if (WSSecurityUtil.findElement(doc.getDocumentElement(), "Fault", soapConstants.getEnvelopeURI()) != null) { return; } /* * To check a UsernameToken or to decrypt an encrypted message we need a * password. */ CallbackHandler cbHandler = null; if ((doAction & (WSConstants.ENCR | WSConstants.UT)) != 0) { cbHandler = getPasswordCB(reqData); } // Copy the WSHandlerConstants.SEND_SIGV over to the new message // context - if it exists, if signatureConfirmation in the response msg String sigConfEnabled = null; if ((sigConfEnabled = (String) getOption(WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION)) == null) { sigConfEnabled = (String) getProperty(msgContext, WSHandlerConstants.ENABLE_SIGNATURE_CONFIRMATION); } // To handle sign confirmation of a sync response // TODO Async response if (!msgContext.isServerSide() && !"false".equalsIgnoreCase(sigConfEnabled)) { OperationContext opCtx = msgContext.getOperationContext(); MessageContext outMsgCtx = opCtx .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); if (outMsgCtx != null) { msgContext.setProperty(WSHandlerConstants.SEND_SIGV, outMsgCtx .getProperty(WSHandlerConstants.SEND_SIGV)); } else { throw new WSSecurityException( "Cannot obtain request message context"); } } /* * Get and check the Signature specific parameters first because they * may be used for encryption too. */ doReceiverAction(doAction, reqData); Vector wsResult = null; try { wsResult = secEngine.processSecurityHeader(doc, actor, cbHandler, reqData.getSigCrypto(), reqData.getDecCrypto()); } catch (WSSecurityException ex) { throw new AxisFault("WSDoAllReceiver: security processing failed", ex); } if (wsResult == null) { // no security header found if (doAction == WSConstants.NO_SECURITY) { return; } else { throw new AxisFault( "WSDoAllReceiver: Incoming message does not contain required Security header"); } } if (reqData.getWssConfig().isEnableSignatureConfirmation() && !msgContext.isServerSide()) { checkSignatureConfirmation(reqData, wsResult); } /** * Set the new SOAPEnvelope */ msgContext.setEnvelope(Axis2Util.getSOAPEnvelopeFromDOMDocument(doc, useDoom)); /* * After setting the new current message, probably modified because of * decryption, we need to locate the security header. That is, we force * Axis (with getSOAPEnvelope()) to parse the string, build the new * header. Then we examine, look up the security header and set the * header as processed. * * Please note: find all header elements that contain the same actor * that was given to processSecurityHeader(). Then check if there is a * security header with this actor. */ SOAPHeader header = null; try { header = msgContext.getEnvelope().getHeader(); } catch (OMException ex) { throw new AxisFault( "WSDoAllReceiver: cannot get SOAP header after security processing", ex); } Iterator headers = header.examineHeaderBlocks(actor); SOAPHeaderBlock headerBlock = null; while (headers.hasNext()) { // Find the wsse header SOAPHeaderBlock hb = (SOAPHeaderBlock) headers.next(); if (hb.getLocalName().equals(WSConstants.WSSE_LN) && hb.getNamespace().getNamespaceURI().equals(WSConstants.WSSE_NS)) { headerBlock = hb; break; } } headerBlock.setProcessed(); /* * Now we can check the certificate used to sign the message. In the * following implementation the certificate is only trusted if either it * itself or the certificate of the issuer is installed in the keystore. * * Note: the method verifyTrust(X509Certificate) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the signature action result from the action vector WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult( wsResult, WSConstants.SIGN); if (actionResult != null) { X509Certificate returnCert = actionResult.getCertificate(); if (returnCert != null) { if (!verifyTrust(returnCert, reqData)) { throw new AxisFault( "WSDoAllReceiver: The certificate used for the signature is not trusted"); } } } /* * Perform further checks on the timestamp that was transmitted in the * header. In the following implementation the timestamp is valid if it * was created after (now-ttl), where ttl is set on server side, not by * the client. * * Note: the method verifyTimestamp(Timestamp) allows custom * implementations with other validation algorithms for subclasses. */ // Extract the timestamp action result from the action vector actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS); if (actionResult != null) { Timestamp timestamp = actionResult.getTimestamp(); if (timestamp != null) { String ttl = null; if ((ttl = (String) getOption(WSHandlerConstants.TTL_TIMESTAMP)) == null) { ttl = (String) getProperty(msgContext, WSHandlerConstants.TTL_TIMESTAMP); } int ttl_i = 0; if (ttl != null) { try { ttl_i = Integer.parseInt(ttl); } catch (NumberFormatException e) { ttl_i = reqData.getTimeToLive(); } } if (ttl_i <= 0) { ttl_i = reqData.getTimeToLive(); } if (!verifyTimestamp(timestamp, ttl_i)) { throw new AxisFault( "WSDoAllReceiver: The timestamp could not be validated"); } } } /* * now check the security actions: do they match, in right order? */ if (!checkReceiverResults(wsResult, actions)) { throw new AxisFault( "WSDoAllReceiver: security processing failed (actions mismatch)"); } /* * All ok up to this point. Now construct and setup the security result * structure. The service may fetch this and check it. Also the * DoAllSender will use this in certain situations such as: * USE_REQ_SIG_CERT to encrypt */ Vector results = null; if ((results = (Vector) getProperty(msgContext, WSHandlerConstants.RECV_RESULTS)) == null) { results = new Vector(); msgContext.setProperty(WSHandlerConstants.RECV_RESULTS, results); } WSHandlerResult rResult = new WSHandlerResult(actor, wsResult); results.add(0, rResult); }
diff --git a/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/features/context/impl/AddContext.java b/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/features/context/impl/AddContext.java index 8d669d45..dc1e58da 100644 --- a/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/features/context/impl/AddContext.java +++ b/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/features/context/impl/AddContext.java @@ -1,156 +1,158 @@ /******************************************************************************* * <copyright> * * Copyright (c) 2005, 2012 SAP AG. * 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: * SAP AG - initial API, implementation and documentation * mwenz - Bug 394801 - AddGraphicalRepresentation doesn't carry properties * * </copyright> * *******************************************************************************/ /* * Created on 17.11.2005 */ package org.eclipse.graphiti.features.context.impl; import java.util.List; import org.eclipse.graphiti.features.context.IAddContext; import org.eclipse.graphiti.features.context.IAreaContext; import org.eclipse.graphiti.features.context.ITargetConnectionContext; import org.eclipse.graphiti.features.context.ITargetContext; import org.eclipse.graphiti.internal.util.T; import org.eclipse.graphiti.mm.pictograms.Connection; import org.eclipse.graphiti.mm.pictograms.ConnectionDecorator; import org.eclipse.graphiti.mm.pictograms.ContainerShape; /** * The Class AddContext. */ public class AddContext extends AreaContext implements IAddContext { private ContainerShape targetContainer; private Connection targetConnection; private ConnectionDecorator targetConnectionDecorator; private Object newObject; /** * Creates a new {@link AddContext}. */ public AddContext() { super(); } /** * Creates a new {@link AddContext}. * * @param context * the context * @param newObject * the new object */ public AddContext(IAreaContext context, Object newObject) { this(); final String SIGNATURE = "AddContext(IAreaContext, Object)"; //$NON-NLS-1$ boolean info = T.racer().info(); if (info) { T.racer().entering(AddContext.class, SIGNATURE, new Object[] { context, newObject }); } setNewObject(newObject); setLocation(context.getX(), context.getY()); setSize(context.getWidth(), context.getHeight()); // Transfer properties, see Bugzilla 394801 List<Object> propertyKeys = context.getPropertyKeys(); - for (Object key : propertyKeys) { - putProperty(key, context.getProperty(key)); + if (propertyKeys != null) { + for (Object key : propertyKeys) { + putProperty(key, context.getProperty(key)); + } } if (context instanceof ITargetContext) { ITargetContext targetContext = (ITargetContext) context; setTargetContainer(targetContext.getTargetContainer()); } if (context instanceof ITargetConnectionContext) { ITargetConnectionContext targetConnectionContext = (ITargetConnectionContext) context; setTargetConnection(targetConnectionContext.getTargetConnection()); } if (info) { T.racer().exiting(AddContext.class, SIGNATURE); } } public Object getNewObject() { return this.newObject; } public Connection getTargetConnection() { return this.targetConnection; } public ConnectionDecorator getTargetConnectionDecorator() { return this.targetConnectionDecorator; } public ContainerShape getTargetContainer() { return this.targetContainer; } /** * Sets the new object. * * @param newObject * the new object */ public void setNewObject(Object newObject) { this.newObject = newObject; } /** * Sets the target container. * * @param targetContainer * The target container to set. */ public void setTargetContainer(ContainerShape targetContainer) { this.targetContainer = targetContainer; } /** * Sets the target connection. * * @param targetConnection * The target connection to set. */ public void setTargetConnection(Connection targetConnection) { this.targetConnection = targetConnection; } /** * Sets the target connection decorator. * * @param targetConnectionDecorator * The target connection decorator to set. */ public void setTargetConnectionDecorator(ConnectionDecorator targetConnectionDecorator) { this.targetConnectionDecorator = targetConnectionDecorator; } @Override public String toString() { String ret = super.toString(); ret = ret + " newObject: " + getNewObject() + " targetConnection: " + getTargetConnection() + " targetConnectionDecorator: " + getTargetConnectionDecorator() + " targetContainer: " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + getTargetContainer(); return ret; } }
true
true
public AddContext(IAreaContext context, Object newObject) { this(); final String SIGNATURE = "AddContext(IAreaContext, Object)"; //$NON-NLS-1$ boolean info = T.racer().info(); if (info) { T.racer().entering(AddContext.class, SIGNATURE, new Object[] { context, newObject }); } setNewObject(newObject); setLocation(context.getX(), context.getY()); setSize(context.getWidth(), context.getHeight()); // Transfer properties, see Bugzilla 394801 List<Object> propertyKeys = context.getPropertyKeys(); for (Object key : propertyKeys) { putProperty(key, context.getProperty(key)); } if (context instanceof ITargetContext) { ITargetContext targetContext = (ITargetContext) context; setTargetContainer(targetContext.getTargetContainer()); } if (context instanceof ITargetConnectionContext) { ITargetConnectionContext targetConnectionContext = (ITargetConnectionContext) context; setTargetConnection(targetConnectionContext.getTargetConnection()); } if (info) { T.racer().exiting(AddContext.class, SIGNATURE); } }
public AddContext(IAreaContext context, Object newObject) { this(); final String SIGNATURE = "AddContext(IAreaContext, Object)"; //$NON-NLS-1$ boolean info = T.racer().info(); if (info) { T.racer().entering(AddContext.class, SIGNATURE, new Object[] { context, newObject }); } setNewObject(newObject); setLocation(context.getX(), context.getY()); setSize(context.getWidth(), context.getHeight()); // Transfer properties, see Bugzilla 394801 List<Object> propertyKeys = context.getPropertyKeys(); if (propertyKeys != null) { for (Object key : propertyKeys) { putProperty(key, context.getProperty(key)); } } if (context instanceof ITargetContext) { ITargetContext targetContext = (ITargetContext) context; setTargetContainer(targetContext.getTargetContainer()); } if (context instanceof ITargetConnectionContext) { ITargetConnectionContext targetConnectionContext = (ITargetConnectionContext) context; setTargetConnection(targetConnectionContext.getTargetConnection()); } if (info) { T.racer().exiting(AddContext.class, SIGNATURE); } }
diff --git a/javagit/src/test/java/edu/nyu/cs/javagit/test/utilities/FileUtilities.java b/javagit/src/test/java/edu/nyu/cs/javagit/test/utilities/FileUtilities.java index 10398e7..e949a11 100644 --- a/javagit/src/test/java/edu/nyu/cs/javagit/test/utilities/FileUtilities.java +++ b/javagit/src/test/java/edu/nyu/cs/javagit/test/utilities/FileUtilities.java @@ -1,133 +1,134 @@ /* * ==================================================================== * Copyright (c) 2008 JavaGit Project. All rights reserved. * * This software is licensed using the GNU LGPL v2.1 license. A copy * of the license is included with the distribution of this source * code in the LICENSE.txt file. The text of the license can also * be obtained at: * * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * For more information on the JavaGit project, see: * * http://www.javagit.com * ==================================================================== */ package edu.nyu.cs.javagit.test.utilities; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import edu.nyu.cs.javagit.api.JavaGitException; /** * Some simple file utility methods for helping with testing java git functionality. */ public class FileUtilities { // The temp directory to use on unix systems. private static final String UNIX_TMP_DIR = "/tmp/"; // The temp directory to use on windows systems. private static final String WINDOWS_TMP_DIR = "c:\\"; // The temp directory for the current running system. private static final String BASE_TMP_DIR; /** True if running on windows. False if not running on windows (assuming Unix/Linux/OS X then). */ public static final boolean IS_WINDOWS; static { if (System.getProperty("os.name").contains("indows")) { IS_WINDOWS = true; BASE_TMP_DIR = WINDOWS_TMP_DIR; } else { IS_WINDOWS = false; BASE_TMP_DIR = UNIX_TMP_DIR; } } /** * Create a temp directory based on the supplied directory base name. The directory will be * created under the temp directory for the system running the program. * * @param baseDirName * A base name for the directory. If this directory exists, a directory based on this * name will be created. * @return A <code>File</code> instance representing the created directory. */ public static File createTempDirectory(String baseDirName) { int num = 0; File file = new File(BASE_TMP_DIR + baseDirName); while (!file.mkdir()) { file = new File(BASE_TMP_DIR + baseDirName + Integer.toString(num++)); } return file; } /** * Create a new file and write the contents to it. * * @param baseDir * The base directory of the repo. * @param filePath * The relative path to the file with respect to the base directory. * @param contents * Some contents to write to the file. * @return A <code>File</code> object representation of the file. * @throws IOException * If there are problems creating the file or writing the contents to the file. */ public static File createFile(File baseDir, String filePath, String contents) throws IOException { File file = new File(baseDir.getAbsolutePath() + File.separator + filePath); file.createNewFile(); FileWriter fw = new FileWriter(file); fw.write(contents); fw.flush(); return file; } /** * Recursively deletes the specified file/directory. * * @param dirOrFile * The file or directory to delete recursively and forcefully. * @throws JavaGitException * Thrown if a file or directory was not deleted. */ public static void removeDirectoryRecursivelyAndForcefully(File dirOrFile) throws JavaGitException { File[] children = dirOrFile.listFiles(); if (null != children) { for (File f : children) { removeDirectoryRecursivelyAndForcefully(f); } } + System.gc(); if (!dirOrFile.delete()) { throw new JavaGitException(-1, "-1: Unable to delete file/directory. { path=[" + dirOrFile.getAbsolutePath() + "] }"); } } /** * Append some text to an existing file. * @param file File that will be modified * @param appendText The text that will be appended to the file * @throws FileNotFoundException Exception thrown if the file does not exist. * @throws IOException thrown if the IO operation fails. */ public static void modifyFileContents(File file, String appendText) throws FileNotFoundException, IOException { if ( ! file.exists()) { throw new FileNotFoundException("File does not exist"); } FileWriter fw = new FileWriter(file); fw.append(appendText); fw.close(); } }
true
true
public static void removeDirectoryRecursivelyAndForcefully(File dirOrFile) throws JavaGitException { File[] children = dirOrFile.listFiles(); if (null != children) { for (File f : children) { removeDirectoryRecursivelyAndForcefully(f); } } if (!dirOrFile.delete()) { throw new JavaGitException(-1, "-1: Unable to delete file/directory. { path=[" + dirOrFile.getAbsolutePath() + "] }"); } }
public static void removeDirectoryRecursivelyAndForcefully(File dirOrFile) throws JavaGitException { File[] children = dirOrFile.listFiles(); if (null != children) { for (File f : children) { removeDirectoryRecursivelyAndForcefully(f); } } System.gc(); if (!dirOrFile.delete()) { throw new JavaGitException(-1, "-1: Unable to delete file/directory. { path=[" + dirOrFile.getAbsolutePath() + "] }"); } }
diff --git a/src/org/oscim/tilesource/mapnik/TileDecoder.java b/src/org/oscim/tilesource/mapnik/TileDecoder.java index f445de34..47a67b66 100644 --- a/src/org/oscim/tilesource/mapnik/TileDecoder.java +++ b/src/org/oscim/tilesource/mapnik/TileDecoder.java @@ -1,595 +1,595 @@ /* * Copyright 2013 * * 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, see <http://www.gnu.org/licenses/>. */ package org.oscim.tilesource.mapnik; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import org.oscim.core.GeometryBuffer.GeometryType; import org.oscim.core.MapElement; import org.oscim.core.Tag; import org.oscim.core.Tile; import org.oscim.tilesource.ITileDataSink; import org.oscim.tilesource.common.PbfDecoder; import org.oscim.utils.pool.Inlist; import org.oscim.utils.pool.Pool; import android.util.Log; public class TileDecoder extends PbfDecoder { private final static String TAG = TileDecoder.class.getName(); private static final int TAG_TILE_LAYERS = 3; private static final int TAG_LAYER_VERSION = 15; private static final int TAG_LAYER_NAME = 1; private static final int TAG_LAYER_FEATURES = 2; private static final int TAG_LAYER_KEYS = 3; private static final int TAG_LAYER_VALUES = 4; private static final int TAG_LAYER_EXTENT = 5; private static final int TAG_FEATURE_ID = 1; private static final int TAG_FEATURE_TAGS = 2; private static final int TAG_FEATURE_TYPE = 3; private static final int TAG_FEATURE_GEOMETRY = 4; private static final int TAG_VALUE_STRING = 1; private static final int TAG_VALUE_FLOAT = 2; private static final int TAG_VALUE_DOUBLE = 3; private static final int TAG_VALUE_LONG = 4; private static final int TAG_VALUE_UINT = 5; private static final int TAG_VALUE_SINT = 6; private static final int TAG_VALUE_BOOL = 7; private static final int TAG_GEOM_UNKNOWN = 0; private static final int TAG_GEOM_POINT = 1; private static final int TAG_GEOM_LINE = 2; private static final int TAG_GEOM_POLYGON = 3; private short[] mTmpTags = new short[1024]; private Tile mTile; private final String mLocale = "de"; private ITileDataSink mMapDataCallback; private final static float REF_TILE_SIZE = 4096.0f; private float mScale; @Override public boolean decode(Tile tile, ITileDataSink mapDataCallback, InputStream is, int contentLength) throws IOException { if (debug) Log.d(TAG, tile + " decode"); setInputStream(is, Integer.MAX_VALUE); mTile = tile; mMapDataCallback = mapDataCallback; mScale = REF_TILE_SIZE / Tile.SIZE; int val; while (hasData() && (val = decodeVarint32()) > 0) { // read tag and wire type int tag = (val >> 3); switch (tag) { case TAG_TILE_LAYERS: decodeLayer(); break; default: error(mTile + " invalid type for tile: " + tag); return false; } } if (hasData()){ error(tile + " invalid tile"); return false; } return true; } private boolean decodeLayer() throws IOException { //int version = 0; //int extent = 4096; int bytes = decodeVarint32(); ArrayList<String> keys = new ArrayList<String>(); ArrayList<String> values = new ArrayList<String>(); String name = null; int numFeatures = 0; ArrayList<Feature> features = new ArrayList<Feature>(); int end = position() + bytes; while (position() < end) { // read tag and wire type int val = decodeVarint32(); if (val == 0) break; int tag = (val >> 3); switch (tag) { case TAG_LAYER_KEYS: keys.add(decodeString()); break; case TAG_LAYER_VALUES: values.add(decodeValue()); break; case TAG_LAYER_FEATURES: numFeatures++; decodeFeature(features); break; case TAG_LAYER_VERSION: //version = decodeVarint32(); break; case TAG_LAYER_NAME: name = decodeString(); break; case TAG_LAYER_EXTENT: //extent = decodeVarint32(); break; default: error(mTile + " invalid type for layer: " + tag); break; } } Tag layerTag = new Tag(name, Tag.VALUE_YES); if (numFeatures == 0) return true; int[] ignoreLocal = new int[20]; int numIgnore = 0; int fallBackLocal = -1; int matchedLocal = -1; for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); if (!key.startsWith(Tag.TAG_KEY_NAME)) continue; int len = key.length(); if (len == 4) { fallBackLocal = i; continue; } if (len < 7) { ignoreLocal[numIgnore++] = i; continue; } if (mLocale.equals(key.substring(5))) { //Log.d(TAG, "found local " + key); matchedLocal = i; } else ignoreLocal[numIgnore++] = i; } for (Feature f : features) { if (f.elem.type == GeometryType.NONE) continue; f.elem.tags.clear(); f.elem.tags.add(layerTag); boolean hasName = false; String fallbackName = null; tagLoop: for (int j = 0; j < (f.numTags << 1); j += 2) { int keyIdx = f.tags[j]; for (int i = 0; i < numIgnore; i++) if (keyIdx == ignoreLocal[i]) continue tagLoop; if (keyIdx == fallBackLocal) { fallbackName = values.get(f.tags[j + 1]); continue; } String key; String val = values.get(f.tags[j + 1]); if (keyIdx == matchedLocal) { hasName = true; f.elem.tags.add(new Tag(Tag.TAG_KEY_NAME, val, false)); } else { key = keys.get(keyIdx); f.elem.tags.add(new Tag(key, val)); } } if (!hasName && fallbackName != null) f.elem.tags.add(new Tag(Tag.TAG_KEY_NAME, fallbackName, false)); // FIXME extract layer tag here f.elem.setLayer(5); mMapDataCallback.process(f.elem); mFeaturePool.release(f); } return true; } private final Pool<Feature> mFeaturePool = new Pool<Feature>() { int count; @Override protected Feature createItem() { count++; return new Feature(); } @Override protected boolean clearItem(Feature item) { if (count > 100) { count--; return false; } item.elem.tags.clear(); item.elem.clear(); item.tags = null; item.type = 0; item.numTags = 0; return true; } }; static class Feature extends Inlist<Feature> { short[] tags; int numTags; int type; final MapElement elem; Feature() { elem = new MapElement(); } boolean match(short otherTags[], int otherNumTags, int otherType) { if (numTags != otherNumTags) return false; if (type != otherType) return false; for (int i = 0; i < numTags << 1; i++) { if (tags[i] != otherTags[i]) return false; } return true; } } private void decodeFeature(ArrayList<Feature> features) throws IOException { int bytes = decodeVarint32(); int end = position() + bytes; int type = 0; //long id; lastX = 0; lastY = 0; mTmpTags[0] = -1; Feature curFeature = null; int numTags = 0; //Log.d(TAG, "start feature"); while (position() < end) { // read tag and wire type int val = decodeVarint32(); if (val == 0) break; int tag = (val >>> 3); switch (tag) { case TAG_FEATURE_ID: //id = decodeVarint32(); break; case TAG_FEATURE_TAGS: mTmpTags = decodeUnsignedVarintArray(mTmpTags); for (; numTags < mTmpTags.length && mTmpTags[numTags] >= 0;) numTags += 2; numTags >>= 1; break; case TAG_FEATURE_TYPE: type = decodeVarint32(); //Log.d(TAG, "got type " + type); break; case TAG_FEATURE_GEOMETRY: for (Feature f : features) { if (f.match(mTmpTags, numTags, type)) { curFeature = f; break; } } if (curFeature == null) { curFeature = mFeaturePool.get(); curFeature.tags = new short[numTags << 1]; System.arraycopy(mTmpTags, 0, curFeature.tags, 0, numTags << 1); curFeature.numTags = numTags; curFeature.type = type; features.add(curFeature); } decodeCoordinates(type, curFeature); break; default: error(mTile + " invalid type for feature: " + tag); break; } } } private final static int CLOSE_PATH = 0x07; private final static int MOVE_TO = 0x01; //private final static int LINE_TO = 0x02; private int lastX, lastY; private int decodeCoordinates(int type, Feature feature) throws IOException { int bytes = decodeVarint32(); fillBuffer(bytes); if (feature == null) { bufferPos += bytes; return 0; } MapElement elem = feature.elem; boolean isPoint = false; boolean isPoly = false; boolean isLine = false; if (type == TAG_GEOM_LINE) { elem.startLine(); isLine = true; } else if (type == TAG_GEOM_POLYGON) { elem.startPolygon(); isPoly = true; } else if (type == TAG_GEOM_POINT) { isPoint = true; elem.startPoints(); } else if (type == TAG_GEOM_UNKNOWN) elem.startPoints(); boolean even = true; int val; int curX = 0; int curY = 0; int prevX = 0; int prevY = 0; int cmd = 0; int num = 0, cnt = 0; boolean first = true; boolean lastClip = false; // test bbox for outer.. boolean isOuter = true; boolean simplify = mTile.zoomLevel < 14; int pixel = simplify ? 7 : 3; int xmin = Integer.MAX_VALUE, xmax = Integer.MIN_VALUE; int ymin = Integer.MAX_VALUE, ymax = Integer.MIN_VALUE; for (int end = bufferPos + bytes; bufferPos < end;) { val = decodeVarint32Filled(); if (num == 0) { // number of points num = val >>> 3; cnt = 0; // path command cmd = val & 0x07; if (isLine && lastClip) { elem.addPoint(curX / mScale, curY / mScale); lastClip = false; } if (cmd == CLOSE_PATH) { num = 0; continue; } if (first) { first = false; continue; } if (cmd == MOVE_TO) { if (type == TAG_GEOM_LINE) elem.startLine(); else if (type == TAG_GEOM_POLYGON) { isOuter = false; elem.startHole(); } } continue; } // zigzag decoding int s = ((val >>> 1) ^ -(val & 1)); if (even) { // get x coordinate even = false; curX = lastX = lastX + s; continue; } // get y coordinate and add point to geometry num--; even = true; curY = lastY = lastY + s; int dx = (curX - prevX); int dy = (curY - prevY); if (isPoly && num == 0 && cnt > 0){ prevX = curX; prevY = curY; // only add last point if it is di int ppos = cnt * 2; if (elem.points[elem.pointPos - ppos] != curX || elem.points[elem.pointPos - ppos + 1] != curY) elem.addPoint(curX / mScale, curY / mScale); lastClip = false; continue; } if ((isPoint || cmd == MOVE_TO) || (dx > pixel || dx < -pixel) || (dy > pixel || dy < -pixel) // hack to not clip at tile boundaries || (curX <= 0 || curX >= 4095) || (curY <= 0 || curY >= 4095)) { prevX = curX; prevY = curY; elem.addPoint(curX / mScale, curY / mScale); cnt++; if (simplify && isOuter) { if (curX < xmin) xmin = curX; if (curX > xmax) xmax = curX; if (curY < ymin) ymin = curY; if (curY > ymax) ymax = curY; } lastClip = false; continue; } lastClip = true; } if (isPoly && isOuter && simplify && !testBBox(xmax - xmin, ymax - ymin)) { //Log.d(TAG, "skip small poly "+ elem.indexPos + " > " // + (xmax - xmin) * (ymax - ymin)); elem.pointPos -= elem.index[elem.indexPos]; if (elem.indexPos > 0) { - elem.indexPos -= 3; + elem.indexPos -= 2; elem.index[elem.indexPos + 1] = -1; } else { elem.type = GeometryType.NONE; } return 0; } if (isLine && lastClip) elem.addPoint(curX / mScale, curY / mScale); return 1; } private static boolean testBBox(int dx, int dy) { return dx * dy > 64 * 64; } private String decodeValue() throws IOException { int bytes = decodeVarint32(); String value = null; int end = position() + bytes; while (position() < end) { // read tag and wire type int val = decodeVarint32(); if (val == 0) break; int tag = (val >> 3); switch (tag) { case TAG_VALUE_STRING: value = decodeString(); break; case TAG_VALUE_UINT: value = String.valueOf(decodeVarint32()); break; case TAG_VALUE_SINT: value = String.valueOf(deZigZag(decodeVarint32())); break; case TAG_VALUE_LONG: value = String.valueOf(decodeVarint64()); break; case TAG_VALUE_FLOAT: value = String.valueOf(decodeFloat()); break; case TAG_VALUE_DOUBLE: value = String.valueOf(decodeDouble()); break; case TAG_VALUE_BOOL: value = decodeBool() ? "yes" : "no"; break; default: break; } } return value; } }
true
true
private int decodeCoordinates(int type, Feature feature) throws IOException { int bytes = decodeVarint32(); fillBuffer(bytes); if (feature == null) { bufferPos += bytes; return 0; } MapElement elem = feature.elem; boolean isPoint = false; boolean isPoly = false; boolean isLine = false; if (type == TAG_GEOM_LINE) { elem.startLine(); isLine = true; } else if (type == TAG_GEOM_POLYGON) { elem.startPolygon(); isPoly = true; } else if (type == TAG_GEOM_POINT) { isPoint = true; elem.startPoints(); } else if (type == TAG_GEOM_UNKNOWN) elem.startPoints(); boolean even = true; int val; int curX = 0; int curY = 0; int prevX = 0; int prevY = 0; int cmd = 0; int num = 0, cnt = 0; boolean first = true; boolean lastClip = false; // test bbox for outer.. boolean isOuter = true; boolean simplify = mTile.zoomLevel < 14; int pixel = simplify ? 7 : 3; int xmin = Integer.MAX_VALUE, xmax = Integer.MIN_VALUE; int ymin = Integer.MAX_VALUE, ymax = Integer.MIN_VALUE; for (int end = bufferPos + bytes; bufferPos < end;) { val = decodeVarint32Filled(); if (num == 0) { // number of points num = val >>> 3; cnt = 0; // path command cmd = val & 0x07; if (isLine && lastClip) { elem.addPoint(curX / mScale, curY / mScale); lastClip = false; } if (cmd == CLOSE_PATH) { num = 0; continue; } if (first) { first = false; continue; } if (cmd == MOVE_TO) { if (type == TAG_GEOM_LINE) elem.startLine(); else if (type == TAG_GEOM_POLYGON) { isOuter = false; elem.startHole(); } } continue; } // zigzag decoding int s = ((val >>> 1) ^ -(val & 1)); if (even) { // get x coordinate even = false; curX = lastX = lastX + s; continue; } // get y coordinate and add point to geometry num--; even = true; curY = lastY = lastY + s; int dx = (curX - prevX); int dy = (curY - prevY); if (isPoly && num == 0 && cnt > 0){ prevX = curX; prevY = curY; // only add last point if it is di int ppos = cnt * 2; if (elem.points[elem.pointPos - ppos] != curX || elem.points[elem.pointPos - ppos + 1] != curY) elem.addPoint(curX / mScale, curY / mScale); lastClip = false; continue; } if ((isPoint || cmd == MOVE_TO) || (dx > pixel || dx < -pixel) || (dy > pixel || dy < -pixel) // hack to not clip at tile boundaries || (curX <= 0 || curX >= 4095) || (curY <= 0 || curY >= 4095)) { prevX = curX; prevY = curY; elem.addPoint(curX / mScale, curY / mScale); cnt++; if (simplify && isOuter) { if (curX < xmin) xmin = curX; if (curX > xmax) xmax = curX; if (curY < ymin) ymin = curY; if (curY > ymax) ymax = curY; } lastClip = false; continue; } lastClip = true; } if (isPoly && isOuter && simplify && !testBBox(xmax - xmin, ymax - ymin)) { //Log.d(TAG, "skip small poly "+ elem.indexPos + " > " // + (xmax - xmin) * (ymax - ymin)); elem.pointPos -= elem.index[elem.indexPos]; if (elem.indexPos > 0) { elem.indexPos -= 3; elem.index[elem.indexPos + 1] = -1; } else { elem.type = GeometryType.NONE; } return 0; } if (isLine && lastClip) elem.addPoint(curX / mScale, curY / mScale); return 1; }
private int decodeCoordinates(int type, Feature feature) throws IOException { int bytes = decodeVarint32(); fillBuffer(bytes); if (feature == null) { bufferPos += bytes; return 0; } MapElement elem = feature.elem; boolean isPoint = false; boolean isPoly = false; boolean isLine = false; if (type == TAG_GEOM_LINE) { elem.startLine(); isLine = true; } else if (type == TAG_GEOM_POLYGON) { elem.startPolygon(); isPoly = true; } else if (type == TAG_GEOM_POINT) { isPoint = true; elem.startPoints(); } else if (type == TAG_GEOM_UNKNOWN) elem.startPoints(); boolean even = true; int val; int curX = 0; int curY = 0; int prevX = 0; int prevY = 0; int cmd = 0; int num = 0, cnt = 0; boolean first = true; boolean lastClip = false; // test bbox for outer.. boolean isOuter = true; boolean simplify = mTile.zoomLevel < 14; int pixel = simplify ? 7 : 3; int xmin = Integer.MAX_VALUE, xmax = Integer.MIN_VALUE; int ymin = Integer.MAX_VALUE, ymax = Integer.MIN_VALUE; for (int end = bufferPos + bytes; bufferPos < end;) { val = decodeVarint32Filled(); if (num == 0) { // number of points num = val >>> 3; cnt = 0; // path command cmd = val & 0x07; if (isLine && lastClip) { elem.addPoint(curX / mScale, curY / mScale); lastClip = false; } if (cmd == CLOSE_PATH) { num = 0; continue; } if (first) { first = false; continue; } if (cmd == MOVE_TO) { if (type == TAG_GEOM_LINE) elem.startLine(); else if (type == TAG_GEOM_POLYGON) { isOuter = false; elem.startHole(); } } continue; } // zigzag decoding int s = ((val >>> 1) ^ -(val & 1)); if (even) { // get x coordinate even = false; curX = lastX = lastX + s; continue; } // get y coordinate and add point to geometry num--; even = true; curY = lastY = lastY + s; int dx = (curX - prevX); int dy = (curY - prevY); if (isPoly && num == 0 && cnt > 0){ prevX = curX; prevY = curY; // only add last point if it is di int ppos = cnt * 2; if (elem.points[elem.pointPos - ppos] != curX || elem.points[elem.pointPos - ppos + 1] != curY) elem.addPoint(curX / mScale, curY / mScale); lastClip = false; continue; } if ((isPoint || cmd == MOVE_TO) || (dx > pixel || dx < -pixel) || (dy > pixel || dy < -pixel) // hack to not clip at tile boundaries || (curX <= 0 || curX >= 4095) || (curY <= 0 || curY >= 4095)) { prevX = curX; prevY = curY; elem.addPoint(curX / mScale, curY / mScale); cnt++; if (simplify && isOuter) { if (curX < xmin) xmin = curX; if (curX > xmax) xmax = curX; if (curY < ymin) ymin = curY; if (curY > ymax) ymax = curY; } lastClip = false; continue; } lastClip = true; } if (isPoly && isOuter && simplify && !testBBox(xmax - xmin, ymax - ymin)) { //Log.d(TAG, "skip small poly "+ elem.indexPos + " > " // + (xmax - xmin) * (ymax - ymin)); elem.pointPos -= elem.index[elem.indexPos]; if (elem.indexPos > 0) { elem.indexPos -= 2; elem.index[elem.indexPos + 1] = -1; } else { elem.type = GeometryType.NONE; } return 0; } if (isLine && lastClip) elem.addPoint(curX / mScale, curY / mScale); return 1; }
diff --git a/src/org/biojavax/bio/seq/io/GenbankFormat.java b/src/org/biojavax/bio/seq/io/GenbankFormat.java index f40f50ae9..ad6fd02f9 100644 --- a/src/org/biojavax/bio/seq/io/GenbankFormat.java +++ b/src/org/biojavax/bio/seq/io/GenbankFormat.java @@ -1,771 +1,771 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojavax.bio.seq.io; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.TreeSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.io.ParseException; import org.biojava.bio.seq.io.SeqIOListener; import org.biojava.bio.seq.io.SymbolTokenization; import org.biojava.bio.symbol.AlphabetManager; import org.biojava.bio.symbol.IllegalSymbolException; import org.biojava.bio.symbol.SimpleSymbolList; import org.biojava.bio.symbol.Symbol; import org.biojava.bio.symbol.SymbolList; import org.biojava.utils.ChangeVetoException; import org.biojava.utils.ParseErrorListener; import org.biojavax.Comment; import org.biojavax.CrossRef; import org.biojavax.DocRef; import org.biojavax.Note; import org.biojavax.RankedCrossRef; import org.biojavax.RankedDocRef; import org.biojavax.SimpleComment; import org.biojavax.SimpleCrossRef; import org.biojavax.SimpleDocRef; import org.biojavax.SimpleRankedCrossRef; import org.biojavax.SimpleRankedDocRef; import org.biojavax.SimpleRichAnnotation; import org.biojavax.bio.db.RichObjectFactory; import org.biojavax.bio.seq.RichFeature; import org.biojavax.bio.seq.RichLocation; import org.biojavax.bio.seq.RichSequence; import org.biojavax.bio.taxa.NCBITaxon; import org.biojavax.bio.taxa.SimpleNCBITaxon; import org.biojavax.ontology.ComparableTerm; /** * Format reader for GenBank files. Converted from the old style io to * the new by working from <code>EmblLikeFormat</code>. * * @author Thomas Down * @author Thad Welch * Added GenBank header info to the sequence annotation. The ACCESSION header * tag is not included. Stored in sequence.getName(). * @author Greg Cox * @author Keith James * @author Matthew Pocock * @author Ron Kuhn * Implemented nice RichSeq stuff. * @author Richard Holland */ public class GenbankFormat implements RichSequenceFormat { public static final String DEFAULT_FORMAT = "GENBANK"; protected static final String LOCUS_TAG = "LOCUS"; protected static final String ACCESSION_TAG = "ACCESSION"; protected static final String VERSION_TAG = "VERSION"; protected static final String DEFINITION_TAG = "DEFINITION"; protected static final String SOURCE_TAG = "SOURCE"; protected static final String ORGANISM_TAG = "ORGANISM"; protected static final String REFERENCE_TAG = "REFERENCE"; protected static final String KEYWORDS_TAG = "KEYWORDS"; protected static final String AUTHORS_TAG = "AUTHORS"; protected static final String TITLE_TAG = "TITLE"; protected static final String JOURNAL_TAG = "JOURNAL"; protected static final String PUBMED_TAG = "PUBMED"; protected static final String MEDLINE_TAG = "MEDLINE"; protected static final String REMARK_TAG = "REMARK"; protected static final String COMMENT_TAG = "COMMENT"; protected static final String FEATURE_TAG = "FEATURES"; protected static final String BASE_COUNT_TAG = "BASE"; protected static final String START_SEQUENCE_TAG = "ORIGIN"; protected static final String END_SEQUENCE_TAG = "//"; private static ComparableTerm ACCESSION_TERM = null; public static ComparableTerm getAccessionTerm() { if (ACCESSION_TERM==null) ACCESSION_TERM = RichObjectFactory.getDefaultOntology().getOrCreateTerm("ACCESSION"); return ACCESSION_TERM; } private static ComparableTerm KERYWORDS_TERM = null; private static ComparableTerm getKeywordsTerm() { if (KERYWORDS_TERM==null) KERYWORDS_TERM = RichObjectFactory.getDefaultOntology().getOrCreateTerm("KEYWORDS"); return KERYWORDS_TERM; } private static ComparableTerm MODIFICATION_TERM = null; private static ComparableTerm getModificationTerm() { if (MODIFICATION_TERM==null) MODIFICATION_TERM = RichObjectFactory.getDefaultOntology().getOrCreateTerm("MDAT"); return MODIFICATION_TERM; } private static ComparableTerm MOLTYPE_TERM = null; public static ComparableTerm getMolTypeTerm() { if (MOLTYPE_TERM==null) MOLTYPE_TERM = RichObjectFactory.getDefaultOntology().getOrCreateTerm("MOLTYPE"); return MOLTYPE_TERM; } private static ComparableTerm STRANDED_TERM = null; private static ComparableTerm getStrandedTerm() { if (STRANDED_TERM==null) STRANDED_TERM = RichObjectFactory.getDefaultOntology().getOrCreateTerm("STRANDED"); return STRANDED_TERM; } private static ComparableTerm GENBANK_TERM = null; private static ComparableTerm getGenBankTerm() { if (GENBANK_TERM==null) GENBANK_TERM = RichObjectFactory.getDefaultOntology().getOrCreateTerm("GenBank"); return GENBANK_TERM; } private boolean elideSymbols = false; /** * The line width for output. */ protected int lineWidth = 80; /** * Retrive the current line width. * * @return the line width */ public int getLineWidth() { return lineWidth; } /** * Set the line width. * <p> * When writing, the lines of sequence will never be longer than the line * width. * * @param width the new line width */ public void setLineWidth(int width) { this.lineWidth = width; } public boolean readSequence(BufferedReader reader, SymbolTokenization symParser, SeqIOListener listener) throws IllegalSymbolException, IOException, ParseException { if (!(listener instanceof RichSeqIOListener)) throw new IllegalArgumentException("Only accepting RichSeqIOListeners today"); return this.readRichSequence(reader,symParser,(RichSeqIOListener)listener); } /** * Reads a sequence from the specified reader using the Symbol * parser and Sequence Factory provided. The sequence read in must * be in Genbank format. * * @return boolean True if there is another sequence in the file; false * otherwise */ public boolean readRichSequence(BufferedReader reader, SymbolTokenization symParser, RichSeqIOListener rlistener) throws IllegalSymbolException, IOException, ParseException { String line; boolean hasAnotherSequence = true; boolean hasInternalWhitespace = false; rlistener.startSequence(); rlistener.setNamespace(RichObjectFactory.getGenbankNamespace()); // Get an ordered list of key->value pairs in array-tuples String sectionKey = null; NCBITaxon tax = null; String organism = null; String accession = null; do { List section = this.readSection(reader); sectionKey = ((String[])section.get(0))[0]; // process section-by-section if (sectionKey.equals(LOCUS_TAG)) { String loc = ((String[])section.get(0))[1]; String regex = "^(\\S+)\\s+\\d+\\s+bp\\s+([dms]s-)?(\\S+)\\s+(circular|linear)?\\s+(\\S+)\\s+(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(loc); if (m.matches()) { rlistener.setName(m.group(1)); rlistener.setDivision(m.group(5)); rlistener.addSequenceProperty(getMolTypeTerm(),m.group(3)); rlistener.addSequenceProperty(getModificationTerm(),m.group(6)); // Optional extras String stranded = m.group(2); String circular = m.group(4); if (stranded!=null) rlistener.addSequenceProperty(getStrandedTerm(),stranded); if (circular!=null && circular.equals("circular")) rlistener.setCircular(true); } else { throw new ParseException("Bad locus line found: "+loc); } } else if (sectionKey.equals(DEFINITION_TAG)) { rlistener.setDescription(((String[])section.get(0))[1]); } else if (sectionKey.equals(ACCESSION_TAG)) { // if multiple accessions, store only first as accession, // and store rest in annotation String[] accs = ((String[])section.get(0))[1].split("\\s+"); accession = accs[0].trim(); rlistener.setAccession(accession); for (int i = 1; i < accs.length; i++) { rlistener.addSequenceProperty(getAccessionTerm(),accs[i].trim()); } } else if (sectionKey.equals(VERSION_TAG)) { String ver = ((String[])section.get(0))[1]; String regex = "^(\\S+?)\\.(\\d+)\\s+GI:(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(ver); if (m.matches()) { rlistener.setVersion(Integer.parseInt(m.group(2))); rlistener.setIdentifier(m.group(3)); } else { throw new ParseException("Bad version line found: "+ver); } } else if (sectionKey.equals(KEYWORDS_TAG)) { rlistener.addSequenceProperty(getKeywordsTerm(), ((String[])section.get(0))[1]); } else if (sectionKey.equals(SOURCE_TAG)) { // ignore - can get all this from the first feature } else if (sectionKey.equals(REFERENCE_TAG)) { // first line of section has rank and location int ref_rank; int ref_start = -999; int ref_end = -999; String ref = ((String[])section.get(0))[1]; String regex = "^(\\d+)\\s*(\\(bases\\s+(\\d+)\\s+to\\s+(\\d+)\\)|\\(sites\\))?"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(ref); if (m.matches()) { ref_rank = Integer.parseInt(m.group(1)); if(m.group(2) != null){ if (m.group(3)!= null) ref_start = Integer.parseInt(m.group(3)); if(m.group(4) != null) ref_end = Integer.parseInt(m.group(4)); } } else { throw new ParseException("Bad reference line found: "+ref); } // rest can be in any order String authors = null; String title = null; String journal = null; String medline = null; String pubmed = null; String remark = null; for (int i = 1; i < section.size(); i++) { String key = ((String[])section.get(i))[0]; String val = ((String[])section.get(i))[1]; if (key.equals("AUTHORS")) authors = val; if (key.equals("TITLE")) title = val; if (key.equals("JOURNAL")) journal = val; if (key.equals("MEDLINE")) medline = val; if (key.equals("PUBMED")) pubmed = val; if (key.equals("REMARK")) authors = val; } // create the pubmed crossref and assign to the bioentry CrossRef pcr = null; if (pubmed!=null) { pcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{"PUBMED", pubmed}); RankedCrossRef rpcr = new SimpleRankedCrossRef(pcr, 0); rlistener.setRankedCrossRef(rpcr); } // create the medline crossref and assign to the bioentry CrossRef mcr = null; if (medline!=null) { mcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{"MEDLINE", medline}); RankedCrossRef rmcr = new SimpleRankedCrossRef(mcr, 0); rlistener.setRankedCrossRef(rmcr); } // create the docref object try { DocRef dr = (DocRef)RichObjectFactory.getObject(SimpleDocRef.class,new Object[]{authors,journal}); if (title!=null) dr.setTitle(title); // assign either the pubmed or medline to the docref if (pcr!=null) dr.setCrossref(pcr); else if (mcr!=null) dr.setCrossref(mcr); // assign the remarks dr.setRemark(remark); // assign the docref to the bioentry RankedDocRef rdr = new SimpleRankedDocRef(dr, (ref_start != -999 ? new Integer(ref_start) : null), (ref_end != -999 ? new Integer(ref_end) : null), ref_rank); rlistener.setRankedDocRef(rdr); } catch (ChangeVetoException e) { throw new ParseException(e); } } else if (sectionKey.equals(COMMENT_TAG)) { // Set up some comments rlistener.setComment(((String[])section.get(0))[1]); } else if (sectionKey.equals(FEATURE_TAG)) { // starting from second line of input, start a new feature whenever we come across // a value that does not start with " boolean seenAFeature = false; for (int i = 1 ; i < section.size(); i++) { String key = ((String[])section.get(i))[0]; String val = ((String[])section.get(i))[1]; if (key.startsWith("/")) { key = key.substring(1); // strip leading slash - val = val.trim().replaceAll("\"",""); // strip quotes + val = val.replaceAll("\"","").trim(); // strip quotes // parameter on old feature if (key.equals("db_xref")) { String regex = "^(\\S+?):(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(val); if (m.matches()) { String dbname = m.group(1); String raccession = m.group(2); if (dbname.equals("taxon")) { // Set the Taxon instead of a dbxref tax = (NCBITaxon)RichObjectFactory.getObject(SimpleNCBITaxon.class, new Object[]{Integer.valueOf(raccession)}); rlistener.setTaxon(tax); try { if (organism!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism); } catch (ChangeVetoException e) { throw new ParseException(e); } } else { try { CrossRef cr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{dbname, raccession}); RankedCrossRef rcr = new SimpleRankedCrossRef(cr, 0); rlistener.getCurrentFeature().addRankedCrossRef(rcr); } catch (ChangeVetoException e) { throw new ParseException(e); } } } else { throw new ParseException("Bad dbxref found: "+val); } } else if (key.equals("organism")) { try { organism = val; if (tax!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism); } catch (ChangeVetoException e) { throw new ParseException(e); } } else { if (key.equals("translation")) { // strip spaces from sequence val = val.replaceAll("\\s+",""); } rlistener.addFeatureProperty(RichObjectFactory.getDefaultOntology().getOrCreateTerm(key),val); } } else { // new feature! // end previous feature if (seenAFeature) rlistener.endFeature(); // start next one, with lots of lovely info in it RichFeature.Template templ = new RichFeature.Template(); templ.annotation = new SimpleRichAnnotation(); templ.sourceTerm = getGenBankTerm(); templ.typeTerm = RichObjectFactory.getDefaultOntology().getOrCreateTerm(key); templ.featureRelationshipSet = new TreeSet(); templ.rankedCrossRefs = new TreeSet(); String tidyLocStr = val.replaceAll("\\s+",""); templ.location = GenbankLocationParser.parseLocation(RichObjectFactory.getDefaultLocalNamespace(), accession, tidyLocStr); rlistener.startFeature(templ); seenAFeature = true; } } if (seenAFeature) rlistener.endFeature(); } else if (sectionKey.equals(BASE_COUNT_TAG)) { // ignore - can calculate from sequence content later if needed } else if (sectionKey.equals(START_SEQUENCE_TAG) && !this.elideSymbols) { // our first line is ignorable as it is the ORIGIN tag // the second line onwards conveniently have the number as // the [0] tuple, and sequence string as [1] so all we have // to do is concat the [1] parts and then strip out spaces, // and replace '.' and '~' with '-' for our parser. StringBuffer seq = new StringBuffer(); for (int i = 1 ; i < section.size(); i++) seq.append(((String[])section.get(i))[1]); try { SymbolList sl = new SimpleSymbolList(symParser, seq.toString().replaceAll("\\s+","").replaceAll("[\\.|~]","-")); rlistener.addSymbols(symParser.getAlphabet(), (Symbol[])(sl.toList().toArray(new Symbol[0])), 0, sl.length()); } catch (Exception e) { throw new ParseException(e); } } } while (!sectionKey.equals(END_SEQUENCE_TAG)); // Allows us to tolerate trailing whitespace without // thinking that there is another Sequence to follow while (true) { reader.mark(1); int c = reader.read(); if (c == -1) { hasAnotherSequence = false; break; } if (Character.isWhitespace((char) c)) { hasInternalWhitespace = true; continue; } if (hasInternalWhitespace) System.err.println("Warning: whitespace found between sequence entries"); reader.reset(); break; } // Finish up. rlistener.endSequence(); return hasAnotherSequence; } private List readSection(BufferedReader br) throws ParseException { List section = new ArrayList(); String line; String currKey = null; StringBuffer currVal = new StringBuffer(); boolean done = false; int linecount = 0; //s0-8 word s1-7 value //s21 word = value String regex = "^(\\s{0,8}(\\S+?)\\s{1,7}(.*)|\\s{21}(\\S+?)=(.*))$"; Pattern p = Pattern.compile(regex); try { while (!done) { br.mark(160); line = br.readLine(); if (line==null || line.equals("") || (line.charAt(0)!=' ' && linecount++>0)) { // dump out last part of section section.add(new String[]{currKey,currVal.toString()}); br.reset(); done = true; } else { Matcher m = p.matcher(line); if (m.matches()) { // new key if (currKey!=null) section.add(new String[]{currKey,currVal.toString()}); currKey = m.group(2)==null?m.group(4):m.group(2); currVal = new StringBuffer(); currVal.append((m.group(2)==null?m.group(5):m.group(3)).trim()); } else { line = line.trim(); // concatted line or SEQ START/END line? if (line.equals(START_SEQUENCE_TAG) || line.equals(END_SEQUENCE_TAG)) currKey = line; else { currVal.append("\n"); // newline in between lines - can be removed later currVal.append(line); } } } } } catch (IOException e) { throw new ParseException(e); } return section; } public void writeSequence(Sequence seq, PrintStream os) throws IOException { if (!(seq instanceof RichSequence)) throw new IllegalArgumentException("Sorry, only RichSequence objects accepted"); this.writeRichSequence((RichSequence)seq, os); } public void writeRichSequence(RichSequence seq, PrintStream os) throws IOException { writeRichSequence(seq, getDefaultFormat(), os); } public void writeSequence(Sequence seq, String format, PrintStream os) throws IOException { if (!(seq instanceof RichSequence)) throw new IllegalArgumentException("Sorry, only RichSequence objects accepted"); this.writeRichSequence((RichSequence)seq, format, os); } /** * <code>writeSequence</code> writes a sequence to the specified * <code>PrintStream</code>, using the specified format. * * @param seq a <code>Sequence</code> to write out. * @param format a <code>String</code> indicating which sub-format * of those available from a particular * <code>SequenceFormat</code> implemention to use when * writing. * @param os a <code>PrintStream</code> object. * * @exception IOException if an error occurs. * @deprecated use writeSequence(Sequence seq, PrintStream os) */ public void writeRichSequence(RichSequence rs, String format, PrintStream os) throws IOException { // Genbank only really - others are treated identically for now if (!( format.equalsIgnoreCase("GENBANK") || format.equalsIgnoreCase("GENPEPT") || format.equalsIgnoreCase("REFSEQ:PROTEIN") )) throw new IllegalArgumentException("Unknown format: "+format); SymbolTokenization tok; try { tok = rs.getAlphabet().getTokenization("token"); } catch (Exception e) { throw new RuntimeException("Unable to get alphabet tokenizer",e); } Set notes = rs.getNoteSet(); String accession = rs.getAccession(); String accessions = accession; String stranded = ""; String mdat = ""; String moltype = rs.getAlphabet().getName(); for (Iterator i = notes.iterator(); i.hasNext(); ) { Note n = (Note)i.next(); if (n.getTerm().equals(getStrandedTerm())) stranded=n.getValue(); else if (n.getTerm().equals(getModificationTerm())) mdat=n.getValue(); else if (n.getTerm().equals(getMolTypeTerm())) moltype=n.getValue(); else if (n.getTerm().equals(getAccessionTerm())) accessions = accessions+" "+n.getValue(); } // locus(name) + length + alpha + div + date line StringBuffer locusLine = new StringBuffer(); locusLine.append(RichSequenceFormat.Tools.rightPad(rs.getName(),10)); locusLine.append(RichSequenceFormat.Tools.leftPad(""+rs.length(),7)); locusLine.append(" bp "); locusLine.append(RichSequenceFormat.Tools.leftPad(stranded,3)); locusLine.append(RichSequenceFormat.Tools.rightPad(moltype,6)); locusLine.append(RichSequenceFormat.Tools.rightPad(rs.getCircular()?"circular":"",10)); locusLine.append(RichSequenceFormat.Tools.rightPad(rs.getDivision()==null?"":rs.getDivision(),10)); locusLine.append(mdat); this.writeWrappedLine(LOCUS_TAG, 12, locusLine.toString(), os); // definition line this.writeWrappedLine(DEFINITION_TAG, 12, rs.getDescription(), os); // accession line this.writeWrappedLine(ACCESSION_TAG, 12, accessions, os); // version + gi line String version = accession+"."+rs.getVersion(); if (rs.getIdentifier()!=null) version = version + " GI:"+rs.getIdentifier(); this.writeWrappedLine(VERSION_TAG, 12, version, os); // keywords line String keywords = null; for (Iterator n = notes.iterator(); n.hasNext(); ) { Note nt = (Note)n.next(); if (nt.getTerm().equals(getKeywordsTerm())) { if (keywords==null) keywords = nt.getValue(); else keywords = keywords+" "+nt.getValue(); } } if (keywords==null) keywords ="."; this.writeWrappedLine(KEYWORDS_TAG, 12, keywords, os); // source line (from taxon) // organism line NCBITaxon tax = rs.getTaxon(); if (tax!=null) { String[] sciNames = (String[])tax.getNames(NCBITaxon.SCIENTIFIC).toArray(new String[0]); if (sciNames.length>0) { this.writeWrappedLine(SOURCE_TAG, 12, sciNames[0], os); this.writeWrappedLine(" "+ORGANISM_TAG, 12, sciNames[0], os); } } // references - rank (bases x to y) for (Iterator r = rs.getRankedDocRefs().iterator(); r.hasNext(); ) { RankedDocRef rdr = (RankedDocRef)r.next(); DocRef d = rdr.getDocumentReference(); this.writeWrappedLine(REFERENCE_TAG, 12, rdr.getRank()+" (bases "+rdr.getStart()+" to "+rdr.getEnd()+")", os); if (d.getAuthors()!=null) this.writeWrappedLine(" "+AUTHORS_TAG, 12, d.getAuthors(), os); this.writeWrappedLine(" "+TITLE_TAG, 12, d.getTitle(), os); this.writeWrappedLine(" "+JOURNAL_TAG, 12, d.getLocation(), os); CrossRef c = d.getCrossref(); if (c!=null) this.writeWrappedLine(" "+c.getDbname().toUpperCase(), 12, c.getAccession(), os); if (d.getRemark()!=null) this.writeWrappedLine(" "+REMARK_TAG, 12, d.getRemark(), os); } // comments - if any if (!rs.getComments().isEmpty()) { StringBuffer sb = new StringBuffer(); for (Iterator i = rs.getComments().iterator(); i.hasNext(); ) { Comment c = (SimpleComment)i.next(); sb.append(c.getComment()); if (i.hasNext()) sb.append("\n"); } this.writeWrappedLine(COMMENT_TAG, 12, sb.toString(), os); } os.println("FEATURES Location/Qualifiers"); // feature_type location for (Iterator i = rs.getFeatureSet().iterator(); i.hasNext(); ) { RichFeature f = (RichFeature)i.next(); this.writeWrappedLocationLine(" "+f.getTypeTerm().getName(), 21, GenbankLocationParser.writeLocation((RichLocation)f.getLocation()), os); for (Iterator j = f.getNoteSet().iterator(); j.hasNext(); ) { Note n = (Note)j.next(); // /key="val" this.writeWrappedLine("",21,"/"+n.getTerm().getName()+"=\""+n.getValue()+"\"", os); } // add-in to source feature only db_xref="taxon:xyz" where present if (f.getType().equals("source") && tax!=null) { this.writeWrappedLine("",21,"/db_xref=\"taxon:"+tax.getNCBITaxID()+"\"", os); } // add-in other dbxrefs where present for (Iterator j = f.getRankedCrossRefs().iterator(); j.hasNext(); ) { RankedCrossRef rcr = (RankedCrossRef)j.next(); CrossRef cr = rcr.getCrossRef(); this.writeWrappedLine("",21,"/db_xref=\""+cr.getDbname()+":"+cr.getAccession()+"\"", os); } } if (rs.getAlphabet()==AlphabetManager.alphabetForName("DNA")) { // BASE COUNT 1510 a 1074 c 835 g 1609 t int aCount = 0; int cCount = 0; int gCount = 0; int tCount = 0; int oCount = 0; for (int i = 1; i <= rs.length(); i++) { char c; try { c = tok.tokenizeSymbol(rs.symbolAt(i)).charAt(0); } catch (Exception e) { throw new RuntimeException("Unable to get symbol at position "+i,e); } switch (c) { case 'a': case 'A': aCount++; break; case 'c': case 'C': cCount++; break; case 'g': case 'G': gCount++; break; case 't': case 'T': tCount++; break; default: oCount++; } } os.print("BASE COUNT "); os.print(aCount + " a "); os.print(cCount + " c "); os.print(gCount + " g "); os.print(tCount + " t "); os.println(oCount + " others"); } os.println(START_SEQUENCE_TAG); // sequence stuff Symbol[] syms = (Symbol[])rs.toList().toArray(new Symbol[0]); int lines = 0; int symCount = 0; for (int i = 0; i < syms.length; i++) { if (symCount % 60 == 0) { if (lines > 0) os.print("\n"); // newline from previous line int lineNum = (lines*60) + 1; os.print(RichSequenceFormat.Tools.leftPad(""+lineNum,9)); lines++; } if (symCount % 10 == 0) os.print(" "); try { os.print(tok.tokenizeSymbol(syms[i])); } catch (IllegalSymbolException e) { throw new RuntimeException("Found illegal symbol: "+syms[i]); } symCount++; } os.print("\n"); os.println(END_SEQUENCE_TAG); } private void writeWrappedLine(String key, int indent, String text, PrintStream os) throws IOException { this._writeWrappedLine(key,indent,text,os,"\\s"); } private void writeWrappedLocationLine(String key, int indent, String text, PrintStream os) throws IOException { this._writeWrappedLine(key,indent,text,os,","); } private void _writeWrappedLine(String key, int indent, String text, PrintStream os, String sep) throws IOException { text = text.trim(); StringBuffer b = new StringBuffer(); b.append(RichSequenceFormat.Tools.rightPad(key, indent)); String[] lines = RichSequenceFormat.Tools.writeWordWrap(text, sep, this.getLineWidth()-indent); for (int i = 0; i<lines.length; i++) { if (i==0) b.append(lines[i]); else b.append(RichSequenceFormat.Tools.leftIndent(lines[i],indent)); // print line before continuing to next one os.println(b.toString()); b.setLength(0); } } /** * <code>getDefaultFormat</code> returns the String identifier for * the default format. * * @return a <code>String</code>. * @deprecated */ public String getDefaultFormat() { return DEFAULT_FORMAT; } public boolean getElideSymbols() { return elideSymbols; } /** * Use this method to toggle reading of sequence data. If you're only * interested in header data set to true. * @param elideSymbols set to true if you don't want the sequence data. */ public void setElideSymbols(boolean elideSymbols) { this.elideSymbols = elideSymbols; } private Vector mListeners = new Vector(); /** * Adds a parse error listener to the list of listeners if it isn't already * included. * * @param theListener Listener to be added. */ public synchronized void addParseErrorListener(ParseErrorListener theListener) { if (mListeners.contains(theListener) == false) { mListeners.addElement(theListener); } } /** * Removes a parse error listener from the list of listeners if it is * included. * * @param theListener Listener to be removed. */ public synchronized void removeParseErrorListener(ParseErrorListener theListener) { if (mListeners.contains(theListener) == true) { mListeners.removeElement(theListener); } } }
true
true
public boolean readRichSequence(BufferedReader reader, SymbolTokenization symParser, RichSeqIOListener rlistener) throws IllegalSymbolException, IOException, ParseException { String line; boolean hasAnotherSequence = true; boolean hasInternalWhitespace = false; rlistener.startSequence(); rlistener.setNamespace(RichObjectFactory.getGenbankNamespace()); // Get an ordered list of key->value pairs in array-tuples String sectionKey = null; NCBITaxon tax = null; String organism = null; String accession = null; do { List section = this.readSection(reader); sectionKey = ((String[])section.get(0))[0]; // process section-by-section if (sectionKey.equals(LOCUS_TAG)) { String loc = ((String[])section.get(0))[1]; String regex = "^(\\S+)\\s+\\d+\\s+bp\\s+([dms]s-)?(\\S+)\\s+(circular|linear)?\\s+(\\S+)\\s+(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(loc); if (m.matches()) { rlistener.setName(m.group(1)); rlistener.setDivision(m.group(5)); rlistener.addSequenceProperty(getMolTypeTerm(),m.group(3)); rlistener.addSequenceProperty(getModificationTerm(),m.group(6)); // Optional extras String stranded = m.group(2); String circular = m.group(4); if (stranded!=null) rlistener.addSequenceProperty(getStrandedTerm(),stranded); if (circular!=null && circular.equals("circular")) rlistener.setCircular(true); } else { throw new ParseException("Bad locus line found: "+loc); } } else if (sectionKey.equals(DEFINITION_TAG)) { rlistener.setDescription(((String[])section.get(0))[1]); } else if (sectionKey.equals(ACCESSION_TAG)) { // if multiple accessions, store only first as accession, // and store rest in annotation String[] accs = ((String[])section.get(0))[1].split("\\s+"); accession = accs[0].trim(); rlistener.setAccession(accession); for (int i = 1; i < accs.length; i++) { rlistener.addSequenceProperty(getAccessionTerm(),accs[i].trim()); } } else if (sectionKey.equals(VERSION_TAG)) { String ver = ((String[])section.get(0))[1]; String regex = "^(\\S+?)\\.(\\d+)\\s+GI:(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(ver); if (m.matches()) { rlistener.setVersion(Integer.parseInt(m.group(2))); rlistener.setIdentifier(m.group(3)); } else { throw new ParseException("Bad version line found: "+ver); } } else if (sectionKey.equals(KEYWORDS_TAG)) { rlistener.addSequenceProperty(getKeywordsTerm(), ((String[])section.get(0))[1]); } else if (sectionKey.equals(SOURCE_TAG)) { // ignore - can get all this from the first feature } else if (sectionKey.equals(REFERENCE_TAG)) { // first line of section has rank and location int ref_rank; int ref_start = -999; int ref_end = -999; String ref = ((String[])section.get(0))[1]; String regex = "^(\\d+)\\s*(\\(bases\\s+(\\d+)\\s+to\\s+(\\d+)\\)|\\(sites\\))?"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(ref); if (m.matches()) { ref_rank = Integer.parseInt(m.group(1)); if(m.group(2) != null){ if (m.group(3)!= null) ref_start = Integer.parseInt(m.group(3)); if(m.group(4) != null) ref_end = Integer.parseInt(m.group(4)); } } else { throw new ParseException("Bad reference line found: "+ref); } // rest can be in any order String authors = null; String title = null; String journal = null; String medline = null; String pubmed = null; String remark = null; for (int i = 1; i < section.size(); i++) { String key = ((String[])section.get(i))[0]; String val = ((String[])section.get(i))[1]; if (key.equals("AUTHORS")) authors = val; if (key.equals("TITLE")) title = val; if (key.equals("JOURNAL")) journal = val; if (key.equals("MEDLINE")) medline = val; if (key.equals("PUBMED")) pubmed = val; if (key.equals("REMARK")) authors = val; } // create the pubmed crossref and assign to the bioentry CrossRef pcr = null; if (pubmed!=null) { pcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{"PUBMED", pubmed}); RankedCrossRef rpcr = new SimpleRankedCrossRef(pcr, 0); rlistener.setRankedCrossRef(rpcr); } // create the medline crossref and assign to the bioentry CrossRef mcr = null; if (medline!=null) { mcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{"MEDLINE", medline}); RankedCrossRef rmcr = new SimpleRankedCrossRef(mcr, 0); rlistener.setRankedCrossRef(rmcr); } // create the docref object try { DocRef dr = (DocRef)RichObjectFactory.getObject(SimpleDocRef.class,new Object[]{authors,journal}); if (title!=null) dr.setTitle(title); // assign either the pubmed or medline to the docref if (pcr!=null) dr.setCrossref(pcr); else if (mcr!=null) dr.setCrossref(mcr); // assign the remarks dr.setRemark(remark); // assign the docref to the bioentry RankedDocRef rdr = new SimpleRankedDocRef(dr, (ref_start != -999 ? new Integer(ref_start) : null), (ref_end != -999 ? new Integer(ref_end) : null), ref_rank); rlistener.setRankedDocRef(rdr); } catch (ChangeVetoException e) { throw new ParseException(e); } } else if (sectionKey.equals(COMMENT_TAG)) { // Set up some comments rlistener.setComment(((String[])section.get(0))[1]); } else if (sectionKey.equals(FEATURE_TAG)) { // starting from second line of input, start a new feature whenever we come across // a value that does not start with " boolean seenAFeature = false; for (int i = 1 ; i < section.size(); i++) { String key = ((String[])section.get(i))[0]; String val = ((String[])section.get(i))[1]; if (key.startsWith("/")) { key = key.substring(1); // strip leading slash val = val.trim().replaceAll("\"",""); // strip quotes // parameter on old feature if (key.equals("db_xref")) { String regex = "^(\\S+?):(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(val); if (m.matches()) { String dbname = m.group(1); String raccession = m.group(2); if (dbname.equals("taxon")) { // Set the Taxon instead of a dbxref tax = (NCBITaxon)RichObjectFactory.getObject(SimpleNCBITaxon.class, new Object[]{Integer.valueOf(raccession)}); rlistener.setTaxon(tax); try { if (organism!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism); } catch (ChangeVetoException e) { throw new ParseException(e); } } else { try { CrossRef cr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{dbname, raccession}); RankedCrossRef rcr = new SimpleRankedCrossRef(cr, 0); rlistener.getCurrentFeature().addRankedCrossRef(rcr); } catch (ChangeVetoException e) { throw new ParseException(e); } } } else { throw new ParseException("Bad dbxref found: "+val); } } else if (key.equals("organism")) { try { organism = val; if (tax!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism); } catch (ChangeVetoException e) { throw new ParseException(e); } } else { if (key.equals("translation")) { // strip spaces from sequence val = val.replaceAll("\\s+",""); } rlistener.addFeatureProperty(RichObjectFactory.getDefaultOntology().getOrCreateTerm(key),val); } } else { // new feature! // end previous feature if (seenAFeature) rlistener.endFeature(); // start next one, with lots of lovely info in it RichFeature.Template templ = new RichFeature.Template(); templ.annotation = new SimpleRichAnnotation(); templ.sourceTerm = getGenBankTerm(); templ.typeTerm = RichObjectFactory.getDefaultOntology().getOrCreateTerm(key); templ.featureRelationshipSet = new TreeSet(); templ.rankedCrossRefs = new TreeSet(); String tidyLocStr = val.replaceAll("\\s+",""); templ.location = GenbankLocationParser.parseLocation(RichObjectFactory.getDefaultLocalNamespace(), accession, tidyLocStr); rlistener.startFeature(templ); seenAFeature = true; } } if (seenAFeature) rlistener.endFeature(); } else if (sectionKey.equals(BASE_COUNT_TAG)) { // ignore - can calculate from sequence content later if needed } else if (sectionKey.equals(START_SEQUENCE_TAG) && !this.elideSymbols) { // our first line is ignorable as it is the ORIGIN tag // the second line onwards conveniently have the number as // the [0] tuple, and sequence string as [1] so all we have // to do is concat the [1] parts and then strip out spaces, // and replace '.' and '~' with '-' for our parser. StringBuffer seq = new StringBuffer(); for (int i = 1 ; i < section.size(); i++) seq.append(((String[])section.get(i))[1]); try { SymbolList sl = new SimpleSymbolList(symParser, seq.toString().replaceAll("\\s+","").replaceAll("[\\.|~]","-")); rlistener.addSymbols(symParser.getAlphabet(), (Symbol[])(sl.toList().toArray(new Symbol[0])), 0, sl.length()); } catch (Exception e) { throw new ParseException(e); } } } while (!sectionKey.equals(END_SEQUENCE_TAG)); // Allows us to tolerate trailing whitespace without // thinking that there is another Sequence to follow while (true) { reader.mark(1); int c = reader.read(); if (c == -1) { hasAnotherSequence = false; break; } if (Character.isWhitespace((char) c)) { hasInternalWhitespace = true; continue; } if (hasInternalWhitespace) System.err.println("Warning: whitespace found between sequence entries"); reader.reset(); break; } // Finish up. rlistener.endSequence(); return hasAnotherSequence; }
public boolean readRichSequence(BufferedReader reader, SymbolTokenization symParser, RichSeqIOListener rlistener) throws IllegalSymbolException, IOException, ParseException { String line; boolean hasAnotherSequence = true; boolean hasInternalWhitespace = false; rlistener.startSequence(); rlistener.setNamespace(RichObjectFactory.getGenbankNamespace()); // Get an ordered list of key->value pairs in array-tuples String sectionKey = null; NCBITaxon tax = null; String organism = null; String accession = null; do { List section = this.readSection(reader); sectionKey = ((String[])section.get(0))[0]; // process section-by-section if (sectionKey.equals(LOCUS_TAG)) { String loc = ((String[])section.get(0))[1]; String regex = "^(\\S+)\\s+\\d+\\s+bp\\s+([dms]s-)?(\\S+)\\s+(circular|linear)?\\s+(\\S+)\\s+(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(loc); if (m.matches()) { rlistener.setName(m.group(1)); rlistener.setDivision(m.group(5)); rlistener.addSequenceProperty(getMolTypeTerm(),m.group(3)); rlistener.addSequenceProperty(getModificationTerm(),m.group(6)); // Optional extras String stranded = m.group(2); String circular = m.group(4); if (stranded!=null) rlistener.addSequenceProperty(getStrandedTerm(),stranded); if (circular!=null && circular.equals("circular")) rlistener.setCircular(true); } else { throw new ParseException("Bad locus line found: "+loc); } } else if (sectionKey.equals(DEFINITION_TAG)) { rlistener.setDescription(((String[])section.get(0))[1]); } else if (sectionKey.equals(ACCESSION_TAG)) { // if multiple accessions, store only first as accession, // and store rest in annotation String[] accs = ((String[])section.get(0))[1].split("\\s+"); accession = accs[0].trim(); rlistener.setAccession(accession); for (int i = 1; i < accs.length; i++) { rlistener.addSequenceProperty(getAccessionTerm(),accs[i].trim()); } } else if (sectionKey.equals(VERSION_TAG)) { String ver = ((String[])section.get(0))[1]; String regex = "^(\\S+?)\\.(\\d+)\\s+GI:(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(ver); if (m.matches()) { rlistener.setVersion(Integer.parseInt(m.group(2))); rlistener.setIdentifier(m.group(3)); } else { throw new ParseException("Bad version line found: "+ver); } } else if (sectionKey.equals(KEYWORDS_TAG)) { rlistener.addSequenceProperty(getKeywordsTerm(), ((String[])section.get(0))[1]); } else if (sectionKey.equals(SOURCE_TAG)) { // ignore - can get all this from the first feature } else if (sectionKey.equals(REFERENCE_TAG)) { // first line of section has rank and location int ref_rank; int ref_start = -999; int ref_end = -999; String ref = ((String[])section.get(0))[1]; String regex = "^(\\d+)\\s*(\\(bases\\s+(\\d+)\\s+to\\s+(\\d+)\\)|\\(sites\\))?"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(ref); if (m.matches()) { ref_rank = Integer.parseInt(m.group(1)); if(m.group(2) != null){ if (m.group(3)!= null) ref_start = Integer.parseInt(m.group(3)); if(m.group(4) != null) ref_end = Integer.parseInt(m.group(4)); } } else { throw new ParseException("Bad reference line found: "+ref); } // rest can be in any order String authors = null; String title = null; String journal = null; String medline = null; String pubmed = null; String remark = null; for (int i = 1; i < section.size(); i++) { String key = ((String[])section.get(i))[0]; String val = ((String[])section.get(i))[1]; if (key.equals("AUTHORS")) authors = val; if (key.equals("TITLE")) title = val; if (key.equals("JOURNAL")) journal = val; if (key.equals("MEDLINE")) medline = val; if (key.equals("PUBMED")) pubmed = val; if (key.equals("REMARK")) authors = val; } // create the pubmed crossref and assign to the bioentry CrossRef pcr = null; if (pubmed!=null) { pcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{"PUBMED", pubmed}); RankedCrossRef rpcr = new SimpleRankedCrossRef(pcr, 0); rlistener.setRankedCrossRef(rpcr); } // create the medline crossref and assign to the bioentry CrossRef mcr = null; if (medline!=null) { mcr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{"MEDLINE", medline}); RankedCrossRef rmcr = new SimpleRankedCrossRef(mcr, 0); rlistener.setRankedCrossRef(rmcr); } // create the docref object try { DocRef dr = (DocRef)RichObjectFactory.getObject(SimpleDocRef.class,new Object[]{authors,journal}); if (title!=null) dr.setTitle(title); // assign either the pubmed or medline to the docref if (pcr!=null) dr.setCrossref(pcr); else if (mcr!=null) dr.setCrossref(mcr); // assign the remarks dr.setRemark(remark); // assign the docref to the bioentry RankedDocRef rdr = new SimpleRankedDocRef(dr, (ref_start != -999 ? new Integer(ref_start) : null), (ref_end != -999 ? new Integer(ref_end) : null), ref_rank); rlistener.setRankedDocRef(rdr); } catch (ChangeVetoException e) { throw new ParseException(e); } } else if (sectionKey.equals(COMMENT_TAG)) { // Set up some comments rlistener.setComment(((String[])section.get(0))[1]); } else if (sectionKey.equals(FEATURE_TAG)) { // starting from second line of input, start a new feature whenever we come across // a value that does not start with " boolean seenAFeature = false; for (int i = 1 ; i < section.size(); i++) { String key = ((String[])section.get(i))[0]; String val = ((String[])section.get(i))[1]; if (key.startsWith("/")) { key = key.substring(1); // strip leading slash val = val.replaceAll("\"","").trim(); // strip quotes // parameter on old feature if (key.equals("db_xref")) { String regex = "^(\\S+?):(\\S+)$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(val); if (m.matches()) { String dbname = m.group(1); String raccession = m.group(2); if (dbname.equals("taxon")) { // Set the Taxon instead of a dbxref tax = (NCBITaxon)RichObjectFactory.getObject(SimpleNCBITaxon.class, new Object[]{Integer.valueOf(raccession)}); rlistener.setTaxon(tax); try { if (organism!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism); } catch (ChangeVetoException e) { throw new ParseException(e); } } else { try { CrossRef cr = (CrossRef)RichObjectFactory.getObject(SimpleCrossRef.class,new Object[]{dbname, raccession}); RankedCrossRef rcr = new SimpleRankedCrossRef(cr, 0); rlistener.getCurrentFeature().addRankedCrossRef(rcr); } catch (ChangeVetoException e) { throw new ParseException(e); } } } else { throw new ParseException("Bad dbxref found: "+val); } } else if (key.equals("organism")) { try { organism = val; if (tax!=null) tax.addName(NCBITaxon.SCIENTIFIC,organism); } catch (ChangeVetoException e) { throw new ParseException(e); } } else { if (key.equals("translation")) { // strip spaces from sequence val = val.replaceAll("\\s+",""); } rlistener.addFeatureProperty(RichObjectFactory.getDefaultOntology().getOrCreateTerm(key),val); } } else { // new feature! // end previous feature if (seenAFeature) rlistener.endFeature(); // start next one, with lots of lovely info in it RichFeature.Template templ = new RichFeature.Template(); templ.annotation = new SimpleRichAnnotation(); templ.sourceTerm = getGenBankTerm(); templ.typeTerm = RichObjectFactory.getDefaultOntology().getOrCreateTerm(key); templ.featureRelationshipSet = new TreeSet(); templ.rankedCrossRefs = new TreeSet(); String tidyLocStr = val.replaceAll("\\s+",""); templ.location = GenbankLocationParser.parseLocation(RichObjectFactory.getDefaultLocalNamespace(), accession, tidyLocStr); rlistener.startFeature(templ); seenAFeature = true; } } if (seenAFeature) rlistener.endFeature(); } else if (sectionKey.equals(BASE_COUNT_TAG)) { // ignore - can calculate from sequence content later if needed } else if (sectionKey.equals(START_SEQUENCE_TAG) && !this.elideSymbols) { // our first line is ignorable as it is the ORIGIN tag // the second line onwards conveniently have the number as // the [0] tuple, and sequence string as [1] so all we have // to do is concat the [1] parts and then strip out spaces, // and replace '.' and '~' with '-' for our parser. StringBuffer seq = new StringBuffer(); for (int i = 1 ; i < section.size(); i++) seq.append(((String[])section.get(i))[1]); try { SymbolList sl = new SimpleSymbolList(symParser, seq.toString().replaceAll("\\s+","").replaceAll("[\\.|~]","-")); rlistener.addSymbols(symParser.getAlphabet(), (Symbol[])(sl.toList().toArray(new Symbol[0])), 0, sl.length()); } catch (Exception e) { throw new ParseException(e); } } } while (!sectionKey.equals(END_SEQUENCE_TAG)); // Allows us to tolerate trailing whitespace without // thinking that there is another Sequence to follow while (true) { reader.mark(1); int c = reader.read(); if (c == -1) { hasAnotherSequence = false; break; } if (Character.isWhitespace((char) c)) { hasInternalWhitespace = true; continue; } if (hasInternalWhitespace) System.err.println("Warning: whitespace found between sequence entries"); reader.reset(); break; } // Finish up. rlistener.endSequence(); return hasAnotherSequence; }
diff --git a/src/org/waveprotocol/box/server/persistence/memory/MemoryDeltaCollection.java b/src/org/waveprotocol/box/server/persistence/memory/MemoryDeltaCollection.java index 383a3b28..1f627199 100644 --- a/src/org/waveprotocol/box/server/persistence/memory/MemoryDeltaCollection.java +++ b/src/org/waveprotocol/box/server/persistence/memory/MemoryDeltaCollection.java @@ -1,120 +1,122 @@ /** * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.waveprotocol.box.server.persistence.memory; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.protobuf.InvalidProtocolBufferException; import org.waveprotocol.box.server.waveserver.ByteStringMessage; import org.waveprotocol.box.server.waveserver.WaveletDeltaRecord; import org.waveprotocol.box.server.waveserver.DeltaStore.DeltasAccess; import org.waveprotocol.wave.federation.Proto.ProtocolAppliedWaveletDelta; import org.waveprotocol.wave.model.id.WaveletName; import org.waveprotocol.wave.model.operation.wave.TransformedWaveletDelta; import org.waveprotocol.wave.model.version.HashedVersion; import java.util.Collection; import java.util.Map; /** * An in-memory implementation of DeltasAccess * * @author [email protected] (Joseph Gentle) */ public class MemoryDeltaCollection implements DeltasAccess { private final Map<Long, WaveletDeltaRecord> deltas = Maps.newHashMap(); private final Map<Long, WaveletDeltaRecord> endDeltas = Maps.newHashMap(); private final WaveletName waveletName; private HashedVersion endVersion = null; public MemoryDeltaCollection(WaveletName waveletName) { Preconditions.checkNotNull(waveletName); this.waveletName = waveletName; } @Override public boolean isEmpty() { return deltas.isEmpty(); } @Override public WaveletName getWaveletName() { return waveletName; } @Override public HashedVersion getEndVersion() { return endVersion; } @Override public WaveletDeltaRecord getDelta(long version) { return deltas.get(version); } @Override public WaveletDeltaRecord getDeltaByEndVersion(long version) { return endDeltas.get(version); } @Override public HashedVersion getAppliedAtVersion(long version) throws InvalidProtocolBufferException { WaveletDeltaRecord delta = getDelta(version); return (delta != null) ? delta.getAppliedAtVersion() : null; } @Override public HashedVersion getResultingVersion(long version) { WaveletDeltaRecord delta = getDelta(version); return (delta != null) ? delta.transformed.getResultingVersion() : null; } @Override public ByteStringMessage<ProtocolAppliedWaveletDelta> getAppliedDelta(long version) { WaveletDeltaRecord delta = getDelta(version); return (delta != null) ? delta.applied : null; } @Override public TransformedWaveletDelta getTransformedDelta(long version) { WaveletDeltaRecord delta = getDelta(version); return (delta != null) ? delta.transformed : null; } @Override public void close() { // Does nothing. } @Override public void append(Collection<WaveletDeltaRecord> newDeltas) { for (WaveletDeltaRecord delta : newDeltas) { // Before: ... | D | // start end // After: ... | D | D + 1 | // start end long startVersion = delta.transformed.getAppliedAtVersion(); - Preconditions.checkState(startVersion == endVersion.getVersion()); + Preconditions.checkState( + (startVersion == 0 && endVersion == null) || + (startVersion == endVersion.getVersion())); deltas.put(startVersion, delta); endVersion = delta.transformed.getResultingVersion(); endDeltas.put(endVersion.getVersion(), delta); } } }
true
true
public void append(Collection<WaveletDeltaRecord> newDeltas) { for (WaveletDeltaRecord delta : newDeltas) { // Before: ... | D | // start end // After: ... | D | D + 1 | // start end long startVersion = delta.transformed.getAppliedAtVersion(); Preconditions.checkState(startVersion == endVersion.getVersion()); deltas.put(startVersion, delta); endVersion = delta.transformed.getResultingVersion(); endDeltas.put(endVersion.getVersion(), delta); } }
public void append(Collection<WaveletDeltaRecord> newDeltas) { for (WaveletDeltaRecord delta : newDeltas) { // Before: ... | D | // start end // After: ... | D | D + 1 | // start end long startVersion = delta.transformed.getAppliedAtVersion(); Preconditions.checkState( (startVersion == 0 && endVersion == null) || (startVersion == endVersion.getVersion())); deltas.put(startVersion, delta); endVersion = delta.transformed.getResultingVersion(); endDeltas.put(endVersion.getVersion(), delta); } }
diff --git a/nuxeo-core-facade/src/main/java/org/nuxeo/ecm/core/jms/CoreEventPublisher.java b/nuxeo-core-facade/src/main/java/org/nuxeo/ecm/core/jms/CoreEventPublisher.java index cccb8fa85..30f65e472 100644 --- a/nuxeo-core-facade/src/main/java/org/nuxeo/ecm/core/jms/CoreEventPublisher.java +++ b/nuxeo-core-facade/src/main/java/org/nuxeo/ecm/core/jms/CoreEventPublisher.java @@ -1,172 +1,172 @@ /* * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * bstefanescu * * $Id$ */ package org.nuxeo.ecm.core.jms; import java.io.Serializable; import java.util.Properties; import javax.jms.DeliveryMode; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicPublisher; import javax.jms.TopicSession; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.runtime.api.Framework; /** * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> * */ public class CoreEventPublisher { private static final Log log = LogFactory.getLog(CoreEventPublisher.class); public final static String XA_TOPIC_CONNECTION_FACTORY = "JmsNX"; public final static String CORE_EVENTS_TOPIC = "topic/NXCoreEvents"; private boolean transacted; private boolean isDeliveryPersistent; private boolean isDisableMessageID; private boolean isDisableMessageTimestamp; private TopicConnectionFactory topicConnectionFactory; private Topic coreEventsTopic; private static CoreEventPublisher instance = new CoreEventPublisher(); private CoreEventPublisher() { configureJMS(); } private void configureJMS() { Properties runtime = Framework.getRuntime().getProperties(); transacted = new Boolean(runtime.getProperty("jms.useTransactedConnection")); isDeliveryPersistent = new Boolean(runtime.getProperty("jms.isDeliveryPersistent")); isDisableMessageID = new Boolean(runtime.getProperty("jms.isDisableMessageID")); isDisableMessageTimestamp = new Boolean(runtime.getProperty("jms.isDisableMessageTimestamp")); } public static CoreEventPublisher getInstance() { return instance; } public void reset() { topicConnectionFactory = null; coreEventsTopic = null; } private final TopicConnectionFactory getTopicConnectionFactory() throws NamingException { if (topicConnectionFactory == null) { Context jndi = new InitialContext(); topicConnectionFactory = (TopicConnectionFactory) jndi.lookup(XA_TOPIC_CONNECTION_FACTORY); if (coreEventsTopic == null) { // initialize the default topic too coreEventsTopic = (Topic) jndi.lookup(CORE_EVENTS_TOPIC); } } return topicConnectionFactory; } private final Topic getDefaultTopic() throws NamingException { if (coreEventsTopic == null) { Context jndi = new InitialContext(); coreEventsTopic = (Topic) jndi.lookup(CORE_EVENTS_TOPIC); if (topicConnectionFactory == null) { // initialize the connection factory too topicConnectionFactory = (TopicConnectionFactory) jndi.lookup(XA_TOPIC_CONNECTION_FACTORY); } } return coreEventsTopic; } /** * Retrieves a new JMS Connection from the pool * * @return a <code>QueueConnection</code> * @throws JMSException if the connection could not be retrieved */ private TopicConnection getTopicConnection() throws JMSException { try { return getTopicConnectionFactory().createTopicConnection(); } catch (NamingException e) { log.error("Failed too lookup topic connection factory", e); throw new JMSException("Failed to lookup topic connection factory: "+e.getMessage()); } } public void publish(Serializable content, String eventId) throws JMSException { try { publish(content, getDefaultTopic(), MessageFactory.DEFAULT, eventId); } catch (NamingException e) { log.error("Failed to lookup default topic", e); throw new JMSException("Failed to lookup default topic"); } } public void publish(Topic topic, Serializable content, String eventId) throws JMSException { publish(content, topic, MessageFactory.DEFAULT, eventId); } public void publish(Object content, Topic topic, MessageFactory factory, String eventId) throws JMSException { TopicConnection connection = null; TopicSession session = null; TopicPublisher publisher = null; try { // get a connection from topic connection pool connection = getTopicConnection(); // create a not transacted session session = connection.createTopicSession(transacted, TopicSession.AUTO_ACKNOWLEDGE); // create the publisher publisher = session.createPublisher(topic); publisher.setDeliveryMode(isDeliveryPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); publisher.setDisableMessageID(isDisableMessageID); publisher.setDisableMessageTimestamp(isDisableMessageTimestamp); // create the message using the given factory Message msg = factory.createMessage(session, content); if(eventId != null) { - msg.setStringProperty("nuxeo.eventId", eventId); + msg.setStringProperty("NuxeoEventId", eventId); } // publish the message publisher.publish(topic, msg); } finally { if (publisher != null) { publisher.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } } public MessagePublisher createPublisher() throws NamingException, JMSException { return new MessagePublisher(getDefaultTopic(), getTopicConnectionFactory()); } }
true
true
public void publish(Object content, Topic topic, MessageFactory factory, String eventId) throws JMSException { TopicConnection connection = null; TopicSession session = null; TopicPublisher publisher = null; try { // get a connection from topic connection pool connection = getTopicConnection(); // create a not transacted session session = connection.createTopicSession(transacted, TopicSession.AUTO_ACKNOWLEDGE); // create the publisher publisher = session.createPublisher(topic); publisher.setDeliveryMode(isDeliveryPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); publisher.setDisableMessageID(isDisableMessageID); publisher.setDisableMessageTimestamp(isDisableMessageTimestamp); // create the message using the given factory Message msg = factory.createMessage(session, content); if(eventId != null) { msg.setStringProperty("nuxeo.eventId", eventId); } // publish the message publisher.publish(topic, msg); } finally { if (publisher != null) { publisher.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }
public void publish(Object content, Topic topic, MessageFactory factory, String eventId) throws JMSException { TopicConnection connection = null; TopicSession session = null; TopicPublisher publisher = null; try { // get a connection from topic connection pool connection = getTopicConnection(); // create a not transacted session session = connection.createTopicSession(transacted, TopicSession.AUTO_ACKNOWLEDGE); // create the publisher publisher = session.createPublisher(topic); publisher.setDeliveryMode(isDeliveryPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); publisher.setDisableMessageID(isDisableMessageID); publisher.setDisableMessageTimestamp(isDisableMessageTimestamp); // create the message using the given factory Message msg = factory.createMessage(session, content); if(eventId != null) { msg.setStringProperty("NuxeoEventId", eventId); } // publish the message publisher.publish(topic, msg); } finally { if (publisher != null) { publisher.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }
diff --git a/freeplane/src/org/freeplane/core/io/xml/XMLParser.java b/freeplane/src/org/freeplane/core/io/xml/XMLParser.java index bd312d997..910646458 100644 --- a/freeplane/src/org/freeplane/core/io/xml/XMLParser.java +++ b/freeplane/src/org/freeplane/core/io/xml/XMLParser.java @@ -1,122 +1,123 @@ /* * 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.core.io.xml; import java.io.IOException; import java.util.Properties; import org.freeplane.n3.nanoxml.IXMLParser; import org.freeplane.n3.nanoxml.IXMLReader; import org.freeplane.n3.nanoxml.StdXMLParser; import org.freeplane.n3.nanoxml.XMLParseException; class XMLParser extends StdXMLParser implements IXMLParser { private boolean skipNextElementContent = false; void notParseNextElementContent() { skipNextElementContent = true; } @Override protected void processElement(final String defaultNamespace, final Properties namespaces) throws Exception { try { super.processElement(defaultNamespace, namespaces); } finally { skipNextElementContent = false; } } @Override protected void processElementContent(final String defaultNamespace, final Properties namespaces, final String fullName, final String name, final String prefix) throws IOException, XMLParseException, Exception { if (skipNextElementContent) { boolean inComment = false; final TreeXmlReader builder = (TreeXmlReader) getBuilder(); final StringBuilder waitingBuf = new StringBuilder(); int level = 1; for (;;) { final IXMLReader reader = getReader(); char ch = reader.read(); if (inComment) { waitingBuf.append(ch); if (ch != '-') { continue; } ch = reader.read(); waitingBuf.append(ch); if (ch != '-') { continue; } ch = reader.read(); waitingBuf.append(ch); if (ch != '>') { continue; } inComment = false; continue; } if (ch == '<') { ch = reader.read(); if (ch == '/') { level--; if (level == 0) { break; } } else if (ch == '!') { final char read1 = reader.read(); final char read2 = reader.read(); if (read1 != '-' || read2 != '-') { throw new XMLParseException(reader.getSystemID(), reader.getLineNr(), "Invalid input: <!" + read1 + read2); } inComment = true; waitingBuf.append("<!--"); + continue; } else { level++; } waitingBuf.append('<'); } else if (ch == '/') { ch = reader.read(); if (ch == '>') { level--; if (level == 0) { throw new XMLParseException(reader.getSystemID(), reader.getLineNr(), "Invalid input: />"); } } else if (ch == '<') { waitingBuf.append('/'); reader.unread(ch); continue; } waitingBuf.append('/'); } waitingBuf.append(ch); } builder.setElementContent(waitingBuf.toString().trim()); return; } super.processElementContent(defaultNamespace, namespaces, fullName, name, prefix); } }
true
true
protected void processElementContent(final String defaultNamespace, final Properties namespaces, final String fullName, final String name, final String prefix) throws IOException, XMLParseException, Exception { if (skipNextElementContent) { boolean inComment = false; final TreeXmlReader builder = (TreeXmlReader) getBuilder(); final StringBuilder waitingBuf = new StringBuilder(); int level = 1; for (;;) { final IXMLReader reader = getReader(); char ch = reader.read(); if (inComment) { waitingBuf.append(ch); if (ch != '-') { continue; } ch = reader.read(); waitingBuf.append(ch); if (ch != '-') { continue; } ch = reader.read(); waitingBuf.append(ch); if (ch != '>') { continue; } inComment = false; continue; } if (ch == '<') { ch = reader.read(); if (ch == '/') { level--; if (level == 0) { break; } } else if (ch == '!') { final char read1 = reader.read(); final char read2 = reader.read(); if (read1 != '-' || read2 != '-') { throw new XMLParseException(reader.getSystemID(), reader.getLineNr(), "Invalid input: <!" + read1 + read2); } inComment = true; waitingBuf.append("<!--"); } else { level++; } waitingBuf.append('<'); } else if (ch == '/') { ch = reader.read(); if (ch == '>') { level--; if (level == 0) { throw new XMLParseException(reader.getSystemID(), reader.getLineNr(), "Invalid input: />"); } } else if (ch == '<') { waitingBuf.append('/'); reader.unread(ch); continue; } waitingBuf.append('/'); } waitingBuf.append(ch); } builder.setElementContent(waitingBuf.toString().trim()); return; } super.processElementContent(defaultNamespace, namespaces, fullName, name, prefix); }
protected void processElementContent(final String defaultNamespace, final Properties namespaces, final String fullName, final String name, final String prefix) throws IOException, XMLParseException, Exception { if (skipNextElementContent) { boolean inComment = false; final TreeXmlReader builder = (TreeXmlReader) getBuilder(); final StringBuilder waitingBuf = new StringBuilder(); int level = 1; for (;;) { final IXMLReader reader = getReader(); char ch = reader.read(); if (inComment) { waitingBuf.append(ch); if (ch != '-') { continue; } ch = reader.read(); waitingBuf.append(ch); if (ch != '-') { continue; } ch = reader.read(); waitingBuf.append(ch); if (ch != '>') { continue; } inComment = false; continue; } if (ch == '<') { ch = reader.read(); if (ch == '/') { level--; if (level == 0) { break; } } else if (ch == '!') { final char read1 = reader.read(); final char read2 = reader.read(); if (read1 != '-' || read2 != '-') { throw new XMLParseException(reader.getSystemID(), reader.getLineNr(), "Invalid input: <!" + read1 + read2); } inComment = true; waitingBuf.append("<!--"); continue; } else { level++; } waitingBuf.append('<'); } else if (ch == '/') { ch = reader.read(); if (ch == '>') { level--; if (level == 0) { throw new XMLParseException(reader.getSystemID(), reader.getLineNr(), "Invalid input: />"); } } else if (ch == '<') { waitingBuf.append('/'); reader.unread(ch); continue; } waitingBuf.append('/'); } waitingBuf.append(ch); } builder.setElementContent(waitingBuf.toString().trim()); return; } super.processElementContent(defaultNamespace, namespaces, fullName, name, prefix); }
diff --git a/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java b/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java index 222dbfcc0..77d5a32e6 100644 --- a/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java +++ b/TFC_Shared/src/TFC/Entities/Mobs/EntitySheepTFC.java @@ -1,463 +1,467 @@ package TFC.Entities.Mobs; import java.util.ArrayList; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAITempt; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.IShearable; import TFC.TFCItems; import TFC.API.Entities.IAnimal; import TFC.Core.TFC_Core; import TFC.Core.TFC_Time; import TFC.Entities.AI.AIEatGrass; import TFC.Entities.AI.EntityAIMateTFC; public class EntitySheepTFC extends EntitySheep implements IShearable, IAnimal { /** * Holds the RGB table of the sheep colors - in OpenGL glColor3f values - used to render the sheep colored fleece. */ public static final float[][] fleeceColorTable = new float[][] {{1.0F, 1.0F, 1.0F}, {0.95F, 0.7F, 0.2F}, {0.9F, 0.5F, 0.85F}, {0.6F, 0.7F, 0.95F}, {0.9F, 0.9F, 0.2F}, {0.5F, 0.8F, 0.1F}, {0.95F, 0.7F, 0.8F}, {0.3F, 0.3F, 0.3F}, {0.6F, 0.6F, 0.6F}, {0.3F, 0.6F, 0.7F}, {0.7F, 0.4F, 0.9F}, {0.2F, 0.4F, 0.8F}, {0.5F, 0.4F, 0.3F}, {0.4F, 0.5F, 0.2F}, {0.8F, 0.3F, 0.3F}, {0.1F, 0.1F, 0.1F}}; /** * Used to control movement as well as wool regrowth. Set to 40 on handleHealthUpdate and counts down with each * tick. */ private int sheepTimer; /** The eat grass AI task for this mob. */ public AIEatGrass aiEatGrass = new AIEatGrass(this); int degreeOfDiversion = 4; protected long animalID; protected int sex = 0; protected int hunger; protected long hasMilkTime; protected boolean pregnant; protected int pregnancyRequiredTime; protected long timeOfConception; protected float mateSizeMod; public float size_mod = 1f; public boolean inLove; public EntitySheepTFC(World par1World) { super(par1World); this.setSize(0.9F, 1.3F); float var2 = 0.23F; this.getNavigator().setAvoidsWater(true); this.tasks.addTask(2, new EntityAIMateTFC(this,worldObj, var2)); this.tasks.addTask(3, new EntityAITempt(this, 1.2F, TFCItems.WheatGrain.itemID, false)); this.tasks.addTask(6, this.aiEatGrass); hunger = 168000; animalID = TFC_Time.getTotalTicks() + entityId; pregnant = false; pregnancyRequiredTime = (int) (4 * TFC_Time.ticksInMonth); timeOfConception = 0; mateSizeMod = 0; sex = rand.nextInt(2); size_mod = (((rand.nextInt (degreeOfDiversion+1)*(rand.nextBoolean()?1:-1)) / 10f) + 1F) * (1.0F - 0.1F * sex); // We hijack the growingAge to hold the day of birth rather // than number of ticks to next growth event. We want spawned // animals to be adults, so we set their birthdays far enough back // in time such that they reach adulthood now. // this.setAge((int) TFC_Time.getTotalDays() - getNumberOfDaysToAdult()); //For Testing Only(makes spawned animals into babies) //this.setGrowingAge((int) TFC_Time.getTotalDays()); } public EntitySheepTFC(World par1World,IAnimal mother, float F_size) { this(par1World); this.posX = ((EntityLivingBase)mother).posX; this.posY = ((EntityLivingBase)mother).posY; this.posZ = ((EntityLivingBase)mother).posZ; size_mod = (((rand.nextInt (degreeOfDiversion+1)*(rand.nextBoolean()?1:-1)) / 10f) + 1F) * (1.0F - 0.1F * sex) * (float)Math.sqrt((mother.getSize() + F_size)/1.9F); size_mod = Math.min(Math.max(size_mod, 0.7F),1.3f); // We hijack the growingAge to hold the day of birth rather // than number of ticks to next growth event. // this.setAge((int) TFC_Time.getTotalDays()); } @Override protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(13, new Integer(0)); this.dataWatcher.addObject(14, new Float(1)); this.dataWatcher.addObject(15, Integer.valueOf(0)); } @Override protected void func_110147_ax() { super.func_110147_ax(); this.func_110148_a(SharedMonsterAttributes.field_111267_a).func_111128_a(400);//MaxHealth } @Override protected void updateAITasks() { this.sheepTimer = this.aiEatGrass.getEatGrassTick(); super.updateAITasks(); } private float getPercentGrown(IAnimal animal) { float birth = animal.getBirthDay(); float time = (int) TFC_Time.getTotalDays(); float percent =(time-birth)/animal.getNumberOfDaysToAdult(); return Math.min(percent, 1f); } /** * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons * use this to react to sunlight and start to burn. */ @Override public void onLivingUpdate() { if (this.worldObj.isRemote) { this.sheepTimer = Math.max(0, this.sheepTimer - 1); } //Handle Hunger ticking if (hunger > 168000) { hunger = 168000; } if (hunger > 0) { hunger--; } if(super.inLove > 0){ super.inLove = 0; setInLove(true); } syncData(); if(isAdult()){ setGrowingAge(0); } else{ setGrowingAge(-1); } if(isPregnant()) { if(TFC_Time.getTotalTicks() >= timeOfConception + pregnancyRequiredTime) { int i = rand.nextInt(3) + 1; for (int x = 0; x<i;x++) { EntitySheepTFC baby = new EntitySheepTFC(worldObj, this, mateSizeMod); + baby.setLocationAndAngles (posX+(rand.nextFloat()-0.5F)*2F,posY,posZ+(rand.nextFloat()-0.5F)*2F, 0.0F, 0.0F); + baby.rotationYawHead = baby.rotationYaw; + baby.renderYawOffset = baby.rotationYaw; worldObj.spawnEntityInWorld(baby); + baby.setAge((int)TFC_Time.getTotalDays()); } pregnant = false; } } /** * This Cancels out the changes made to growingAge by EntityAgeable * */ TFC_Core.PreventEntityDataUpdate = true; super.onLivingUpdate(); TFC_Core.PreventEntityDataUpdate = false; if (hunger > 144000 && rand.nextInt (100) == 0 && func_110143_aJ() < TFC_Core.getEntityMaxHealth(this) && !isDead) { this.heal(1); } } public void syncData() { if(dataWatcher!= null) { if(!this.worldObj.isRemote){ this.dataWatcher.updateObject(13, Integer.valueOf(sex)); this.dataWatcher.updateObject(14, Float.valueOf(size_mod)); } else{ sex = this.dataWatcher.getWatchableObjectInt(13); size_mod = this.dataWatcher.func_111145_d(14); } } } @Override public void eatGrassBonus() { this.setSheared(false); hunger += 24000; } /** * Drop 0-2 items of this living's type */ @Override protected void dropFewItems(boolean par1, int par2) { float ageMod = TFC_Core.getPercentGrown(this); if(this.isAdult()){ if(!this.getSheared()) { this.entityDropItem(new ItemStack(TFCItems.SheepSkin,1), 0.0F); } else { this.dropItem(TFCItems.Hide.itemID,1); } this.dropItem(Item.bone.itemID, rand.nextInt(5)+2); } if (this.isBurning()) { this.dropItem(TFCItems.muttonCooked.itemID,(int)(ageMod*this.size_mod *(5+rand.nextInt(5)))); } else { this.dropItem(TFCItems.muttonRaw.itemID,(int)(ageMod*this.size_mod *(5+rand.nextInt(5)))); } } @Override public boolean isBreedingItem(ItemStack par1ItemStack) { return !pregnant&&(par1ItemStack.getItem() == TFCItems.WheatGrain ||par1ItemStack.getItem() == TFCItems.OatGrain||par1ItemStack.getItem() == TFCItems.RiceGrain|| par1ItemStack.getItem() == TFCItems.BarleyGrain||par1ItemStack.getItem() == TFCItems.RyeGrain); } /** * Returns the item ID for the item the mob drops on death. */ @Override protected int getDropItemId() { return TFCItems.Wool.itemID; } /** * Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig. */ @Override public boolean interact(EntityPlayer par1EntityPlayer) { if(!worldObj.isRemote){ par1EntityPlayer.addChatMessage(getGender()==GenderEnum.FEMALE?"Female":"Male"); if(getGender()==GenderEnum.FEMALE && pregnant){ par1EntityPlayer.addChatMessage("Pregnant"); } //par1EntityPlayer.addChatMessage("12: "+dataWatcher.getWatchableObjectInt(12)+", 15: "+dataWatcher.getWatchableObjectInt(15)); } if(getGender() == GenderEnum.FEMALE && isAdult() && hasMilkTime < TFC_Time.getTotalTicks()){ ItemStack var2 = par1EntityPlayer.inventory.getCurrentItem(); if (var2 != null && var2.itemID == TFCItems.WoodenBucketEmpty.itemID) { par1EntityPlayer.inventory.setInventorySlotContents(par1EntityPlayer.inventory.currentItem, new ItemStack(TFCItems.WoodenBucketMilk)); hasMilkTime = TFC_Time.getTotalTicks() + (3*TFC_Time.dayLength); //Can be milked ones every 3 days return true; } } return super.interact(par1EntityPlayer); } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ @Override public void writeEntityToNBT(NBTTagCompound nbt) { super.writeEntityToNBT(nbt); nbt.setInteger ("Sex", sex); nbt.setLong ("Animal ID", animalID); nbt.setFloat ("Size Modifier", size_mod); nbt.setInteger ("Hunger", hunger); nbt.setBoolean("Pregnant", pregnant); nbt.setFloat("MateSize", mateSizeMod); nbt.setLong("ConceptionTime",timeOfConception); nbt.setInteger("Age", getBirthDay()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ @Override public void readEntityFromNBT(NBTTagCompound nbt) { super.readEntityFromNBT(nbt); animalID = nbt.getLong ("Animal ID"); sex = nbt.getInteger ("Sex"); size_mod = nbt.getFloat ("Size Modifier"); hunger = nbt.getInteger ("Hunger"); pregnant = nbt.getBoolean("Pregnant"); mateSizeMod = nbt.getFloat("MateSize"); timeOfConception = nbt.getLong("ConceptionTime"); this.dataWatcher.updateObject(15, nbt.getInteger ("Age")); this.setAge(nbt.getInteger ("Age")); } @Override public boolean isShearable(ItemStack item, World world, int X, int Y, int Z) { return !getSheared() && isAdult(); } @Override public ArrayList<ItemStack> onSheared(ItemStack item, World world, int X, int Y, int Z, int fortune) { ArrayList<ItemStack> ret = new ArrayList<ItemStack>(); setSheared(true); ret.add(new ItemStack(TFCItems.Wool.itemID, 1, getFleeceColor())); this.worldObj.playSoundAtEntity(this, "mob.sheep.shear", 1.0F, 1.0F); return ret; } @Override public void setGrowingAge(int par1) { if(!TFC_Core.PreventEntityDataUpdate) { this.dataWatcher.updateObject(12, Integer.valueOf(par1)); } } @Override public boolean isChild() { return !isAdult(); } @Override public EntityAgeable createChild(EntityAgeable entityageable) { return null; } @Override public int getBirthDay() { return this.dataWatcher.getWatchableObjectInt(15); } @Override public int getNumberOfDaysToAdult() { return TFC_Time.daysInMonth * 3; } @Override public boolean isAdult() { return getBirthDay()+getNumberOfDaysToAdult() <= TFC_Time.getTotalDays(); } @Override public float getSize() { return size_mod; } @Override public boolean isPregnant() { return pregnant; } @Override public EntityLiving getEntity() { return this; } @Override public boolean canMateWith(IAnimal animal) { if(animal.getGender() != this.getGender() && animal.isAdult() && animal instanceof EntitySheepTFC) { return true; } else { return false; } } @Override public void mate(IAnimal otherAnimal) { if (getGender() == GenderEnum.MALE) { otherAnimal.mate(this); return; } timeOfConception = TFC_Time.getTotalTicks(); pregnant = true; resetInLove(); otherAnimal.setInLove(false); mateSizeMod = otherAnimal.getSize(); } @Override public boolean getInLove() { return inLove; } @Override public void setInLove(boolean b) { this.inLove = b; } @Override public long getAnimalID() { return animalID; } @Override public void setAnimalID(long id) { animalID = id; } @Override public int getHunger() { return hunger; } @Override public void setHunger(int h) { hunger = h; } @Override public GenderEnum getGender() { return GenderEnum.genders[getSex()]; } @Override public int getSex() { return dataWatcher.getWatchableObjectInt(13); } @Override public EntityAgeable createChildTFC(EntityAgeable entityageable) { return new EntitySheepTFC(worldObj, this, entityageable.getEntityData().getFloat("MateSize")); } @Override public void setAge(int par1) { this.dataWatcher.updateObject(15, Integer.valueOf(par1)); } }
false
true
public void onLivingUpdate() { if (this.worldObj.isRemote) { this.sheepTimer = Math.max(0, this.sheepTimer - 1); } //Handle Hunger ticking if (hunger > 168000) { hunger = 168000; } if (hunger > 0) { hunger--; } if(super.inLove > 0){ super.inLove = 0; setInLove(true); } syncData(); if(isAdult()){ setGrowingAge(0); } else{ setGrowingAge(-1); } if(isPregnant()) { if(TFC_Time.getTotalTicks() >= timeOfConception + pregnancyRequiredTime) { int i = rand.nextInt(3) + 1; for (int x = 0; x<i;x++) { EntitySheepTFC baby = new EntitySheepTFC(worldObj, this, mateSizeMod); worldObj.spawnEntityInWorld(baby); } pregnant = false; } } /** * This Cancels out the changes made to growingAge by EntityAgeable * */ TFC_Core.PreventEntityDataUpdate = true; super.onLivingUpdate(); TFC_Core.PreventEntityDataUpdate = false; if (hunger > 144000 && rand.nextInt (100) == 0 && func_110143_aJ() < TFC_Core.getEntityMaxHealth(this) && !isDead) { this.heal(1); } }
public void onLivingUpdate() { if (this.worldObj.isRemote) { this.sheepTimer = Math.max(0, this.sheepTimer - 1); } //Handle Hunger ticking if (hunger > 168000) { hunger = 168000; } if (hunger > 0) { hunger--; } if(super.inLove > 0){ super.inLove = 0; setInLove(true); } syncData(); if(isAdult()){ setGrowingAge(0); } else{ setGrowingAge(-1); } if(isPregnant()) { if(TFC_Time.getTotalTicks() >= timeOfConception + pregnancyRequiredTime) { int i = rand.nextInt(3) + 1; for (int x = 0; x<i;x++) { EntitySheepTFC baby = new EntitySheepTFC(worldObj, this, mateSizeMod); baby.setLocationAndAngles (posX+(rand.nextFloat()-0.5F)*2F,posY,posZ+(rand.nextFloat()-0.5F)*2F, 0.0F, 0.0F); baby.rotationYawHead = baby.rotationYaw; baby.renderYawOffset = baby.rotationYaw; worldObj.spawnEntityInWorld(baby); baby.setAge((int)TFC_Time.getTotalDays()); } pregnant = false; } } /** * This Cancels out the changes made to growingAge by EntityAgeable * */ TFC_Core.PreventEntityDataUpdate = true; super.onLivingUpdate(); TFC_Core.PreventEntityDataUpdate = false; if (hunger > 144000 && rand.nextInt (100) == 0 && func_110143_aJ() < TFC_Core.getEntityMaxHealth(this) && !isDead) { this.heal(1); } }
diff --git a/Jcrop-parent/Jcrop-integration/src/main/java/org/jcrop/JcropImage.java b/Jcrop-parent/Jcrop-integration/src/main/java/org/jcrop/JcropImage.java index 45b8439..0d8a638 100644 --- a/Jcrop-parent/Jcrop-integration/src/main/java/org/jcrop/JcropImage.java +++ b/Jcrop-parent/Jcrop-integration/src/main/java/org/jcrop/JcropImage.java @@ -1,60 +1,60 @@ package org.jcrop; import org.apache.wicket.markup.html.image.NonCachingImage; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.IResource; import org.apache.wicket.request.resource.PackageResourceReference; import org.apache.wicket.request.resource.ResourceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JcropImage extends NonCachingImage { private static final Logger logger = LoggerFactory.getLogger(JcropImage.class); public JcropImage(String id, IResource imageResource, CroppableSettings settings) { super(id, imageResource); setOutputMarkupId(true); initJCrop(settings); } public JcropImage(String id, ResourceReference resourceReference, PageParameters resourceParameters, CroppableSettings settings) { super(id, resourceReference, resourceParameters); setOutputMarkupId(true); initJCrop(settings); } public JcropImage(String id, ResourceReference resourceReference, CroppableSettings settings) { super(id, resourceReference); setOutputMarkupId(true); initJCrop(settings); } public JcropImage(String id, CroppableSettings settings) { super(id, new PackageResourceReference(JcropImage.class, "4.jpg")); setOutputMarkupId(true); initJCrop(settings); } protected void initJCrop(CroppableSettings settings) { add(jCropBehavior = new JcropBehavior(settings) { @Override - protected void onCooridnatsChange(Coordinates coordinates) { + protected void onCoordinatesChange(Coordinates coordinates) { JcropImage.this.onCooridnatsChange(coordinates); } }); } public JcropController getApiController() { if (null != jCropBehavior) { return jCropBehavior.getApiController(); } return null; } protected void onCooridnatsChange(Coordinates coordinates) { logger.info(coordinates.toString()); } private JcropBehavior jCropBehavior = null; }
true
true
protected void initJCrop(CroppableSettings settings) { add(jCropBehavior = new JcropBehavior(settings) { @Override protected void onCooridnatsChange(Coordinates coordinates) { JcropImage.this.onCooridnatsChange(coordinates); } }); }
protected void initJCrop(CroppableSettings settings) { add(jCropBehavior = new JcropBehavior(settings) { @Override protected void onCoordinatesChange(Coordinates coordinates) { JcropImage.this.onCooridnatsChange(coordinates); } }); }
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java index 1ff891bcc..5d8161ae7 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java @@ -1,1976 +1,1978 @@ /* * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.core; import gov.nist.javax.sip.stack.SIPServerTransaction; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.sip.SipErrorEvent; import javax.servlet.sip.SipErrorListener; import javax.servlet.sip.SipFactory; import javax.servlet.sip.SipServlet; import javax.servlet.sip.SipServletContextEvent; import javax.servlet.sip.SipServletListener; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipURI; import javax.servlet.sip.ar.SipApplicationRouter; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.servlet.sip.ar.SipApplicationRoutingDirective; import javax.servlet.sip.ar.SipApplicationRoutingRegion; import javax.servlet.sip.ar.SipRouteModifier; import javax.sip.ClientTransaction; import javax.sip.Dialog; import javax.sip.DialogTerminatedEvent; import javax.sip.IOExceptionEvent; import javax.sip.InvalidArgumentException; import javax.sip.ListeningPoint; import javax.sip.RequestEvent; import javax.sip.ResponseEvent; import javax.sip.ServerTransaction; import javax.sip.SipException; import javax.sip.SipProvider; import javax.sip.TimeoutEvent; import javax.sip.Transaction; import javax.sip.TransactionAlreadyExistsException; import javax.sip.TransactionTerminatedEvent; import javax.sip.TransactionUnavailableException; import javax.sip.address.Address; import javax.sip.address.URI; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContentTypeHeader; import javax.sip.header.Header; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.catalina.Container; import org.apache.catalina.LifecycleException; import org.apache.catalina.Wrapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.modeler.Registry; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.address.SipURIImpl; import org.mobicents.servlet.sip.address.TelURLImpl; import org.mobicents.servlet.sip.core.session.SessionManagerUtil; import org.mobicents.servlet.sip.core.session.SipApplicationSessionImpl; import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey; import org.mobicents.servlet.sip.core.session.SipListenersHolder; import org.mobicents.servlet.sip.core.session.SipManager; import org.mobicents.servlet.sip.core.session.SipSessionImpl; import org.mobicents.servlet.sip.core.session.SipSessionKey; import org.mobicents.servlet.sip.message.SipFactoryImpl; import org.mobicents.servlet.sip.message.SipServletMessageImpl; import org.mobicents.servlet.sip.message.SipServletRequestImpl; import org.mobicents.servlet.sip.message.SipServletResponseImpl; import org.mobicents.servlet.sip.message.TransactionApplicationData; import org.mobicents.servlet.sip.proxy.ProxyBranchImpl; import org.mobicents.servlet.sip.router.ManageableApplicationRouter; import org.mobicents.servlet.sip.security.SipSecurityUtils; import org.mobicents.servlet.sip.startup.SipContext; import org.mobicents.servlet.sip.startup.loading.SipServletMapping; /** * Implementation of the SipApplicationDispatcher interface. * Central point getting the sip messages from the different stacks for a Tomcat Service(Engine), * translating jain sip SIP messages to sip servlets SIP messages, calling the application router * to know which app is interested in the messages and * dispatching them to those sip applications interested in the messages. * @author Jean Deruelle */ public class SipApplicationDispatcherImpl implements SipApplicationDispatcher, MBeanRegistration { //the logger private static transient Log logger = LogFactory .getLog(SipApplicationDispatcherImpl.class); private enum SipSessionRoutingType { PREVIOUS_SESSION, CURRENT_SESSION; } public static final String ROUTE_PARAM_DIRECTIVE = "directive"; public static final String ROUTE_PARAM_PREV_APPLICATION_NAME = "previousappname"; /* * This parameter is to know which app handled the request */ public static final String RR_PARAM_APPLICATION_NAME = "appname"; /* * This parameter is to know which servlet handled the request */ public static final String RR_PARAM_HANDLER_NAME = "handler"; /* * This parameter is to know if a servlet application sent a final response */ public static final String FINAL_RESPONSE = "final_response"; /* * This parameter is to know when an app was not deployed and couldn't handle the request * used so that the response doesn't try to call the app not deployed */ public static final String APP_NOT_DEPLOYED = "appnotdeployed"; /* * This parameter is to know when no app was returned by the AR when doing the initial selection process * used so that the response is forwarded externally directly */ public static final String NO_APP_RETURNED = "noappreturned"; /* * This parameter is to know when the AR returned an external route instead of an app */ public static final String MODIFIER = "modifier"; public static final Set<String> nonInitialSipRequestMethods = new HashSet<String>(); static { nonInitialSipRequestMethods.add("CANCEL"); nonInitialSipRequestMethods.add("BYE"); nonInitialSipRequestMethods.add("PRACK"); nonInitialSipRequestMethods.add("ACK"); nonInitialSipRequestMethods.add("UPDATE"); nonInitialSipRequestMethods.add("INFO"); }; // private enum InitialRequestRouting { // CONTINUE, STOP; // } //the sip factory implementation, it is not clear if the sip factory should be the same instance //for all applications private SipFactoryImpl sipFactoryImpl = null; //the sip application router responsible for the routing logic of sip messages to //sip servlet applications private SipApplicationRouter sipApplicationRouter = null; //map of applications deployed private Map<String, SipContext> applicationDeployed = null; //List of host names managed by the container private List<String> hostNames = null; //application chains // private Map<String, SipContext> applicationChains = null; private SessionManagerUtil sessionManager = null; private Boolean started = Boolean.FALSE; private SipNetworkInterfaceManager sipNetworkInterfaceManager; /** * */ public SipApplicationDispatcherImpl() { applicationDeployed = new ConcurrentHashMap<String, SipContext>(); sipFactoryImpl = new SipFactoryImpl(this); sessionManager = new SessionManagerUtil(); hostNames = Collections.synchronizedList(new ArrayList<String>()); sipNetworkInterfaceManager = new SipNetworkInterfaceManager(); } /** * {@inheritDoc} */ public void init(String sipApplicationRouterClassName) throws LifecycleException { //load the sip application router from the class name specified in the server.xml file //and initializes it try { sipApplicationRouter = (SipApplicationRouter) Class.forName(sipApplicationRouterClassName).newInstance(); } catch (InstantiationException e) { throw new LifecycleException("Impossible to load the Sip Application Router",e); } catch (IllegalAccessException e) { throw new LifecycleException("Impossible to load the Sip Application Router",e); } catch (ClassNotFoundException e) { throw new LifecycleException("Impossible to load the Sip Application Router",e); } catch (ClassCastException e) { throw new LifecycleException("Sip Application Router defined does not implement " + SipApplicationRouter.class.getName(),e); } sipApplicationRouter.init(new ArrayList<String>(applicationDeployed.keySet())); if( oname == null ) { try { oname=new ObjectName(domain + ":type=SipApplicationDispatcher"); Registry.getRegistry(null, null) .registerComponent(this, oname, null); logger.info("Sip Application dispatcher registered under following name " + oname); } catch (Exception e) { logger.error("Impossible to register the Sip Application dispatcher in domain" + domain, e); } } } /** * {@inheritDoc} */ public void start() { synchronized (started) { if(started) { return; } started = Boolean.TRUE; } if(logger.isDebugEnabled()) { logger.debug("Sip Application Dispatcher started"); } // outbound interfaces set here and not in sipstandardcontext because // depending on jboss or tomcat context can be started before or after // connectors resetOutboundInterfaces(); //JSR 289 Section 2.1.1 Step 4.If present invoke SipServletListener.servletInitialized() on each of initialized Servlet's listeners. for (SipContext sipContext : applicationDeployed.values()) { notifySipServletsListeners(sipContext); } } /** * Notifies the sip servlet listeners that the servlet has been initialized * and that it is ready for service * @param sipContext the sip context of the application where the listeners reside. * @return true if all listeners have been notified correctly */ private static boolean notifySipServletsListeners(SipContext sipContext) { boolean ok = true; SipListenersHolder sipListenersHolder = sipContext.getListeners(); List<SipServletListener> sipServletListeners = sipListenersHolder.getSipServletsListeners(); if(logger.isDebugEnabled()) { logger.debug(sipServletListeners.size() + " SipServletListener to notify of servlet initialization"); } Container[] children = sipContext.findChildren(); if(logger.isDebugEnabled()) { logger.debug(children.length + " container to notify of servlet initialization"); } for (Container container : children) { if(logger.isDebugEnabled()) { logger.debug("container " + container.getName() + ", class : " + container.getClass().getName()); } if(container instanceof Wrapper) { Wrapper wrapper = (Wrapper) container; Servlet sipServlet = null; try { sipServlet = wrapper.allocate(); if(sipServlet instanceof SipServlet) { SipServletContextEvent sipServletContextEvent = new SipServletContextEvent(sipContext.getServletContext(), (SipServlet)sipServlet); for (SipServletListener sipServletListener : sipServletListeners) { sipServletListener.servletInitialized(sipServletContextEvent); } } } catch (ServletException e) { logger.error("Cannot allocate the servlet "+ wrapper.getServletClass() +" for notifying the listener " + "that it has been initialized", e); ok = false; } catch (Throwable e) { logger.error("An error occured when initializing the servlet " + wrapper.getServletClass(), e); ok = false; } try { if(sipServlet != null) { wrapper.deallocate(sipServlet); } } catch (ServletException e) { logger.error("Deallocate exception for servlet" + wrapper.getName(), e); ok = false; } catch (Throwable e) { logger.error("Deallocate exception for servlet" + wrapper.getName(), e); ok = false; } } } return ok; } /** * {@inheritDoc} */ public void stop() { synchronized (started) { if(!started) { return; } started = Boolean.FALSE; } sipApplicationRouter.destroy(); if(oname != null) { Registry.getRegistry(null, null).unregisterComponent(oname); } } /** * {@inheritDoc} */ public void addSipApplication(String sipApplicationName, SipContext sipApplication) { if(logger.isDebugEnabled()) { logger.debug("Adding the following sip servlet application " + sipApplicationName + ", SipContext=" + sipApplication); } applicationDeployed.put(sipApplicationName, sipApplication); List<String> newlyApplicationsDeployed = new ArrayList<String>(); newlyApplicationsDeployed.add(sipApplicationName); sipApplicationRouter.applicationDeployed(newlyApplicationsDeployed); //if the ApplicationDispatcher is started, notification is sent that the servlets are ready for service //otherwise the notification will be delayed until the ApplicationDispatcher has started synchronized (started) { if(started) { notifySipServletsListeners(sipApplication); } } logger.info("the following sip servlet application has been added : " + sipApplicationName); } /** * {@inheritDoc} */ public SipContext removeSipApplication(String sipApplicationName) { SipContext sipContext = applicationDeployed.remove(sipApplicationName); List<String> applicationsUndeployed = new ArrayList<String>(); applicationsUndeployed.add(sipApplicationName); sipApplicationRouter.applicationUndeployed(applicationsUndeployed); ((SipManager)sipContext.getManager()).removeAllSessions(); logger.info("the following sip servlet application has been removed : " + sipApplicationName); return sipContext; } /* * (non-Javadoc) * @see javax.sip.SipListener#processDialogTerminated(javax.sip.DialogTerminatedEvent) */ public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { // TODO FIXME logger.info("Dialog Terminated => " + dialogTerminatedEvent.getDialog().getCallId().getCallId()); Dialog dialog = dialogTerminatedEvent.getDialog(); TransactionApplicationData tad = (TransactionApplicationData) dialog.getApplicationData(); SipServletMessageImpl sipServletMessageImpl = tad.getSipServletMessage(); SipSessionImpl sipSessionImpl = sipServletMessageImpl.getSipSession(); /* TODO: FIXME: Review this. We can't remove sesions that still have transactions. Although the jsip stacktransaction might have ended, the message that ended it is not yet delivered to the container and the servlet at this time. */ // if(!sipSessionImpl.hasOngoingTransaction()) { // sessionManager.removeSipSession(sipSessionImpl.getKey()); // } } /* * (non-Javadoc) * @see javax.sip.SipListener#processIOException(javax.sip.IOExceptionEvent) */ public void processIOException(IOExceptionEvent arg0) { // TODO Auto-generated method stub } /* * (non-Javadoc) * @see javax.sip.SipListener#processRequest(javax.sip.RequestEvent) */ public void processRequest(RequestEvent requestEvent) { SipProvider sipProvider = (SipProvider)requestEvent.getSource(); ServerTransaction transaction = requestEvent.getServerTransaction(); Request request = requestEvent.getRequest(); try { logger.info("Got a request event " + request.toString()); if (!Request.ACK.equals(request.getMethod()) && transaction == null ) { try { //folsson fix : Workaround broken Cisco 7940/7912 if(request.getHeader(MaxForwardsHeader.NAME)==null){ request.setHeader(SipFactories.headerFactory.createMaxForwardsHeader(70)); } transaction = sipProvider.getNewServerTransaction(request); } catch ( TransactionUnavailableException tae) { // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return; } catch ( TransactionAlreadyExistsException taex ) { // Already processed this request so just return. return; } } logger.info("ServerTx ref " + transaction); logger.info("Dialog ref " + requestEvent.getDialog()); SipServletRequestImpl sipServletRequest = new SipServletRequestImpl( request, sipFactoryImpl, null, transaction, requestEvent.getDialog(), JainSipUtils.dialogCreatingMethods.contains(request.getMethod())); // Check if the request is meant for me. If so, strip the topmost // Route header. RouteHeader routeHeader = (RouteHeader) request .getHeader(RouteHeader.NAME); //Popping the router header if it's for the container as //specified in JSR 289 - Section 15.8 if(! isRouteExternal(routeHeader)) { request.removeFirst(RouteHeader.NAME); sipServletRequest.setPoppedRoute(routeHeader); } logger.info("Routing State " + sipServletRequest.getRoutingState()); if(sipServletRequest.isInitial()) { logger.info("Routing of Initial Request " + request); routeInitialRequest(sipProvider, sipServletRequest); } else { logger.info("Routing of Subsequent Request " + request); if(sipServletRequest.getMethod().equals(Request.CANCEL)) { routeCancel(sipProvider, sipServletRequest); } else { routeSubsequentRequest(sipProvider, sipServletRequest); } } } catch (Throwable e) { logger.error("Unexpected exception while processing request",e); // Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); } return; } } /** * Forward statefully a request whether it is initial or subsequent * and keep track of the transactions used in application data of each transaction * @param sipServletRequest the sip servlet request to forward statefully * @param sipRouteModifier the route modifier returned by the AR when receiving the request * @throws ParseException * @throws TransactionUnavailableException * @throws SipException * @throws InvalidArgumentException */ private void forwardStatefully(SipServletRequestImpl sipServletRequest, SipSessionRoutingType sipSessionRoutingType, SipRouteModifier sipRouteModifier) throws ParseException, TransactionUnavailableException, SipException, InvalidArgumentException { Request clonedRequest = (Request)sipServletRequest.getMessage().clone(); //Add via header String transport = JainSipUtils.findTransport(clonedRequest); ViaHeader viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, transport, null); SipSessionImpl session = sipServletRequest.getSipSession(); if(session != null) { if(SipSessionRoutingType.CURRENT_SESSION.equals(sipSessionRoutingType)) { //an app was found or an app was returned by the AR but not found String handlerName = session.getHandler(); if(handlerName != null) { viaHeader.setParameter(SipApplicationDispatcherImpl.RR_PARAM_APPLICATION_NAME, sipServletRequest.getSipSession().getKey().getApplicationName()); viaHeader.setParameter(SipApplicationDispatcherImpl.RR_PARAM_HANDLER_NAME, sipServletRequest.getSipSession().getHandler()); } else { // if the handler name is null it means that the app returned by the AR was not deployed // and couldn't be called, // we specify it so that on response handling this app can be skipped viaHeader.setParameter(SipApplicationDispatcherImpl.APP_NOT_DEPLOYED, sipServletRequest.getSipSession().getKey().getApplicationName()); } clonedRequest.addHeader(viaHeader); } else { if(SipRouteModifier.NO_ROUTE.equals(sipRouteModifier)) { // no app was returned by the AR viaHeader.setParameter(SipApplicationDispatcherImpl.NO_APP_RETURNED, "noappreturned"); } else { viaHeader.setParameter(SipApplicationDispatcherImpl.MODIFIER, sipRouteModifier.toString()); } clonedRequest.addHeader(viaHeader); } } else { if(SipRouteModifier.NO_ROUTE.equals(sipRouteModifier)) { // no app was returned by the AR and no application was selected before // if the handler name is null it means that the app returned by the AR was not deployed // and couldn't be called, // we specify it so that on response handling this app can be skipped viaHeader.setParameter(SipApplicationDispatcherImpl.NO_APP_RETURNED, "noappreturned"); } else { viaHeader.setParameter(SipApplicationDispatcherImpl.MODIFIER, sipRouteModifier.toString()); } clonedRequest.addHeader(viaHeader); } //decrease the Max Forward Header MaxForwardsHeader mf = (MaxForwardsHeader) clonedRequest .getHeader(MaxForwardsHeader.NAME); if (mf == null) { mf = SipFactories.headerFactory.createMaxForwardsHeader(JainSipUtils.MAX_FORWARD_HEADER_VALUE); clonedRequest.addHeader(mf); } else { //TODO send error meesage for loop if maxforward < 0 mf.setMaxForwards(mf.getMaxForwards() - 1); } if(logger.isDebugEnabled()) { if(SipRouteModifier.NO_ROUTE.equals(sipRouteModifier)) { logger.debug("Routing Back to the container the following request " + clonedRequest); } else { logger.debug("Routing externally the following request " + clonedRequest); } } ExtendedListeningPoint extendedListeningPoint = sipNetworkInterfaceManager.findMatchingListeningPoint(transport, false); if(logger.isDebugEnabled()) { logger.debug("Matching listening point found " + extendedListeningPoint); } SipProvider sipProvider = extendedListeningPoint.getSipProvider(); ServerTransaction serverTransaction = (ServerTransaction) sipServletRequest.getTransaction(); Dialog dialog = sipServletRequest.getDialog(); if(logger.isDebugEnabled()) { logger.debug("Dialog existing " + dialog != null); } if(dialog == null) { Transaction transaction = ((TransactionApplicationData) serverTransaction.getApplicationData()).getSipServletMessage().getTransaction(); if(transaction == null || transaction instanceof ServerTransaction) { ClientTransaction ctx = sipProvider.getNewClientTransaction(clonedRequest); //keeping the server transaction in the client transaction's application data TransactionApplicationData appData = new TransactionApplicationData(sipServletRequest); appData.setTransaction(serverTransaction); ctx.setApplicationData(appData); //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)serverTransaction.getApplicationData()).setTransaction(ctx); logger.info("Sending the request through a new client transaction " + clonedRequest); ctx.sendRequest(); } else { logger.info("Sending the request through the existing transaction " + clonedRequest); ((ClientTransaction)transaction).sendRequest(); } } else if ( clonedRequest.getMethod().equals("ACK") ) { logger.info("Sending the ACK through the dialog " + clonedRequest); dialog.sendAck(clonedRequest); } else { Request dialogRequest= dialog.createRequest(clonedRequest.getMethod()); Object content=clonedRequest.getContent(); if (content!=null) { ContentTypeHeader contentTypeHeader= (ContentTypeHeader) clonedRequest.getHeader(ContentTypeHeader.NAME); if (contentTypeHeader!=null) { dialogRequest.setContent(content,contentTypeHeader); } } // Copy all the headers from the original request to the // dialog created request: ListIterator<String> headerNamesListIterator=clonedRequest.getHeaderNames(); while (headerNamesListIterator.hasNext()) { String name=headerNamesListIterator.next(); Header header=dialogRequest.getHeader(name); if (header==null ) { ListIterator<Header> li=clonedRequest.getHeaders(name); if (li!=null) { while (li.hasNext() ) { Header h = li.next(); dialogRequest.addHeader(h); } } } else { if ( header instanceof ViaHeader) { ListIterator<Header> li= clonedRequest.getHeaders(name); if (li!=null) { dialogRequest.removeHeader(name); Vector v=new Vector(); while (li.hasNext() ) { Header h=li.next(); v.addElement(h); } for (int k=(v.size()-1);k>=0;k--) { Header h=(Header)v.elementAt(k); dialogRequest.addHeader(h); } } } } } ClientTransaction clientTransaction = sipProvider.getNewClientTransaction(dialogRequest); //keeping the server transaction in the client transaction's application data TransactionApplicationData appData = new TransactionApplicationData(sipServletRequest); appData.setTransaction(serverTransaction); clientTransaction.setApplicationData(appData); //keeping the client transaction in the server transaction's application data ((TransactionApplicationData)serverTransaction.getApplicationData()).setTransaction(clientTransaction); dialog.setApplicationData(appData); logger.info("Sending the request through the dialog " + clonedRequest); dialog.sendRequest(clientTransaction); } } /** * @param sipProvider * @param transaction * @param request * @param sipServletRequest * @throws InvalidArgumentException * @throws SipException * @throws ParseException * @throws TransactionUnavailableException */ private boolean routeSubsequentRequest(SipProvider sipProvider, SipServletRequestImpl sipServletRequest) throws TransactionUnavailableException, ParseException, SipException, InvalidArgumentException { ServerTransaction transaction = (ServerTransaction) sipServletRequest.getTransaction(); Request request = (Request) sipServletRequest.getMessage(); Dialog dialog = sipServletRequest.getDialog(); javax.servlet.sip.Address poppedAddress = sipServletRequest.getPoppedRoute(); if(poppedAddress==null){ if(Request.ACK.equals(request.getMethod())) { //Means that this is an ACK to a container generated error response, so we can drop it if(logger.isDebugEnabled()) { logger.debug("The popped route is null for an ACK, this is an ACK to a container generated error response, so it is dropped"); } return false; } else { throw new IllegalArgumentException("The popped route shouldn't be null for not proxied requests."); } } //Extract information from the Record Route Header String applicationName = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME); String handlerName = poppedAddress.getParameter(RR_PARAM_HANDLER_NAME); String finalResponse = poppedAddress.getParameter(FINAL_RESPONSE); if(applicationName == null || applicationName.length() < 1 || handlerName == null || handlerName.length() < 1) { throw new IllegalArgumentException("cannot find the application to handle this subsequent request " + "in this popped routed header " + poppedAddress); } boolean inverted = false; if(dialog != null && !dialog.isServer()) { inverted = true; } SipContext sipContext = this.applicationDeployed.get(applicationName); if(sipContext == null) { throw new IllegalArgumentException("cannot find the application to handle this subsequent request " + "in this popped routed header " + poppedAddress); } SipManager sipManager = (SipManager)sipContext.getManager(); SipApplicationSessionKey sipApplicationSessionKey = makeAppSessionKey( sipContext, sipServletRequest, applicationName); SipApplicationSessionImpl sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false); if(sipApplicationSession == null) { logger.error("Cannot find the corresponding sip application session to this subsequent request " + request + " with the following popped route header " + sipServletRequest.getPoppedRoute()); sipManager.dumpSipApplicationSessions(); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } SipSessionKey key = SessionManagerUtil.getSipSessionKey(applicationName, sipServletRequest.getMessage(), inverted); SipSessionImpl sipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession); // Added by Vladimir because the inversion detection on proxied requests doesn't work if(sipSession == null) { if(logger.isDebugEnabled()) { logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request + " with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted."); } key = SessionManagerUtil.getSipSessionKey(applicationName, sipServletRequest.getMessage(), !inverted); sipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession); } if(sipSession == null) { logger.error("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request + " with the following popped route header " + sipServletRequest.getPoppedRoute()); sipManager.dumpSipSessions(); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } sipServletRequest.setSipSession(sipSession); // JSR 289 Section 6.2.1 : // any state transition caused by the reception of a SIP message, // the state change must be accomplished by the container before calling // the service() method of any SipServlet to handle the incoming message. sipSession.updateStateOnSubsequentRequest(sipServletRequest, true); try { // See if the subsequent request should go directly to the proxy if(sipServletRequest.getSipSession().getProxyBranch() != null) { ProxyBranchImpl proxyBranch = sipServletRequest.getSipSession().getProxyBranch(); if(proxyBranch.getProxy().getSupervised()) { callServlet(sipServletRequest); } proxyBranch.proxySubsequentRequest(sipServletRequest); } // If it's not for a proxy then it's just an AR, so go to the next application else { callServlet(sipServletRequest); } } catch (ServletException e) { logger.error("An unexpected servlet exception occured while processing the following subsequent request " + request, e); // Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); } return false; } catch (IOException e) { logger.error("An unexpected IO exception occured while processing the following subsequent request " + request, e); // Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); } return false; } //if a final response has been sent, or if the request has //been proxied or relayed we stop routing the request RoutingState routingState = sipServletRequest.getRoutingState(); if(RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || RoutingState.PROXIED.equals(routingState) || RoutingState.RELAYED.equals(routingState) || RoutingState.CANCELLED.equals(routingState)) { if(logger.isDebugEnabled()) { logger.debug("Routing State : " + sipServletRequest.getRoutingState() + "The Container hence stops routing the subsequent request."); } return false; } else { if(finalResponse != null && finalResponse.length() > 0) { logger.info("Subsequent Request reached the servlet application " + "that sent a final response, stop routing the subsequent request " + request.toString()); return false; } // Check if the request is meant for me. RouteHeader routeHeader = (RouteHeader) request .getHeader(RouteHeader.NAME); if(routeHeader == null || isRouteExternal(routeHeader)) { // no route header or external, send outside the container // FIXME send it statefully if(dialog == null && transaction == null) { try{ sipProvider.sendRequest((Request)request.clone()); logger.info("Subsequent Request dispatched outside the container" + request.toString()); } catch (Exception ex) { throw new IllegalStateException("Error sending request",ex); } } else { forwardStatefully(sipServletRequest, SipSessionRoutingType.CURRENT_SESSION, SipRouteModifier.ROUTE); } return false; } else { //route header is meant for the container hence we continue forwardStatefully(sipServletRequest, SipSessionRoutingType.CURRENT_SESSION, SipRouteModifier.NO_ROUTE); return true; } } } /** * This method allows to route the CANCEL request along the application path * followed by the INVITE. * We can distinguish cases here as per spec : * Applications that acts as User Agent or B2BUA * 11.2.3 Receiving CANCEL * * When a CANCEL is received for a request which has been passed to an application, * and the application has not responded yet or proxied the original request, * the container responds to the original request with a 487 (Request Terminated) * and to the CANCEL with a 200 OK final response, and it notifies the application * by passing it a SipServletRequest object representing the CANCEL request. * The application should not attempt to respond to a request after receiving a CANCEL for it. * Neither should it respond to the CANCEL notification. * Clearly, there is a race condition between the container generating the 487 response * and the SIP servlet generating its own response. * This should be handled using standard Java mechanisms for resolving race conditions. * If the application wins, it will not be notified that a CANCEL request was received. * If the container wins and the servlet tries to send a response before * (or for that matter after) being notified of the CANCEL, * the container throws an IllegalStateException. * * Applications that acts as proxy : * 10.2.6 Receiving CANCEL * if the original request has not been proxied yet the container responds * to it with a 487 final response otherwise, all branches are cancelled, * and response processing continues as usual * In either case, the application is subsequently invoked with the CANCEL request. * This is a notification only, as the server has already responded to the CANCEL * and cancelled outstanding branches as appropriate. * The race condition between the server sending the 487 response and * the application proxying the request is handled as in the UAS case as * discussed in section 11.2.3 Receiving CANCEL. * * @param sipProvider * @param sipServletRequest * @param transaction * @param request * @param poppedAddress * @throws InvalidArgumentException * @throws SipException * @throws ParseException * @throws TransactionUnavailableException */ private boolean routeCancel(SipProvider sipProvider, SipServletRequestImpl sipServletRequest) throws TransactionUnavailableException, ParseException, SipException, InvalidArgumentException { ServerTransaction transaction = (ServerTransaction) sipServletRequest.getTransaction(); Request request = (Request) sipServletRequest.getMessage(); Dialog dialog = transaction.getDialog(); /* * WARNING: TODO: We need to find a way to route CANCELs through the app path * of the INVITE. CANCEL does not contain Route headers as other requests related * to the dialog. */ /* If there is a proxy with the request, let's try to send it directly there. * This is needed because of CANCEL which is a subsequent request that might * not have Routes. For example if the callee has'n responded the caller still * doesn't know the route-record and just sends cancel to the outbound proxy. */ // boolean proxyCancel = false; try { // First we need to send OK ASAP because of retransmissions both for //proxy or app ServerTransaction cancelTransaction = (ServerTransaction) sipServletRequest.getTransaction(); SipServletResponseImpl cancelResponse = (SipServletResponseImpl) sipServletRequest.createResponse(200, "Canceling"); Response cancelJsipResponse = (Response) cancelResponse.getMessage(); cancelTransaction.sendResponse(cancelJsipResponse); } catch (SipException e) { logger.error("Impossible to send the ok to the CANCEL",e); JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } catch (InvalidArgumentException e) { logger.error("Impossible to send the ok to the CANCEL",e); JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } if(logger.isDebugEnabled()) { logger.debug("checking what to do with the CANCEL " + sipServletRequest); } // TransactionApplicationData dialogAppData = (TransactionApplicationData) dialog.getApplicationData(); Transaction inviteTransaction = ((SIPServerTransaction) sipServletRequest.getTransaction()).getCanceledInviteTransaction(); TransactionApplicationData dialogAppData = (TransactionApplicationData)inviteTransaction.getApplicationData(); SipServletRequestImpl inviteRequest = (SipServletRequestImpl) dialogAppData.getSipServletMessage(); if(logger.isDebugEnabled()) { logger.debug("message associated with the dialogAppData " + "of the CANCEL " + inviteRequest); } // Transaction inviteTransaction = inviteRequest.getTransaction(); if(logger.isDebugEnabled()) { logger.debug("invite transaction associated with the dialogAppData " + "of the CANCEL " + inviteTransaction); // logger.debug(dialog.isServer()); } TransactionApplicationData inviteAppData = (TransactionApplicationData) inviteTransaction.getApplicationData(); if(logger.isDebugEnabled()) { logger.debug("app data of the invite transaction associated with the dialogAppData " + "of the CANCEL " + inviteAppData); } if(inviteAppData.getProxy() != null) { if(logger.isDebugEnabled()) { logger.debug("proxying the CANCEL " + sipServletRequest); } if(logger.isDebugEnabled()) { logger.debug("CANCEL a proxied request state = " + inviteRequest.getRoutingState()); } // Routing State : PROXY case SipServletResponseImpl inviteResponse = (SipServletResponseImpl) inviteRequest.createResponse(Response.REQUEST_TERMINATED); if(!RoutingState.PROXIED.equals(inviteRequest.getRoutingState())) { // 10.2.6 if the original request has not been proxied yet the container // responds to it with a 487 final response try { inviteRequest.setRoutingState(RoutingState.CANCELLED); } catch (IllegalStateException e) { logger.info("request already proxied, dropping the cancel"); return false; } try { Response requestTerminatedResponse = (Response) inviteResponse.getMessage(); ((ServerTransaction)inviteTransaction).sendResponse(requestTerminatedResponse); } catch (SipException e) { logger.error("Impossible to send the 487 to the INVITE transaction corresponding to CANCEL",e); JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } catch (InvalidArgumentException e) { logger.error("Impossible to send the ok 487 to the INVITE transaction corresponding to CANCEL",e); JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } else { // otherwise, all branches are cancelled, and response processing continues as usual inviteAppData.getProxy().cancel(); } return true; } else if(RoutingState.RELAYED.equals(inviteRequest.getRoutingState())) { if(logger.isDebugEnabled()) { logger.debug("Relaying the CANCEL " + sipServletRequest); } // Routing State : RELAYED - B2BUA case SipServletResponseImpl inviteResponse = (SipServletResponseImpl) inviteRequest.createResponse(Response.REQUEST_TERMINATED); try { inviteRequest.setRoutingState(RoutingState.CANCELLED); } catch (IllegalStateException e) { logger.info("Final response already sent, dropping the cancel"); return false; } try { Response requestTerminatedResponse = (Response) inviteResponse.getMessage(); ((ServerTransaction)inviteTransaction).sendResponse(requestTerminatedResponse); } catch (SipException e) { logger.error("Impossible to send the 487 to the INVITE transaction corresponding to CANCEL",e); JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } catch (InvalidArgumentException e) { logger.error("Impossible to send the ok 487 to the INVITE transaction corresponding to CANCEL",e); JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } //Forwarding the cancel on the other B2BUA side if(inviteRequest.getLinkedRequest() != null) { SipServletRequestImpl cancelRequest = (SipServletRequestImpl) inviteRequest.getLinkedRequest().createCancel(); cancelRequest.send(); return true; } else { SipSessionImpl sipSession = inviteRequest.getSipSession(); sipServletRequest.setSipSession(sipSession); Wrapper servletWrapper = (Wrapper) applicationDeployed.get(sipSession.getKey().getApplicationName()).findChild(sipSession.getHandler()); try{ Servlet servlet = servletWrapper.allocate(); servlet.service(sipServletRequest, null); return true; } catch (ServletException e) { logger.error("An unexpected servlet exception occured while routing the CANCEL", e); // Sends a 500 Internal server error and stops processing. // JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } catch (IOException e) { logger.error("An unexpected IO exception occured while routing the CANCEL", e); // Sends a 500 Internal server error and stops processing. // JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } } else if(RoutingState.FINAL_RESPONSE_SENT.equals(inviteRequest.getRoutingState())) { if(logger.isDebugEnabled()) { logger.debug("the final response has already been sent, nothing to do here"); } return true; } else if(RoutingState.INITIAL.equals(inviteRequest.getRoutingState()) || RoutingState.SUBSEQUENT.equals(inviteRequest.getRoutingState())) { if(logger.isDebugEnabled()) { logger.debug("the app didn't do anything with the request forwarding the cancel on the other tx"); } javax.servlet.sip.Address poppedAddress = sipServletRequest.getPoppedRoute(); if(poppedAddress==null){ throw new IllegalArgumentException("The popped route shouldn't be null for not proxied requests."); } Request clonedRequest = (Request) sipServletRequest.getMessage().clone(); // Branch Id will be assigned by the stack. String transport = JainSipUtils.findTransport(clonedRequest); ViaHeader viaHeader = JainSipUtils.createViaHeader( sipNetworkInterfaceManager, transport, null); // Cancel is hop by hop so remove all other via headers. clonedRequest.removeHeader(ViaHeader.NAME); clonedRequest.addHeader(viaHeader); ClientTransaction clientTransaction = (ClientTransaction)inviteAppData.getTransaction(); Request cancelRequest = clientTransaction.createCancel(); sipProvider.getNewClientTransaction(cancelRequest).sendRequest(); return true; } else { if(logger.isDebugEnabled()) { logger.debug("the initial request isn't in a good routing state "); } throw new IllegalStateException("Initial request for CANCEL is in "+ sipServletRequest.getRoutingState() +" Routing state"); } } private SipApplicationSessionKey makeAppSessionKey(SipContext sipContext, SipServletRequestImpl sipServletRequestImpl, String applicationName) { String callId = null; Request request = (Request) sipServletRequestImpl.getMessage(); Method appKeyMethod = null; if(sipContext != null) appKeyMethod = sipContext.getSipApplicationKeyMethod(); if(appKeyMethod != null) { try { callId = (String) appKeyMethod.invoke(null, new Object[] {sipServletRequestImpl}); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(callId == null) throw new IllegalStateException("SipApplicationKey annotated method shoud not return null"); } else { callId = ((CallIdHeader)request.getHeader((CallIdHeader.NAME))).getCallId(); } SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey( applicationName, callId); return sipApplicationSessionKey; } /** * * @param sipProvider * @param transaction * @param request * @param session * @param sipServletRequest * @throws ParseException * @throws InvalidArgumentException * @throws SipException * @throws TransactionUnavailableException */ private boolean routeInitialRequest(SipProvider sipProvider, SipServletRequestImpl sipServletRequest) throws ParseException, TransactionUnavailableException, SipException, InvalidArgumentException { ServerTransaction transaction = (ServerTransaction) sipServletRequest.getTransaction(); Request request = (Request) sipServletRequest.getMessage(); javax.servlet.sip.Address poppedAddress = sipServletRequest.getPoppedRoute(); logger.info("popped route : " + poppedAddress); //set directive from popped route header if it is present Serializable stateInfo = null; SipApplicationRoutingDirective sipApplicationRoutingDirective = SipApplicationRoutingDirective.NEW;; if(poppedAddress != null) { // get the state info associated with the request because it means // that is has been routed back to the container String directive = poppedAddress.getParameter(ROUTE_PARAM_DIRECTIVE); if(directive != null && directive.length() > 0) { logger.info("directive before the request has been routed back to container : " + directive); sipApplicationRoutingDirective = SipApplicationRoutingDirective.valueOf( SipApplicationRoutingDirective.class, directive); String previousAppName = poppedAddress.getParameter(ROUTE_PARAM_PREV_APPLICATION_NAME); logger.info("application name before the request has been routed back to container : " + previousAppName); SipContext sipContext = applicationDeployed.get(previousAppName); SipSessionKey sipSessionKey = SessionManagerUtil.getSipSessionKey(previousAppName, request, false); SipSessionImpl sipSession = ((SipManager)sipContext.getManager()).getSipSession(sipSessionKey, false, sipFactoryImpl, null); stateInfo = sipSession.getStateInfo(); sipServletRequest.setSipSession(sipSession); logger.info("state info before the request has been routed back to container : " + stateInfo); } } else if(sipServletRequest.getSipSession() != null) { stateInfo = sipServletRequest.getSipSession().getStateInfo(); sipApplicationRoutingDirective = sipServletRequest.getRoutingDirective(); logger.info("previous state info : " + stateInfo); } // 15.4.1 Routing an Initial request Algorithm // 15.4.1 Procedure : point 1 SipApplicationRoutingRegion routingRegion = null; if(sipServletRequest.getSipSession() != null) { routingRegion = sipServletRequest.getSipSession().getRegion(); } //TODO the spec mandates that the sipServletRequest should be //made read only for the AR to process SipApplicationRouterInfo applicationRouterInfo = sipApplicationRouter.getNextApplication( sipServletRequest, routingRegion, sipApplicationRoutingDirective, stateInfo); // 15.4.1 Procedure : point 2 SipRouteModifier sipRouteModifier = applicationRouterInfo.getRouteModifier(); if(logger.isDebugEnabled()) { logger.debug("the AR returned the following sip route modifier" + sipRouteModifier); } if(sipRouteModifier != null) { String[] route = applicationRouterInfo.getRoutes(); switch(sipRouteModifier) { // ROUTE modifier indicates that SipApplicationRouterInfo.getRoute() returns a valid route, // it is up to container to decide whether it is external or internal. case ROUTE : Address routeAddress = null; RouteHeader applicationRouterInfoRouteHeader = null; try { routeAddress = SipFactories.addressFactory.createAddress(route[0]); applicationRouterInfoRouteHeader = SipFactories.headerFactory.createRouteHeader(routeAddress); } catch (ParseException e) { logger.error("Impossible to parse the route returned by the application router " + "into a compliant address",e); // the AR returned an empty string route or a bad route // this shouldn't happen if the route modifier is ROUTE, processing is stopped //and a 500 is sent JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } if(isRouteExternal(applicationRouterInfoRouteHeader)) { // push all of the routes on the Route header stack of the request and // send the request externally for (int i = route.length-1 ; i >= 0; i--) { Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, route[i]); sipServletRequest.getMessage().addHeader(routeHeader); } if(logger.isDebugEnabled()) { logger.debug("Routing the request externally " + sipServletRequest ); } ((Request)sipServletRequest.getMessage()).setRequestURI(SipFactories.addressFactory.createURI(route[0])); forwardStatefully(sipServletRequest, null, sipRouteModifier); return false; } else { // the container MUST make the route available to the applications // via the SipServletRequest.getPoppedRoute() method. sipServletRequest.setPoppedRoute(applicationRouterInfoRouteHeader); break; } // NO_ROUTE indicates that application router is not returning any route // and the SipApplicationRouterInfo.getRoute() value if any should be disregarded. case NO_ROUTE : //nothing to do here //disregard the result.getRoute() and proceed. Specifically the SipServletRequest.getPoppedRoute() //returns the same value as before the invocation of application router. break; // ROUTE_BACK directs the container to push its own route before // pushing the external routes obtained from SipApplicationRouterInfo.getRoutes(). case ROUTE_BACK : // Push container Route, pick up the first outbound interface SipURI sipURI = getOutboundInterfaces().get(0); sipURI.setParameter("modifier", "route_back"); Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, sipURI.toString()); sipServletRequest.getMessage().addHeader(routeHeader); // push all of the routes on the Route header stack of the request and // send the request externally for (int i = route.length-1 ; i >= 0; i--) { routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, route[i]); sipServletRequest.getMessage().addHeader(routeHeader); } if(logger.isDebugEnabled()) { logger.debug("Routing the request externally " + sipServletRequest ); } forwardStatefully(sipServletRequest, null, sipRouteModifier); return false; } } // 15.4.1 Procedure : point 3 if(applicationRouterInfo.getNextApplicationName() == null) { logger.info("Dispatching the request event outside the container"); //check if the request point to another domain javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI(); String host = sipRequestUri.getHost(); int port = sipRequestUri.getPort(); String transport = JainSipUtils.findTransport(request); boolean isAnotherDomain = isExternal(host, port, transport); ListIterator<String> routeHeaders = sipServletRequest.getHeaders(RouteHeader.NAME); if(isAnotherDomain || routeHeaders.hasNext()) { forwardStatefully(sipServletRequest, SipSessionRoutingType.PREVIOUS_SESSION, SipRouteModifier.NO_ROUTE); // FIXME send it statefully // try{ // sipProvider.sendRequest((Request)request.clone()); // logger.info("Initial Request dispatched outside the container" + request.toString()); // } catch (SipException ex) { // throw new IllegalStateException("Error sending request",ex); // } return false; } else { // the Request-URI does not point to another domain, and there is no Route header, // the container should not send the request as it will cause a loop. // Instead, the container must reject the request with 404 Not Found final response with no Retry-After header. JainSipUtils.sendErrorResponse(Response.NOT_FOUND, transaction, request, sipProvider); return false; } } else { logger.info("Dispatching the request event to " + applicationRouterInfo.getNextApplicationName()); sipServletRequest.setCurrentApplicationName(applicationRouterInfo.getNextApplicationName()); SipContext sipContext = applicationDeployed.get(applicationRouterInfo.getNextApplicationName()); // follow the procedures of Chapter 16 to select a servlet from the application. //no matching deployed apps if(sipContext == null) { logger.error("No matching deployed application has been found !"); // the app returned by the Application Router returned an app // that is not currently deployed, sends a 500 error response as was discussed // in the JSR 289 EG, (for reference thread "Questions regarding AR" initiated by Uri Segev) // and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } SipManager sipManager = (SipManager)sipContext.getManager(); //sip appliation session association SipApplicationSessionKey sipApplicationSessionKey = makeAppSessionKey( sipContext, sipServletRequest, applicationRouterInfo.getNextApplicationName()); SipApplicationSessionImpl appSession = sipManager.getSipApplicationSession( sipApplicationSessionKey, true); //sip session association SipSessionKey sessionKey = SessionManagerUtil.getSipSessionKey(applicationRouterInfo.getNextApplicationName(), request, false); SipSessionImpl sipSession = sipManager.getSipSession(sessionKey, true, sipFactoryImpl, appSession); sipSession.setSessionCreatingTransaction(transaction); sipServletRequest.setSipSession(sipSession); // set the request's stateInfo to result.getStateInfo(), region to result.getRegion(), and URI to result.getSubscriberURI(). sipServletRequest.getSipSession().setStateInfo(applicationRouterInfo.getStateInfo()); sipServletRequest.getSipSession().setRoutingRegion(applicationRouterInfo.getRoutingRegion()); sipServletRequest.setRoutingRegion(applicationRouterInfo.getRoutingRegion()); try { URI subscriberUri = SipFactories.addressFactory.createURI(applicationRouterInfo.getSubscriberURI()); if(subscriberUri instanceof javax.sip.address.SipURI) { javax.servlet.sip.URI uri = new SipURIImpl((javax.sip.address.SipURI)subscriberUri); sipServletRequest.setRequestURI(uri); sipServletRequest.setSubscriberURI(uri); } else if (subscriberUri instanceof javax.sip.address.TelURL) { javax.servlet.sip.URI uri = new TelURLImpl((javax.sip.address.TelURL)subscriberUri); sipServletRequest.setRequestURI(uri); sipServletRequest.setSubscriberURI(uri); } } catch (ParseException pe) { - logger.error("An unexpected parse exception occured ", pe); + logger.error("Impossible to parse the subscriber URI returned by the Application Router " + + applicationRouterInfo.getSubscriberURI() + + ", please put one of DAR:<HeaderName> with Header containing a valid URI or an exlicit valid URI ", pe); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } String sipSessionHandlerName = sipServletRequest.getSipSession().getHandler(); if(sipSessionHandlerName == null || sipSessionHandlerName.length() < 1) { String mainServlet = sipContext.getMainServlet(); if(mainServlet != null && mainServlet.length() > 0) { sipSessionHandlerName = mainServlet; } else { SipServletMapping sipServletMapping = sipContext.findSipServletMappings(sipServletRequest); if(sipServletMapping == null) { logger.error("Sending 404 because no matching servlet found for this request " + request); // Sends a 404 and stops processing. JainSipUtils.sendErrorResponse(Response.NOT_FOUND, transaction, request, sipProvider); return false; } else { sipSessionHandlerName = sipServletMapping.getServletName(); } } try { sipServletRequest.getSipSession().setHandler(sipSessionHandlerName); } catch (ServletException e) { // this should never happen logger.error("An unexpected servlet exception occured while routing an initial request",e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } try { callServlet(sipServletRequest); logger.info("Request event dispatched to " + sipContext.getApplicationName()); } catch (ServletException e) { logger.error("An unexpected servlet exception occured while routing an initial request", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } catch (IOException e) { logger.error("An unexpected IO exception occured while routing an initial request", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } //if a final response has been sent, or if the request has //been proxied or relayed we stop routing the request RoutingState routingState = sipServletRequest.getRoutingState(); if(RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || RoutingState.PROXIED.equals(routingState) || RoutingState.RELAYED.equals(routingState) || RoutingState.CANCELLED.equals(routingState)) { if(logger.isDebugEnabled()) { logger.debug("Routing State : " + sipServletRequest.getRoutingState() + "The Container hence stops routing the initial request."); } return false; } else { if(logger.isDebugEnabled()) { logger.debug("Routing State : " + sipServletRequest.getRoutingState() + "The Container hence continue routing the initial request."); } try { // the app that was called didn't do anything with the request // in any case we should route back to container statefully sipServletRequest.addAppCompositionRRHeader(); SipApplicationRouterInfo routerInfo = getNextInterestedApplication(sipServletRequest); if(routerInfo.getNextApplicationName() != null) { if(logger.isDebugEnabled()) { logger.debug("routing back to the container " + "since the following app is interested " + routerInfo.getNextApplicationName()); } //add a route header to direct the request back to the container //to check if there is any other apps interested in it sipServletRequest.addInfoForRoutingBackToContainer(applicationRouterInfo.getNextApplicationName()); } else { if(logger.isDebugEnabled()) { logger.debug("routing outside the container " + "since no more apps are is interested."); // If a servlet does not generate final response the routing process // will continue (non-terminating routing state). This code stops // routing these requests. javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI(); String host = sipRequestUri.getHost(); int port = sipRequestUri.getPort(); String transport = JainSipUtils.findTransport(request); boolean isAnotherDomain = isExternal(host, port, transport); if(!isAnotherDomain) return false; } } forwardStatefully(sipServletRequest, SipSessionRoutingType.CURRENT_SESSION, SipRouteModifier.NO_ROUTE); return true; } catch (SipException e) { logger.error("an exception has occured when trying to forward statefully", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } } } /** * Check if the route is external * @param routeHeader the route to check * @return true if the route is external, false otherwise */ private boolean isRouteExternal(RouteHeader routeHeader) { if (routeHeader != null) { javax.sip.address.SipURI routeUri = (javax.sip.address.SipURI) routeHeader.getAddress().getURI(); String routeTransport = routeUri.getTransportParam(); if(routeTransport == null) { routeTransport = ListeningPoint.UDP; } return isExternal(routeUri.getHost(), routeUri.getPort(), routeTransport); } return true; } /** * Check if the via header is external * @param viaHeader the via header to check * @return true if the via header is external, false otherwise */ private boolean isViaHeaderExternal(ViaHeader viaHeader) { if (viaHeader != null) { return isExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport()); } return true; } /** * Check whether or not the triplet host, port and transport are corresponding to an interface * @param host can be hostname or ipaddress * @param port port number * @param transport transport used * @return true if the triplet host, port and transport are corresponding to an interface * false otherwise */ private boolean isExternal(String host, int port, String transport) { boolean isExternal = true; ExtendedListeningPoint listeningPoint = sipNetworkInterfaceManager.findMatchingListeningPoint(host, port, transport); if((hostNames.contains(host) || listeningPoint != null)) { if(logger.isDebugEnabled()) { logger.debug("hostNames.contains(host)=" + hostNames.contains(host) + " | listeningPoint found = " + listeningPoint); } isExternal = false; } if(logger.isDebugEnabled()) { logger.debug("the triplet host/port/transport : " + host + "/" + port + "/" + transport + " is external : " + isExternal); } return isExternal; } /* * (non-Javadoc) * @see javax.sip.SipListener#processResponse(javax.sip.ResponseEvent) */ public void processResponse(ResponseEvent responseEvent) { logger.info("Response " + responseEvent.getResponse().toString()); Response response = responseEvent.getResponse(); CSeqHeader cSeqHeader = (CSeqHeader)response.getHeader(CSeqHeader.NAME); //if this is a response to a cancel, the response is dropped if(Request.CANCEL.equalsIgnoreCase(cSeqHeader.getMethod())) { if(logger.isDebugEnabled()) { logger.debug("the response is dropped accordingly to JSR 289 " + "since this a response to a CANCEL"); } return; } //if this is a trying response, the response is dropped if(Response.TRYING == response.getStatusCode()) { if(logger.isDebugEnabled()) { logger.debug("the response is dropped accordingly to JSR 289 " + "since this a 100"); } return; } boolean continueRouting = routeResponse(responseEvent); // if continue routing is to true it means that // a B2BUA got it so we don't have anything to do here // or an app that didn't do anything with it // or a when handling the request an app had to be called but wasn't deployed // we have to strip the topmost via header and forward it statefully if (continueRouting) { Response newResponse = (Response) response.clone(); newResponse.removeFirst(ViaHeader.NAME); ListIterator<ViaHeader> viaHeadersLeft = newResponse.getHeaders(ViaHeader.NAME); if(viaHeadersLeft.hasNext()) { //forward it statefully //TODO should decrease the max forward header to avoid infinite loop if(logger.isDebugEnabled()) { logger.debug("forwarding the response statefully " + newResponse); } TransactionApplicationData applicationData = null; if(responseEvent.getClientTransaction() != null) { applicationData = (TransactionApplicationData)responseEvent.getClientTransaction().getApplicationData(); if(logger.isDebugEnabled()) { logger.debug("ctx application Data " + applicationData); } } //there is no client transaction associated with it, it means that this is a retransmission else if(responseEvent.getDialog() != null){ applicationData = (TransactionApplicationData)responseEvent.getDialog().getApplicationData(); if(logger.isDebugEnabled()) { logger.debug("dialog application data " + applicationData); } } ServerTransaction serverTransaction = (ServerTransaction) applicationData.getTransaction(); try { serverTransaction.sendResponse(newResponse); } catch (SipException e) { logger.error("cannot forward the response statefully" , e); } catch (InvalidArgumentException e) { logger.error("cannot forward the response statefully" , e); } } else { //B2BUA case we don't have to do anything here //no more via header B2BUA is the end point if(logger.isDebugEnabled()) { logger.debug("Not forwarding the response statefully. " + "It was either an endpoint or a B2BUA, ie an endpoint too " + newResponse); } } } } /** * Method for routing responses to apps. This uses via header to know which * app has to be called * @param responseEvent the jain sip response received * @return true if we need to continue routing */ private boolean routeResponse(ResponseEvent responseEvent) { Response response = responseEvent.getResponse(); ListIterator<ViaHeader> viaHeaders = response.getHeaders(ViaHeader.NAME); ViaHeader viaHeader = viaHeaders.next(); logger.info("viaHeader = " + viaHeader.toString()); //response meant for the container if(!isViaHeaderExternal(viaHeader)) { ClientTransaction clientTransaction = responseEvent.getClientTransaction(); Dialog dialog = responseEvent.getDialog(); String appNameNotDeployed = viaHeader.getParameter(APP_NOT_DEPLOYED); if(appNameNotDeployed != null && appNameNotDeployed.length() > 0) { return true; } String noAppReturned = viaHeader.getParameter(NO_APP_RETURNED); if(noAppReturned != null && noAppReturned.length() > 0) { return true; } String modifier = viaHeader.getParameter(MODIFIER); if(modifier != null && modifier.length() > 0) { return true; } String appName = viaHeader.getParameter(RR_PARAM_APPLICATION_NAME); String handlerName = viaHeader.getParameter(RR_PARAM_HANDLER_NAME); boolean inverted = false; if(dialog != null && dialog.isServer()) { inverted = true; } SipContext sipContext = applicationDeployed.get(appName); SipManager sipManager = (SipManager)sipContext.getManager(); SipSessionKey sessionKey = SessionManagerUtil.getSipSessionKey(appName, response, inverted); logger.info("route response on following session " + sessionKey); SipSessionImpl session = sipManager.getSipSession(sessionKey, false, sipFactoryImpl, null); if(logger.isDebugEnabled()) { logger.debug("session found is " + session); if(session == null) { sipManager.dumpSipSessions(); } } TransactionApplicationData applicationData = null; SipServletRequestImpl originalRequest = null; if(clientTransaction != null) { applicationData = (TransactionApplicationData)clientTransaction.getApplicationData(); if(applicationData.getSipServletMessage() instanceof SipServletRequestImpl) { originalRequest = (SipServletRequestImpl)applicationData.getSipServletMessage(); } } //there is no client transaction associated with it, it means that this is a retransmission else if(dialog != null){ applicationData = (TransactionApplicationData)dialog.getApplicationData(); } // Transate the repsponse to SipServletResponse SipServletResponseImpl sipServletResponse = new SipServletResponseImpl( response, sipFactoryImpl, clientTransaction, session, dialog, originalRequest); try { session.setHandler(handlerName); // See if this is a response to a proxied request if(originalRequest != null) { originalRequest.setLastFinalResponse(sipServletResponse); } // We can not use session.getProxyBranch() because all branches belong to the same session // and the session.proxyBranch is overwritten each time there is activity on the branch. ProxyBranchImpl proxyBranch = applicationData.getProxyBranch(); if(proxyBranch != null) { sipServletResponse.setProxyBranch(proxyBranch); // Update Session state session.updateStateOnResponse(sipServletResponse, true); // Handle it at the branch proxyBranch.onResponse(sipServletResponse); // Notfiy the servlet if(logger.isDebugEnabled()) { logger.debug("Is Supervised enabled for this proxy branch ? " + proxyBranch.getProxy().getSupervised()); } if(proxyBranch.getProxy().getSupervised()) { callServlet(sipServletResponse); } return false; } else { // Update Session state session.updateStateOnResponse(sipServletResponse, true); callServlet(sipServletResponse); } } catch (ServletException e) { logger.error("Unexpected servlet exception while processing the response : " + response, e); // Sends a 500 Internal server error and stops processing. // JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider); return false; } catch (IOException e) { logger.error("Unexpected io exception while processing the response : " + response, e); // Sends a 500 Internal server error and stops processing. // JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider); return false; } catch (Throwable e) { logger.error("Unexpected exception while processing response : " + response, e); // Sends a 500 Internal server error and stops processing. // JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, clientTransaction, request, sipProvider); return false; } } return true; } public static void callServlet(SipServletRequestImpl request) throws ServletException, IOException { SipSessionImpl session = request.getSipSession(); logger.info("Dispatching request " + request.toString() + " to following App/servlet => " + session.getKey().getApplicationName()+ "/" + session.getHandler()); String sessionHandler = session.getHandler(); SipApplicationSessionImpl sipApplicationSessionImpl = session.getSipApplicationSession(); SipContext sipContext = sipApplicationSessionImpl.getSipContext(); Wrapper sipServletImpl = (Wrapper) sipContext.findChild(sessionHandler); Servlet servlet = sipServletImpl.allocate(); // JBoss-specific CL issue: // This is needed because usually the classloader here is some UnifiedClassLoader3, // which has no idea where the servlet ENC is. We will use the classloader of the // servlet class, which is the WebAppClassLoader, and has ENC fully loaded with // with java:comp/env/security (manager, context etc) ClassLoader cl = servlet.getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(cl); if(!securityCheck(request)) return; servlet.service(request, null); sipServletImpl.deallocate(servlet); } public static void callServlet(SipServletResponseImpl response) throws ServletException, IOException { SipSessionImpl session = response.getSipSession(); logger.info("Dispatching response " + response.toString() + " to following App/servlet => " + session.getKey().getApplicationName()+ "/" + session.getHandler()); Container container = ((SipApplicationSessionImpl)session.getApplicationSession()).getSipContext().findChild(session.getHandler()); Wrapper sipServletImpl = (Wrapper) container; if(sipServletImpl.isUnavailable()) { logger.warn(sipServletImpl.getName()+ " is unavailable, dropping response " + response); } else { Servlet servlet = sipServletImpl.allocate(); servlet.service(null, response); sipServletImpl.deallocate(servlet); } } public static boolean securityCheck(SipServletRequestImpl request) { SipApplicationSessionImpl appSession = (SipApplicationSessionImpl) request.getApplicationSession(); SipContext sipStandardContext = appSession.getSipContext(); boolean authorized = SipSecurityUtils.authorize(sipStandardContext, request); // This will propagate the identity for the thread and all called components // TODO: FIXME: This would introduce a dependency on JBoss // SecurityAssociation.setPrincipal(request.getUserPrincipal()); return authorized; } /* * (non-Javadoc) * @see javax.sip.SipListener#processTimeout(javax.sip.TimeoutEvent) */ public void processTimeout(TimeoutEvent timeoutEvent) { // TODO: FIX ME if(timeoutEvent.isServerTransaction()) { logger.info("timeout => " + timeoutEvent.getServerTransaction().getRequest().toString()); } else { logger.info("timeout => " + timeoutEvent.getClientTransaction().getRequest().toString()); } Transaction transaction = null; if(timeoutEvent.isServerTransaction()) { transaction = timeoutEvent.getServerTransaction(); } else { transaction = timeoutEvent.getClientTransaction(); } TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); SipServletMessageImpl sipServletMessage = tad.getSipServletMessage(); SipSessionImpl sipSession = sipServletMessage.getSipSession(); sipSession.removeOngoingTransaction(transaction); //notifying SipErrorListener that no ACK has been received for a UAS only if(sipServletMessage instanceof SipServletRequestImpl && tad.getProxy() == null && ((SipServletRequestImpl)sipServletMessage).getLastFinalResponse() != null) { List<SipErrorListener> sipErrorListeners = sipSession.getSipApplicationSession().getSipContext().getListeners().getSipErrorListeners(); SipErrorEvent sipErrorEvent = new SipErrorEvent( (SipServletRequest)sipServletMessage, ((SipServletRequestImpl)sipServletMessage).getLastFinalResponse()); for (SipErrorListener sipErrorListener : sipErrorListeners) { try { sipErrorListener.noAckReceived(sipErrorEvent); } catch (Throwable t) { logger.error("SipErrorListener threw exception", t); } } } } /* * (non-Javadoc) * @see javax.sip.SipListener#processTransactionTerminated(javax.sip.TransactionTerminatedEvent) */ public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) { // TODO: FIX ME Transaction transaction = null; if(transactionTerminatedEvent.isServerTransaction()) { transaction = transactionTerminatedEvent.getServerTransaction(); } else { transaction = transactionTerminatedEvent.getClientTransaction(); } logger.info("transaction " + transaction + " terminated => " + transaction.getRequest().toString()); TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); SipSessionImpl sipSessionImpl = tad.getSipServletMessage().getSipSession(); if(sipSessionImpl == null) { logger.info("no app were returned for this transaction " + transaction); } else { sipSessionImpl.removeOngoingTransaction(transaction); } } /** * @return the sipApplicationRouter */ public SipApplicationRouter getSipApplicationRouter() { return sipApplicationRouter; } /** * @param sipApplicationRouter the sipApplicationRouter to set */ public void setSipApplicationRouter(SipApplicationRouter sipApplicationRouter) { this.sipApplicationRouter = sipApplicationRouter; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getSipNetworkInterfaceManager() */ public SipNetworkInterfaceManager getSipNetworkInterfaceManager() { return this.sipNetworkInterfaceManager; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getSipFactory() */ public SipFactory getSipFactory() { return sipFactoryImpl; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getOutboundInterfaces() */ public List<SipURI> getOutboundInterfaces() { return sipNetworkInterfaceManager.getOutboundInterfaces(); } /** * set the outbound interfaces on all servlet context of applications deployed */ private void resetOutboundInterfaces() { List<SipURI> outboundInterfaces = sipNetworkInterfaceManager.getOutboundInterfaces(); for (SipContext sipContext : applicationDeployed.values()) { sipContext.getServletContext().setAttribute(javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES, outboundInterfaces); } } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#addHostName(java.lang.String) */ public void addHostName(String hostName) { if(logger.isDebugEnabled()) { logger.debug(this); logger.debug("Adding hostname "+ hostName); } hostNames.add(hostName); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findHostNames() */ public List<String> findHostNames() { return Collections.unmodifiableList(hostNames); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#removeHostName(java.lang.String) */ public void removeHostName(String hostName) { if(logger.isDebugEnabled()) { logger.debug("Removing hostname "+ hostName); } hostNames.remove(hostName); } /** * @return the sessionManager */ public SessionManagerUtil getSessionManager() { return sessionManager; } /** * */ public SipApplicationRouterInfo getNextInterestedApplication( SipServletRequestImpl sipServletRequest) { SipApplicationRoutingRegion routingRegion = null; Serializable stateInfo = null; if(sipServletRequest.getSipSession() != null) { routingRegion = sipServletRequest.getSipSession().getRegion(); stateInfo =sipServletRequest.getSipSession().getStateInfo(); } SipApplicationRouterInfo applicationRouterInfo = sipApplicationRouter.getNextApplication( sipServletRequest, routingRegion, sipServletRequest.getRoutingDirective(), stateInfo); // 15.4.1 Procedure : point 2 SipRouteModifier sipRouteModifier = applicationRouterInfo.getRouteModifier(); String[] routes = applicationRouterInfo.getRoutes(); try { // ROUTE modifier indicates that SipApplicationRouterInfo.getRoute() returns a valid route, // it is up to container to decide whether it is external or internal. if(SipRouteModifier.ROUTE.equals(sipRouteModifier)) { Address routeAddress = null; RouteHeader applicationRouterInfoRouteHeader = null; routeAddress = SipFactories.addressFactory.createAddress(routes[0]); applicationRouterInfoRouteHeader = SipFactories.headerFactory.createRouteHeader(routeAddress); if(isRouteExternal(applicationRouterInfoRouteHeader)) { // push all of the routes on the Route header stack of the request and // send the request externally for (int i = routes.length-1 ; i >= 0; i--) { Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, routes[i]); sipServletRequest.getMessage().addHeader(routeHeader); } } } else if (SipRouteModifier.ROUTE_BACK.equals(sipRouteModifier)) { // Push container Route, pick up the first outbound interface SipURI sipURI = getOutboundInterfaces().get(0); sipURI.setParameter("modifier", "route_back"); Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, sipURI.toString()); sipServletRequest.getMessage().addHeader(routeHeader); // push all of the routes on the Route header stack of the request and // send the request externally for (int i = routes.length-1 ; i >= 0; i--) { routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, routes[i]); sipServletRequest.getMessage().addHeader(routeHeader); } } } catch (ParseException e) { logger.error("Impossible to parse the route returned by the application router " + "into a compliant address",e); // the AR returned an empty string route or a bad route // this shouldn't happen if the route modifier is ROUTE, processing is stopped //and a 500 is sent // JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); // return false; } return applicationRouterInfo; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findSipApplications() */ public Iterator<SipContext> findSipApplications() { return applicationDeployed.values().iterator(); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findSipApplication(java.lang.String) */ public SipContext findSipApplication(String applicationName) { return applicationDeployed.get(applicationName); } // -------------------- JMX and Registration -------------------- protected String domain; protected ObjectName oname; protected MBeanServer mserver; public ObjectName getObjectName() { return oname; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } /* * (non-Javadoc) * @see javax.management.MBeanRegistration#postDeregister() */ public void postDeregister() {} /* * (non-Javadoc) * @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean) */ public void postRegister(Boolean registrationDone) {} /* * (non-Javadoc) * @see javax.management.MBeanRegistration#preDeregister() */ public void preDeregister() throws Exception {} /* * (non-Javadoc) * @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName) */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { oname=name; mserver=server; domain=name.getDomain(); return name; } /* Exposed methods for the management console. Some of these duplicate existing methods, but * with JMX friendly types. */ public String[] findInstalledSipApplications() { Iterator<SipContext> apps = findSipApplications(); ArrayList<String> appList = new ArrayList<String>(); while(apps.hasNext()){ SipContext ctx = apps.next(); appList.add(ctx.getApplicationName()); } String[] ret = new String[appList.size()]; for(int q=0; q<appList.size(); q++) ret[q] = appList.get(q); return ret; } public Object retrieveApplicationRouterConfiguration() { if(this.sipApplicationRouter instanceof ManageableApplicationRouter) { ManageableApplicationRouter router = (ManageableApplicationRouter) this.sipApplicationRouter; return router.getCurrentConfiguration(); } else { throw new RuntimeException("This application router is not manageable"); } } public void updateApplicationRouterConfiguration(Object configuration) { if(this.sipApplicationRouter instanceof ManageableApplicationRouter) { ManageableApplicationRouter router = (ManageableApplicationRouter) this.sipApplicationRouter; router.configure(configuration); } else { throw new RuntimeException("This application router is not manageable"); } } }
true
true
private boolean routeInitialRequest(SipProvider sipProvider, SipServletRequestImpl sipServletRequest) throws ParseException, TransactionUnavailableException, SipException, InvalidArgumentException { ServerTransaction transaction = (ServerTransaction) sipServletRequest.getTransaction(); Request request = (Request) sipServletRequest.getMessage(); javax.servlet.sip.Address poppedAddress = sipServletRequest.getPoppedRoute(); logger.info("popped route : " + poppedAddress); //set directive from popped route header if it is present Serializable stateInfo = null; SipApplicationRoutingDirective sipApplicationRoutingDirective = SipApplicationRoutingDirective.NEW;; if(poppedAddress != null) { // get the state info associated with the request because it means // that is has been routed back to the container String directive = poppedAddress.getParameter(ROUTE_PARAM_DIRECTIVE); if(directive != null && directive.length() > 0) { logger.info("directive before the request has been routed back to container : " + directive); sipApplicationRoutingDirective = SipApplicationRoutingDirective.valueOf( SipApplicationRoutingDirective.class, directive); String previousAppName = poppedAddress.getParameter(ROUTE_PARAM_PREV_APPLICATION_NAME); logger.info("application name before the request has been routed back to container : " + previousAppName); SipContext sipContext = applicationDeployed.get(previousAppName); SipSessionKey sipSessionKey = SessionManagerUtil.getSipSessionKey(previousAppName, request, false); SipSessionImpl sipSession = ((SipManager)sipContext.getManager()).getSipSession(sipSessionKey, false, sipFactoryImpl, null); stateInfo = sipSession.getStateInfo(); sipServletRequest.setSipSession(sipSession); logger.info("state info before the request has been routed back to container : " + stateInfo); } } else if(sipServletRequest.getSipSession() != null) { stateInfo = sipServletRequest.getSipSession().getStateInfo(); sipApplicationRoutingDirective = sipServletRequest.getRoutingDirective(); logger.info("previous state info : " + stateInfo); } // 15.4.1 Routing an Initial request Algorithm // 15.4.1 Procedure : point 1 SipApplicationRoutingRegion routingRegion = null; if(sipServletRequest.getSipSession() != null) { routingRegion = sipServletRequest.getSipSession().getRegion(); } //TODO the spec mandates that the sipServletRequest should be //made read only for the AR to process SipApplicationRouterInfo applicationRouterInfo = sipApplicationRouter.getNextApplication( sipServletRequest, routingRegion, sipApplicationRoutingDirective, stateInfo); // 15.4.1 Procedure : point 2 SipRouteModifier sipRouteModifier = applicationRouterInfo.getRouteModifier(); if(logger.isDebugEnabled()) { logger.debug("the AR returned the following sip route modifier" + sipRouteModifier); } if(sipRouteModifier != null) { String[] route = applicationRouterInfo.getRoutes(); switch(sipRouteModifier) { // ROUTE modifier indicates that SipApplicationRouterInfo.getRoute() returns a valid route, // it is up to container to decide whether it is external or internal. case ROUTE : Address routeAddress = null; RouteHeader applicationRouterInfoRouteHeader = null; try { routeAddress = SipFactories.addressFactory.createAddress(route[0]); applicationRouterInfoRouteHeader = SipFactories.headerFactory.createRouteHeader(routeAddress); } catch (ParseException e) { logger.error("Impossible to parse the route returned by the application router " + "into a compliant address",e); // the AR returned an empty string route or a bad route // this shouldn't happen if the route modifier is ROUTE, processing is stopped //and a 500 is sent JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } if(isRouteExternal(applicationRouterInfoRouteHeader)) { // push all of the routes on the Route header stack of the request and // send the request externally for (int i = route.length-1 ; i >= 0; i--) { Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, route[i]); sipServletRequest.getMessage().addHeader(routeHeader); } if(logger.isDebugEnabled()) { logger.debug("Routing the request externally " + sipServletRequest ); } ((Request)sipServletRequest.getMessage()).setRequestURI(SipFactories.addressFactory.createURI(route[0])); forwardStatefully(sipServletRequest, null, sipRouteModifier); return false; } else { // the container MUST make the route available to the applications // via the SipServletRequest.getPoppedRoute() method. sipServletRequest.setPoppedRoute(applicationRouterInfoRouteHeader); break; } // NO_ROUTE indicates that application router is not returning any route // and the SipApplicationRouterInfo.getRoute() value if any should be disregarded. case NO_ROUTE : //nothing to do here //disregard the result.getRoute() and proceed. Specifically the SipServletRequest.getPoppedRoute() //returns the same value as before the invocation of application router. break; // ROUTE_BACK directs the container to push its own route before // pushing the external routes obtained from SipApplicationRouterInfo.getRoutes(). case ROUTE_BACK : // Push container Route, pick up the first outbound interface SipURI sipURI = getOutboundInterfaces().get(0); sipURI.setParameter("modifier", "route_back"); Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, sipURI.toString()); sipServletRequest.getMessage().addHeader(routeHeader); // push all of the routes on the Route header stack of the request and // send the request externally for (int i = route.length-1 ; i >= 0; i--) { routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, route[i]); sipServletRequest.getMessage().addHeader(routeHeader); } if(logger.isDebugEnabled()) { logger.debug("Routing the request externally " + sipServletRequest ); } forwardStatefully(sipServletRequest, null, sipRouteModifier); return false; } } // 15.4.1 Procedure : point 3 if(applicationRouterInfo.getNextApplicationName() == null) { logger.info("Dispatching the request event outside the container"); //check if the request point to another domain javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI(); String host = sipRequestUri.getHost(); int port = sipRequestUri.getPort(); String transport = JainSipUtils.findTransport(request); boolean isAnotherDomain = isExternal(host, port, transport); ListIterator<String> routeHeaders = sipServletRequest.getHeaders(RouteHeader.NAME); if(isAnotherDomain || routeHeaders.hasNext()) { forwardStatefully(sipServletRequest, SipSessionRoutingType.PREVIOUS_SESSION, SipRouteModifier.NO_ROUTE); // FIXME send it statefully // try{ // sipProvider.sendRequest((Request)request.clone()); // logger.info("Initial Request dispatched outside the container" + request.toString()); // } catch (SipException ex) { // throw new IllegalStateException("Error sending request",ex); // } return false; } else { // the Request-URI does not point to another domain, and there is no Route header, // the container should not send the request as it will cause a loop. // Instead, the container must reject the request with 404 Not Found final response with no Retry-After header. JainSipUtils.sendErrorResponse(Response.NOT_FOUND, transaction, request, sipProvider); return false; } } else { logger.info("Dispatching the request event to " + applicationRouterInfo.getNextApplicationName()); sipServletRequest.setCurrentApplicationName(applicationRouterInfo.getNextApplicationName()); SipContext sipContext = applicationDeployed.get(applicationRouterInfo.getNextApplicationName()); // follow the procedures of Chapter 16 to select a servlet from the application. //no matching deployed apps if(sipContext == null) { logger.error("No matching deployed application has been found !"); // the app returned by the Application Router returned an app // that is not currently deployed, sends a 500 error response as was discussed // in the JSR 289 EG, (for reference thread "Questions regarding AR" initiated by Uri Segev) // and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } SipManager sipManager = (SipManager)sipContext.getManager(); //sip appliation session association SipApplicationSessionKey sipApplicationSessionKey = makeAppSessionKey( sipContext, sipServletRequest, applicationRouterInfo.getNextApplicationName()); SipApplicationSessionImpl appSession = sipManager.getSipApplicationSession( sipApplicationSessionKey, true); //sip session association SipSessionKey sessionKey = SessionManagerUtil.getSipSessionKey(applicationRouterInfo.getNextApplicationName(), request, false); SipSessionImpl sipSession = sipManager.getSipSession(sessionKey, true, sipFactoryImpl, appSession); sipSession.setSessionCreatingTransaction(transaction); sipServletRequest.setSipSession(sipSession); // set the request's stateInfo to result.getStateInfo(), region to result.getRegion(), and URI to result.getSubscriberURI(). sipServletRequest.getSipSession().setStateInfo(applicationRouterInfo.getStateInfo()); sipServletRequest.getSipSession().setRoutingRegion(applicationRouterInfo.getRoutingRegion()); sipServletRequest.setRoutingRegion(applicationRouterInfo.getRoutingRegion()); try { URI subscriberUri = SipFactories.addressFactory.createURI(applicationRouterInfo.getSubscriberURI()); if(subscriberUri instanceof javax.sip.address.SipURI) { javax.servlet.sip.URI uri = new SipURIImpl((javax.sip.address.SipURI)subscriberUri); sipServletRequest.setRequestURI(uri); sipServletRequest.setSubscriberURI(uri); } else if (subscriberUri instanceof javax.sip.address.TelURL) { javax.servlet.sip.URI uri = new TelURLImpl((javax.sip.address.TelURL)subscriberUri); sipServletRequest.setRequestURI(uri); sipServletRequest.setSubscriberURI(uri); } } catch (ParseException pe) { logger.error("An unexpected parse exception occured ", pe); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } String sipSessionHandlerName = sipServletRequest.getSipSession().getHandler(); if(sipSessionHandlerName == null || sipSessionHandlerName.length() < 1) { String mainServlet = sipContext.getMainServlet(); if(mainServlet != null && mainServlet.length() > 0) { sipSessionHandlerName = mainServlet; } else { SipServletMapping sipServletMapping = sipContext.findSipServletMappings(sipServletRequest); if(sipServletMapping == null) { logger.error("Sending 404 because no matching servlet found for this request " + request); // Sends a 404 and stops processing. JainSipUtils.sendErrorResponse(Response.NOT_FOUND, transaction, request, sipProvider); return false; } else { sipSessionHandlerName = sipServletMapping.getServletName(); } } try { sipServletRequest.getSipSession().setHandler(sipSessionHandlerName); } catch (ServletException e) { // this should never happen logger.error("An unexpected servlet exception occured while routing an initial request",e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } try { callServlet(sipServletRequest); logger.info("Request event dispatched to " + sipContext.getApplicationName()); } catch (ServletException e) { logger.error("An unexpected servlet exception occured while routing an initial request", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } catch (IOException e) { logger.error("An unexpected IO exception occured while routing an initial request", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } //if a final response has been sent, or if the request has //been proxied or relayed we stop routing the request RoutingState routingState = sipServletRequest.getRoutingState(); if(RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || RoutingState.PROXIED.equals(routingState) || RoutingState.RELAYED.equals(routingState) || RoutingState.CANCELLED.equals(routingState)) { if(logger.isDebugEnabled()) { logger.debug("Routing State : " + sipServletRequest.getRoutingState() + "The Container hence stops routing the initial request."); } return false; } else { if(logger.isDebugEnabled()) { logger.debug("Routing State : " + sipServletRequest.getRoutingState() + "The Container hence continue routing the initial request."); } try { // the app that was called didn't do anything with the request // in any case we should route back to container statefully sipServletRequest.addAppCompositionRRHeader(); SipApplicationRouterInfo routerInfo = getNextInterestedApplication(sipServletRequest); if(routerInfo.getNextApplicationName() != null) { if(logger.isDebugEnabled()) { logger.debug("routing back to the container " + "since the following app is interested " + routerInfo.getNextApplicationName()); } //add a route header to direct the request back to the container //to check if there is any other apps interested in it sipServletRequest.addInfoForRoutingBackToContainer(applicationRouterInfo.getNextApplicationName()); } else { if(logger.isDebugEnabled()) { logger.debug("routing outside the container " + "since no more apps are is interested."); // If a servlet does not generate final response the routing process // will continue (non-terminating routing state). This code stops // routing these requests. javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI(); String host = sipRequestUri.getHost(); int port = sipRequestUri.getPort(); String transport = JainSipUtils.findTransport(request); boolean isAnotherDomain = isExternal(host, port, transport); if(!isAnotherDomain) return false; } } forwardStatefully(sipServletRequest, SipSessionRoutingType.CURRENT_SESSION, SipRouteModifier.NO_ROUTE); return true; } catch (SipException e) { logger.error("an exception has occured when trying to forward statefully", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } } }
private boolean routeInitialRequest(SipProvider sipProvider, SipServletRequestImpl sipServletRequest) throws ParseException, TransactionUnavailableException, SipException, InvalidArgumentException { ServerTransaction transaction = (ServerTransaction) sipServletRequest.getTransaction(); Request request = (Request) sipServletRequest.getMessage(); javax.servlet.sip.Address poppedAddress = sipServletRequest.getPoppedRoute(); logger.info("popped route : " + poppedAddress); //set directive from popped route header if it is present Serializable stateInfo = null; SipApplicationRoutingDirective sipApplicationRoutingDirective = SipApplicationRoutingDirective.NEW;; if(poppedAddress != null) { // get the state info associated with the request because it means // that is has been routed back to the container String directive = poppedAddress.getParameter(ROUTE_PARAM_DIRECTIVE); if(directive != null && directive.length() > 0) { logger.info("directive before the request has been routed back to container : " + directive); sipApplicationRoutingDirective = SipApplicationRoutingDirective.valueOf( SipApplicationRoutingDirective.class, directive); String previousAppName = poppedAddress.getParameter(ROUTE_PARAM_PREV_APPLICATION_NAME); logger.info("application name before the request has been routed back to container : " + previousAppName); SipContext sipContext = applicationDeployed.get(previousAppName); SipSessionKey sipSessionKey = SessionManagerUtil.getSipSessionKey(previousAppName, request, false); SipSessionImpl sipSession = ((SipManager)sipContext.getManager()).getSipSession(sipSessionKey, false, sipFactoryImpl, null); stateInfo = sipSession.getStateInfo(); sipServletRequest.setSipSession(sipSession); logger.info("state info before the request has been routed back to container : " + stateInfo); } } else if(sipServletRequest.getSipSession() != null) { stateInfo = sipServletRequest.getSipSession().getStateInfo(); sipApplicationRoutingDirective = sipServletRequest.getRoutingDirective(); logger.info("previous state info : " + stateInfo); } // 15.4.1 Routing an Initial request Algorithm // 15.4.1 Procedure : point 1 SipApplicationRoutingRegion routingRegion = null; if(sipServletRequest.getSipSession() != null) { routingRegion = sipServletRequest.getSipSession().getRegion(); } //TODO the spec mandates that the sipServletRequest should be //made read only for the AR to process SipApplicationRouterInfo applicationRouterInfo = sipApplicationRouter.getNextApplication( sipServletRequest, routingRegion, sipApplicationRoutingDirective, stateInfo); // 15.4.1 Procedure : point 2 SipRouteModifier sipRouteModifier = applicationRouterInfo.getRouteModifier(); if(logger.isDebugEnabled()) { logger.debug("the AR returned the following sip route modifier" + sipRouteModifier); } if(sipRouteModifier != null) { String[] route = applicationRouterInfo.getRoutes(); switch(sipRouteModifier) { // ROUTE modifier indicates that SipApplicationRouterInfo.getRoute() returns a valid route, // it is up to container to decide whether it is external or internal. case ROUTE : Address routeAddress = null; RouteHeader applicationRouterInfoRouteHeader = null; try { routeAddress = SipFactories.addressFactory.createAddress(route[0]); applicationRouterInfoRouteHeader = SipFactories.headerFactory.createRouteHeader(routeAddress); } catch (ParseException e) { logger.error("Impossible to parse the route returned by the application router " + "into a compliant address",e); // the AR returned an empty string route or a bad route // this shouldn't happen if the route modifier is ROUTE, processing is stopped //and a 500 is sent JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } if(isRouteExternal(applicationRouterInfoRouteHeader)) { // push all of the routes on the Route header stack of the request and // send the request externally for (int i = route.length-1 ; i >= 0; i--) { Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, route[i]); sipServletRequest.getMessage().addHeader(routeHeader); } if(logger.isDebugEnabled()) { logger.debug("Routing the request externally " + sipServletRequest ); } ((Request)sipServletRequest.getMessage()).setRequestURI(SipFactories.addressFactory.createURI(route[0])); forwardStatefully(sipServletRequest, null, sipRouteModifier); return false; } else { // the container MUST make the route available to the applications // via the SipServletRequest.getPoppedRoute() method. sipServletRequest.setPoppedRoute(applicationRouterInfoRouteHeader); break; } // NO_ROUTE indicates that application router is not returning any route // and the SipApplicationRouterInfo.getRoute() value if any should be disregarded. case NO_ROUTE : //nothing to do here //disregard the result.getRoute() and proceed. Specifically the SipServletRequest.getPoppedRoute() //returns the same value as before the invocation of application router. break; // ROUTE_BACK directs the container to push its own route before // pushing the external routes obtained from SipApplicationRouterInfo.getRoutes(). case ROUTE_BACK : // Push container Route, pick up the first outbound interface SipURI sipURI = getOutboundInterfaces().get(0); sipURI.setParameter("modifier", "route_back"); Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, sipURI.toString()); sipServletRequest.getMessage().addHeader(routeHeader); // push all of the routes on the Route header stack of the request and // send the request externally for (int i = route.length-1 ; i >= 0; i--) { routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, route[i]); sipServletRequest.getMessage().addHeader(routeHeader); } if(logger.isDebugEnabled()) { logger.debug("Routing the request externally " + sipServletRequest ); } forwardStatefully(sipServletRequest, null, sipRouteModifier); return false; } } // 15.4.1 Procedure : point 3 if(applicationRouterInfo.getNextApplicationName() == null) { logger.info("Dispatching the request event outside the container"); //check if the request point to another domain javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI(); String host = sipRequestUri.getHost(); int port = sipRequestUri.getPort(); String transport = JainSipUtils.findTransport(request); boolean isAnotherDomain = isExternal(host, port, transport); ListIterator<String> routeHeaders = sipServletRequest.getHeaders(RouteHeader.NAME); if(isAnotherDomain || routeHeaders.hasNext()) { forwardStatefully(sipServletRequest, SipSessionRoutingType.PREVIOUS_SESSION, SipRouteModifier.NO_ROUTE); // FIXME send it statefully // try{ // sipProvider.sendRequest((Request)request.clone()); // logger.info("Initial Request dispatched outside the container" + request.toString()); // } catch (SipException ex) { // throw new IllegalStateException("Error sending request",ex); // } return false; } else { // the Request-URI does not point to another domain, and there is no Route header, // the container should not send the request as it will cause a loop. // Instead, the container must reject the request with 404 Not Found final response with no Retry-After header. JainSipUtils.sendErrorResponse(Response.NOT_FOUND, transaction, request, sipProvider); return false; } } else { logger.info("Dispatching the request event to " + applicationRouterInfo.getNextApplicationName()); sipServletRequest.setCurrentApplicationName(applicationRouterInfo.getNextApplicationName()); SipContext sipContext = applicationDeployed.get(applicationRouterInfo.getNextApplicationName()); // follow the procedures of Chapter 16 to select a servlet from the application. //no matching deployed apps if(sipContext == null) { logger.error("No matching deployed application has been found !"); // the app returned by the Application Router returned an app // that is not currently deployed, sends a 500 error response as was discussed // in the JSR 289 EG, (for reference thread "Questions regarding AR" initiated by Uri Segev) // and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } SipManager sipManager = (SipManager)sipContext.getManager(); //sip appliation session association SipApplicationSessionKey sipApplicationSessionKey = makeAppSessionKey( sipContext, sipServletRequest, applicationRouterInfo.getNextApplicationName()); SipApplicationSessionImpl appSession = sipManager.getSipApplicationSession( sipApplicationSessionKey, true); //sip session association SipSessionKey sessionKey = SessionManagerUtil.getSipSessionKey(applicationRouterInfo.getNextApplicationName(), request, false); SipSessionImpl sipSession = sipManager.getSipSession(sessionKey, true, sipFactoryImpl, appSession); sipSession.setSessionCreatingTransaction(transaction); sipServletRequest.setSipSession(sipSession); // set the request's stateInfo to result.getStateInfo(), region to result.getRegion(), and URI to result.getSubscriberURI(). sipServletRequest.getSipSession().setStateInfo(applicationRouterInfo.getStateInfo()); sipServletRequest.getSipSession().setRoutingRegion(applicationRouterInfo.getRoutingRegion()); sipServletRequest.setRoutingRegion(applicationRouterInfo.getRoutingRegion()); try { URI subscriberUri = SipFactories.addressFactory.createURI(applicationRouterInfo.getSubscriberURI()); if(subscriberUri instanceof javax.sip.address.SipURI) { javax.servlet.sip.URI uri = new SipURIImpl((javax.sip.address.SipURI)subscriberUri); sipServletRequest.setRequestURI(uri); sipServletRequest.setSubscriberURI(uri); } else if (subscriberUri instanceof javax.sip.address.TelURL) { javax.servlet.sip.URI uri = new TelURLImpl((javax.sip.address.TelURL)subscriberUri); sipServletRequest.setRequestURI(uri); sipServletRequest.setSubscriberURI(uri); } } catch (ParseException pe) { logger.error("Impossible to parse the subscriber URI returned by the Application Router " + applicationRouterInfo.getSubscriberURI() + ", please put one of DAR:<HeaderName> with Header containing a valid URI or an exlicit valid URI ", pe); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } String sipSessionHandlerName = sipServletRequest.getSipSession().getHandler(); if(sipSessionHandlerName == null || sipSessionHandlerName.length() < 1) { String mainServlet = sipContext.getMainServlet(); if(mainServlet != null && mainServlet.length() > 0) { sipSessionHandlerName = mainServlet; } else { SipServletMapping sipServletMapping = sipContext.findSipServletMappings(sipServletRequest); if(sipServletMapping == null) { logger.error("Sending 404 because no matching servlet found for this request " + request); // Sends a 404 and stops processing. JainSipUtils.sendErrorResponse(Response.NOT_FOUND, transaction, request, sipProvider); return false; } else { sipSessionHandlerName = sipServletMapping.getServletName(); } } try { sipServletRequest.getSipSession().setHandler(sipSessionHandlerName); } catch (ServletException e) { // this should never happen logger.error("An unexpected servlet exception occured while routing an initial request",e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } try { callServlet(sipServletRequest); logger.info("Request event dispatched to " + sipContext.getApplicationName()); } catch (ServletException e) { logger.error("An unexpected servlet exception occured while routing an initial request", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } catch (IOException e) { logger.error("An unexpected IO exception occured while routing an initial request", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } //if a final response has been sent, or if the request has //been proxied or relayed we stop routing the request RoutingState routingState = sipServletRequest.getRoutingState(); if(RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || RoutingState.PROXIED.equals(routingState) || RoutingState.RELAYED.equals(routingState) || RoutingState.CANCELLED.equals(routingState)) { if(logger.isDebugEnabled()) { logger.debug("Routing State : " + sipServletRequest.getRoutingState() + "The Container hence stops routing the initial request."); } return false; } else { if(logger.isDebugEnabled()) { logger.debug("Routing State : " + sipServletRequest.getRoutingState() + "The Container hence continue routing the initial request."); } try { // the app that was called didn't do anything with the request // in any case we should route back to container statefully sipServletRequest.addAppCompositionRRHeader(); SipApplicationRouterInfo routerInfo = getNextInterestedApplication(sipServletRequest); if(routerInfo.getNextApplicationName() != null) { if(logger.isDebugEnabled()) { logger.debug("routing back to the container " + "since the following app is interested " + routerInfo.getNextApplicationName()); } //add a route header to direct the request back to the container //to check if there is any other apps interested in it sipServletRequest.addInfoForRoutingBackToContainer(applicationRouterInfo.getNextApplicationName()); } else { if(logger.isDebugEnabled()) { logger.debug("routing outside the container " + "since no more apps are is interested."); // If a servlet does not generate final response the routing process // will continue (non-terminating routing state). This code stops // routing these requests. javax.sip.address.SipURI sipRequestUri = (javax.sip.address.SipURI)request.getRequestURI(); String host = sipRequestUri.getHost(); int port = sipRequestUri.getPort(); String transport = JainSipUtils.findTransport(request); boolean isAnotherDomain = isExternal(host, port, transport); if(!isAnotherDomain) return false; } } forwardStatefully(sipServletRequest, SipSessionRoutingType.CURRENT_SESSION, SipRouteModifier.NO_ROUTE); return true; } catch (SipException e) { logger.error("an exception has occured when trying to forward statefully", e); // Sends a 500 Internal server error and stops processing. JainSipUtils.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return false; } } } }
diff --git a/src/main/java/org/thymeleaf/spring3/view/ThymeleafViewResolver.java b/src/main/java/org/thymeleaf/spring3/view/ThymeleafViewResolver.java index 6b3dc99..c2a9e83 100644 --- a/src/main/java/org/thymeleaf/spring3/view/ThymeleafViewResolver.java +++ b/src/main/java/org/thymeleaf/spring3/view/ThymeleafViewResolver.java @@ -1,671 +1,676 @@ /* * ============================================================================= * * Copyright (c) 2011-2012, The THYMELEAF team (http://www.thymeleaf.org) * * 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.thymeleaf.spring3.view; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.core.Ordered; import org.springframework.util.PatternMatchUtils; import org.springframework.web.servlet.View; import org.springframework.web.servlet.view.AbstractCachingViewResolver; import org.springframework.web.servlet.view.InternalResourceView; import org.springframework.web.servlet.view.RedirectView; import org.thymeleaf.spring3.SpringTemplateEngine; /** * <p> * Implementation of the Spring MVC {@link org.springframework.web.servlet.ViewResolver} * interface. * </p> * <p> * View resolvers execute after the controller ends its execution. They receive the name * of the view to be processed and are in charge of creating (and configuring) the * corresponding {@link View} object for it. * </p> * <p> * The {@link View} implementations managed by this class are subclasses of * {@link AbstractThymeleafView}. By default, {@link ThymeleafView} is used. * </p> * * @author Daniel Fern&aacute;ndez * * @since 1.0 * */ public class ThymeleafViewResolver extends AbstractCachingViewResolver implements Ordered { private static final Logger vrlogger = LoggerFactory.getLogger(ThymeleafViewResolver.class); /** * <p> * Prefix to be used in view names (returned by controllers) for specifying an * HTTP redirect. * </p> * <p> * Value: <tt>redirect:</tt> * </p> */ public static final String REDIRECT_URL_PREFIX = "redirect:"; /** * <p> * Prefix to be used in view names (returned by controllers) for specifying an * HTTP forward. * </p> * <p> * Value: <tt>forward:</tt> * </p> */ public static final String FORWARD_URL_PREFIX = "forward:"; private boolean redirectContextRelative = true; private boolean redirectHttp10Compatible = true; private Class<? extends AbstractThymeleafView> viewClass = ThymeleafView.class; private String[] viewNames = null; private String[] excludedViewNames = null; private int order = Integer.MAX_VALUE; private final Map<String, Object> staticVariables = new LinkedHashMap<String, Object>(); private String contentType = null; private String characterEncoding = null; private SpringTemplateEngine templateEngine; /** * <p> * Create an instance of ThymeleafViewResolver. * </p> */ public ThymeleafViewResolver() { super(); } /** * <p> * Set the view class that should be used to create views. This must be a subclass * of {@link AbstractThymeleafView}. The default value is {@link ThymeleafView}. * </p> * * @param viewClass class that is assignable to the required view class * (by default, ThmeleafView). * * @since 2.0.9 * */ public void setViewClass(Class<? extends AbstractThymeleafView> viewClass) { if (viewClass == null || !AbstractThymeleafView.class.isAssignableFrom(viewClass)) { throw new IllegalArgumentException( "Given view class [" + (viewClass != null ? viewClass.getName() : null) + "] is not of type [" + AbstractThymeleafView.class.getName() + "]"); } this.viewClass = viewClass; } /** * <p> * Return the view class to be used to create views. * </p> * * @return the view class. * * @since 2.0.9 * */ protected Class<? extends AbstractThymeleafView> getViewClass() { return this.viewClass; } /** * <p> * Returns the Thymeleaf template engine instance to be used for the * execution of templates. * </p> * <p> * Template engine instances to be used for this view resolver should be of a * subclass of {@link org.thymeleaf.TemplateEngine} including * specific Spring integrations: {@link SpringTemplateEngine}. * </p> * * @return the template engine being used for processing templates. */ public SpringTemplateEngine getTemplateEngine() { return this.templateEngine; } /** * <p> * Sets the Template Engine instance to be used for processing * templates. * </p> * <p> * Template engine instances to be used for this view resolver should be of a * subclass of {@link org.thymeleaf.TemplateEngine} including * specific Spring integrations: {@link SpringTemplateEngine}. * </p> * * @param templateEngine the template engine to be used */ public void setTemplateEngine(final SpringTemplateEngine templateEngine) { this.templateEngine = templateEngine; } /** * <p> * Return the static variables, which will be available at the context * every time a view resolved by this ViewResolver is processed. * </p> * <p> * These static variables are added to the context by the view resolver * before every view is processed, so that they can be referenced from * the context like any other context variables, for example: * <tt>${myStaticVar}</tt>. * </p> * * @return the map of static variables to be set into views' execution. */ public Map<String,Object> getStaticVariables() { return Collections.unmodifiableMap(this.staticVariables); } /** * <p> * Add a new static variable. * </p> * <p> * These static variables are added to the context by the view resolver * before every view is processed, so that they can be referenced from * the context like any other context variables, for example: * <tt>${myStaticVar}</tt>. * </p> * * @param name the name of the static variable * @param value the value of the static variable */ public void addStaticVariable(final String name, final Object value) { this.staticVariables.put(name, value); } /** * <p> * Sets a set of static variables, which will be available at the context * every time a view resolved by this ViewResolver is processed. * </p> * <p> * This method <b>does not overwrite</b> the existing static variables, it * simply adds the ones specify to any variables already registered. * </p> * <p> * These static variables are added to the context by the view resolver * before every view is processed, so that they can be referenced from * the context like any other context variables, for example: * <tt>${myStaticVar}</tt>. * </p> * * * @param variables the set of variables to be added. */ public void setStaticVariables(final Map<String, ?> variables) { if (variables != null) { for (Map.Entry<String, ?> entry : variables.entrySet()) { addStaticVariable(entry.getKey(), entry.getValue()); } } } /** * <p> * Specify the order in which this view resolver will be queried. * </p> * <p> * Spring MVC applications can have several view resolvers configured, * and this <tt>order</tt> property established the order in which * they will be queried for view resolution. * </p> * * @param order the order in which this view resolver will be asked to resolve * the view. */ public void setOrder(final int order) { this.order = order; } /** * <p> * Returns the order in which this view resolver will be queried. * </p> * <p> * Spring MVC applications can have several view resolvers configured, * and this <tt>order</tt> property established the order in which * they will be queried for view resolution. * </p> * * @return the order */ public int getOrder() { return this.order; } /** * <p> * Sets the content type to be used when rendering views. * </p> * <p> * This content type acts as a <i>default</i>, so that every view * resolved by this resolver will use this content type unless there * is a bean defined for such view that specifies a different content type. * </p> * <p> * Therefore, individual views are allowed to specify their own content type * regardless of the <i>application-wide</i> setting established here. * </p> * <p> * If a content type is not specified (either here or at a specific view definition), * {@link AbstractThymeleafView#DEFAULT_CONTENT_TYPE} will be used. * </p> * * @param contentType the content type to be used. */ public void setContentType(final String contentType) { this.contentType = contentType; } /** * <p> * Returns the content type that will be set into views resolved by this * view resolver. * </p> * <p> * This content type acts as a <i>default</i>, so that every view * resolved by this resolver will use this content type unless there * is a bean defined for such view that specifies a different content type. * </p> * <p> * Therefore, individual views are allowed to specify their own content type * regardless of the <i>application-wide</i> setting established here. * </p> * <p> * If a content type is not specified (either at the view resolver or at a specific * view definition), {@link AbstractThymeleafView#DEFAULT_CONTENT_TYPE} will be used. * </p> * * @return the content type currently configured */ public String getContentType() { return this.contentType; } /** * <p> * Specifies the character encoding to be set into the response when * the view is rendered. * </p> * <p> * Many times, character encoding is specified as a part of the <i>content * type</i>, using the {@link #setContentType(String)} or * {@link AbstractThymeleafView#setContentType(String)}, but this is not mandatory, * and it could be that only the MIME type is specified that way, thus allowing * to set the character encoding using this method. * </p> * <p> * As with {@link #setContentType(String)}, the value specified here acts as a * default in case no character encoding has been specified at the view itself. * If a view bean exists with the name of the view to be processed, and this * view has been set a value for its {@link AbstractThymeleafView#setCharacterEncoding(String)} * method, the value specified at the view resolver has no effect. * </p> * * @param characterEncoding the character encoding to be used (e.g. <tt>UTF-8</tt>, * <tt>ISO-8859-1</tt>, etc.) */ public void setCharacterEncoding(final String characterEncoding) { this.characterEncoding = characterEncoding; } /** * <p> * Returns the character encoding set to be used for all views resolved by * this view resolver. * </p> * <p> * Many times, character encoding is specified as a part of the <i>content * type</i>, using the {@link #setContentType(String)} or * {@link AbstractThymeleafView#setContentType(String)}, but this is not mandatory, * and it could be that only the MIME type is specified that way, thus allowing * to set the character encoding using the {@link #setCharacterEncoding(String)} * counterpart of this getter method. * </p> * <p> * As with {@link #setContentType(String)}, the value specified here acts as a * default in case no character encoding has been specified at the view itself. * If a view bean exists with the name of the view to be processed, and this * view has been set a value for its {@link AbstractThymeleafView#setCharacterEncoding(String)} * method, the value specified at the view resolver has no effect. * </p> * * @return the character encoding to be set at a view-resolver-wide level. */ public String getCharacterEncoding() { return this.characterEncoding; } /** * <p> * Set whether to interpret a given redirect URL that starts with a slash ("/") * as relative to the current ServletContext, i.e. as relative to the web application root. * </p> * <p> * Default is <b><tt>true</tt></b>: A redirect URL that starts with a slash will be interpreted * as relative to the web application root, i.e. the context path will be prepended to the URL. * </p> * <p> * Redirect URLs can be specified via the <tt>"redirect:"</tt> prefix. e.g.: * <tt>"redirect:myAction.do"</tt>. * </p> * * @param redirectContextRelative whether redirect URLs should be considered context-relative or not. * @see RedirectView#setContextRelative(boolean) */ public void setRedirectContextRelative(final boolean redirectContextRelative) { this.redirectContextRelative = redirectContextRelative; } /** * <p> * Return whether to interpret a given redirect URL that starts with a slash ("/") * as relative to the current ServletContext, i.e. as relative to the web application root. * </p> * <p> * Default is <b><tt>true</tt></b>. * </p> * * @return true if redirect URLs will be considered relative to context, false if not. * @see RedirectView#setContextRelative(boolean) */ public boolean isRedirectContextRelative() { return this.redirectContextRelative; } /** * <p> * Set whether redirects should stay compatible with HTTP 1.0 clients. * </p> * <p> * In the default implementation (default is <b><tt>true</tt></b>), this will enforce HTTP status * code 302 in any case, i.e. delegate to * {@link javax.servlet.http.HttpServletResponse#sendRedirect(String)}. Turning this off * will send HTTP status code 303, which is the correct code for HTTP 1.1 clients, but not understood * by HTTP 1.0 clients. * </p> * <p> * Many HTTP 1.1 clients treat 302 just like 303, not making any difference. However, some clients * depend on 303 when redirecting after a POST request; turn this flag off in such a scenario. * </p> * Redirect URLs can be specified via the <tt>"redirect:"</tt> prefix. e.g.: * <tt>"redirect:myAction.do"</tt> * </p> * * @param redirectHttp10Compatible true if redirects should stay compatible with HTTP 1.0 clients, * false if not. * @see RedirectView#setHttp10Compatible(boolean) */ public void setRedirectHttp10Compatible(final boolean redirectHttp10Compatible) { this.redirectHttp10Compatible = redirectHttp10Compatible; } /** * <p> * Return whether redirects should stay compatible with HTTP 1.0 clients. * </p> * <p> * Default is <b><tt>true</tt></b>. * </p> * * @return whether redirect responses should stay compatible with HTTP 1.0 clients. * @see RedirectView#setHttp10Compatible(boolean) */ public boolean isRedirectHttp10Compatible() { return this.redirectHttp10Compatible; } /** * <p> * Specify a set of name patterns that will applied to determine whether a view name * returned by a controller will be resolved by this resolver or not. * </p> * <p> * In applications configuring several view resolvers &ndash;for example, one for Thymeleaf * and another one for JSP+JSTL legacy pages&ndash;, this property establishes when * a view will be considered to be resolved by this view resolver and when Spring should * simply ask the next resolver in the chain &ndash;according to its <tt>order</tt>&ndash; * instead. * </p> * <p> * The specified view name patterns can be complete view names, but can also use * the <tt>*</tt> wildcard: "<tt>index.*</tt>", "<tt>user_*</tt>", "<tt>admin/*</tt>", etc. * </p> * <p> * Also note that these view name patterns are checked <i>before</i> applying any prefixes * or suffixes to the view name, so they should not include these. Usually therefore, you * would specify <tt>orders/*</tt> instead of <tt>/WEB-INF/templates/orders/*.html</tt>. * </p> * * @param viewNames the view names (actually view name patterns) * @see PatternMatchUtils#simpleMatch(String[], String) */ public void setViewNames(final String[] viewNames) { this.viewNames = viewNames; } /** * <p> * Return the set of name patterns that will applied to determine whether a view name * returned by a controller will be resolved by this resolver or not. * </p> * <p> * In applications configuring several view resolvers &ndash;for example, one for Thymeleaf * and another one for JSP+JSTL legacy pages&ndash;, this property establishes when * a view will be considered to be resolved by this view resolver and when Spring should * simply ask the next resolver in the chain &ndash;according to its <tt>order</tt>&ndash; * instead. * </p> * <p> * The specified view name patterns can be complete view names, but can also use * the <tt>*</tt> wildcard: "<tt>index.*</tt>", "<tt>user_*</tt>", "<tt>admin/*</tt>", etc. * </p> * <p> * Also note that these view name patterns are checked <i>before</i> applying any prefixes * or suffixes to the view name, so they should not include these. Usually therefore, you * would specify <tt>orders/*</tt> instead of <tt>/WEB-INF/templates/orders/*.html</tt>. * </p> * * @return the view name patterns * @see PatternMatchUtils#simpleMatch(String[], String) */ public String[] getViewNames() { return this.viewNames; } /** * <p> * Specify names of views &ndash;patterns, in fact&ndash; that cannot * be handled by this view resolver. * </p> * <p> * These patterns can be specified in the same format as those in * {@link #setViewNames(String[])}, but work as an <i>exclusion list</i>. * </p> * * @param excludedViewNames the view names to be excluded (actually view name patterns) * @see ThymeleafViewResolver#setViewNames(String[]) * @see PatternMatchUtils#simpleMatch(String[], String) */ public void setExcludedViewNames(final String[] excludedViewNames) { this.excludedViewNames = excludedViewNames; } /** * <p> * Returns the names of views &ndash;patterns, in fact&ndash; that cannot * be handled by this view resolver. * </p> * <p> * These patterns can be specified in the same format as those in * {@link #setViewNames(String[])}, but work as an <i>exclusion list</i>. * </p> * * @return the excluded view name patterns * @see ThymeleafViewResolver#getViewNames() * @see PatternMatchUtils#simpleMatch(String[], String) */ public String[] getExcludedViewNames() { return this.excludedViewNames; } protected boolean canHandle(final String viewName, @SuppressWarnings("unused") final Locale locale) { final String[] viewNamesToBeProcessed = getViewNames(); final String[] viewNamesNotToBeProcessed = getExcludedViewNames(); return ((viewNamesToBeProcessed == null || PatternMatchUtils.simpleMatch(viewNamesToBeProcessed, viewName)) && (viewNamesNotToBeProcessed == null || !PatternMatchUtils.simpleMatch(viewNamesNotToBeProcessed, viewName))); } @Override protected View createView(final String viewName, final Locale locale) throws Exception { if (!canHandle(viewName, locale)) { vrlogger.trace("[THYMELEAF] View \"{}\" cannot be handled by ThymeleafViewResolver. Passing on to the next resolver in the chain.", viewName); return null; } if (viewName.startsWith(REDIRECT_URL_PREFIX)) { vrlogger.trace("[THYMELEAF] View \"{}\" is a redirect, and will not be handled directly by ThymeleafViewResolver.", viewName); final String redirectUrl = viewName.substring(REDIRECT_URL_PREFIX.length()); return new RedirectView(redirectUrl, isRedirectContextRelative(), isRedirectHttp10Compatible()); } if (viewName.startsWith(FORWARD_URL_PREFIX)) { vrlogger.trace("[THYMELEAF] View \"{}\" is a forward, and will not be handled directly by ThymeleafViewResolver.", viewName); final String forwardUrl = viewName.substring(FORWARD_URL_PREFIX.length()); return new InternalResourceView(forwardUrl); } vrlogger.trace("[THYMELEAF] View {} will be handled by ThymeleafViewResolver and a " + "{} instance will be created for it", viewName, this.viewClass.getSimpleName()); return loadView(viewName, locale); } @Override protected View loadView(final String viewName, final Locale locale) throws Exception { final AutowireCapableBeanFactory beanFactory = getApplicationContext().getAutowireCapableBeanFactory(); AbstractThymeleafView view = BeanUtils.instantiateClass(getViewClass()); if (beanFactory.containsBean(viewName)) { final Class<?> viewBeanType = beanFactory.getType(viewName); - if (AbstractThymeleafView.class.isAssignableFrom(viewBeanType)) { + // viewBeanType could be null if bean is abstract (just a set of properties) + if (viewBeanType != null && AbstractThymeleafView.class.isAssignableFrom(viewBeanType)) { view = (AbstractThymeleafView) beanFactory.configureBean(view, viewName); } else { - view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); // The AUTOWIRE_NO mode applies autowiring only through annotations beanFactory.autowireBeanProperties(view, AutowireCapableBeanFactory.AUTOWIRE_NO, false); + // A bean with this name exists, so we apply its properties + beanFactory.applyBeanPropertyValues(view, viewName); + // Finally, we let Spring do the remaining initializations (incl. proxifying if needed) + view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); } } else { - view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); // The AUTOWIRE_NO mode applies autowiring only through annotations beanFactory.autowireBeanProperties(view, AutowireCapableBeanFactory.AUTOWIRE_NO, false); + // Finally, we let Spring do the remaining initializations (incl. proxifying if needed) + view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); } view.setTemplateEngine(getTemplateEngine()); view.setTemplateName(viewName); view.setStaticVariables(getStaticVariables()); if (!view.isContentTypeSet() && getContentType() != null) { view.setContentType(getContentType()); } if (view.getLocale() == null && locale != null) { view.setLocale(locale); } if (view.getCharacterEncoding() == null && getCharacterEncoding() != null) { view.setCharacterEncoding(getCharacterEncoding()); } return view; } }
false
true
protected View loadView(final String viewName, final Locale locale) throws Exception { final AutowireCapableBeanFactory beanFactory = getApplicationContext().getAutowireCapableBeanFactory(); AbstractThymeleafView view = BeanUtils.instantiateClass(getViewClass()); if (beanFactory.containsBean(viewName)) { final Class<?> viewBeanType = beanFactory.getType(viewName); if (AbstractThymeleafView.class.isAssignableFrom(viewBeanType)) { view = (AbstractThymeleafView) beanFactory.configureBean(view, viewName); } else { view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); // The AUTOWIRE_NO mode applies autowiring only through annotations beanFactory.autowireBeanProperties(view, AutowireCapableBeanFactory.AUTOWIRE_NO, false); } } else { view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); // The AUTOWIRE_NO mode applies autowiring only through annotations beanFactory.autowireBeanProperties(view, AutowireCapableBeanFactory.AUTOWIRE_NO, false); } view.setTemplateEngine(getTemplateEngine()); view.setTemplateName(viewName); view.setStaticVariables(getStaticVariables()); if (!view.isContentTypeSet() && getContentType() != null) { view.setContentType(getContentType()); } if (view.getLocale() == null && locale != null) { view.setLocale(locale); } if (view.getCharacterEncoding() == null && getCharacterEncoding() != null) { view.setCharacterEncoding(getCharacterEncoding()); } return view; }
protected View loadView(final String viewName, final Locale locale) throws Exception { final AutowireCapableBeanFactory beanFactory = getApplicationContext().getAutowireCapableBeanFactory(); AbstractThymeleafView view = BeanUtils.instantiateClass(getViewClass()); if (beanFactory.containsBean(viewName)) { final Class<?> viewBeanType = beanFactory.getType(viewName); // viewBeanType could be null if bean is abstract (just a set of properties) if (viewBeanType != null && AbstractThymeleafView.class.isAssignableFrom(viewBeanType)) { view = (AbstractThymeleafView) beanFactory.configureBean(view, viewName); } else { // The AUTOWIRE_NO mode applies autowiring only through annotations beanFactory.autowireBeanProperties(view, AutowireCapableBeanFactory.AUTOWIRE_NO, false); // A bean with this name exists, so we apply its properties beanFactory.applyBeanPropertyValues(view, viewName); // Finally, we let Spring do the remaining initializations (incl. proxifying if needed) view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); } } else { // The AUTOWIRE_NO mode applies autowiring only through annotations beanFactory.autowireBeanProperties(view, AutowireCapableBeanFactory.AUTOWIRE_NO, false); // Finally, we let Spring do the remaining initializations (incl. proxifying if needed) view = (AbstractThymeleafView) beanFactory.initializeBean(view, viewName); } view.setTemplateEngine(getTemplateEngine()); view.setTemplateName(viewName); view.setStaticVariables(getStaticVariables()); if (!view.isContentTypeSet() && getContentType() != null) { view.setContentType(getContentType()); } if (view.getLocale() == null && locale != null) { view.setLocale(locale); } if (view.getCharacterEncoding() == null && getCharacterEncoding() != null) { view.setCharacterEncoding(getCharacterEncoding()); } return view; }
diff --git a/GPSLogger/src/com/mendhak/gpslogger/senders/ZipHelper.java b/GPSLogger/src/com/mendhak/gpslogger/senders/ZipHelper.java index 08e8d151..8963d52d 100644 --- a/GPSLogger/src/com/mendhak/gpslogger/senders/ZipHelper.java +++ b/GPSLogger/src/com/mendhak/gpslogger/senders/ZipHelper.java @@ -1,57 +1,58 @@ package com.mendhak.gpslogger.senders; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipHelper { private static final int BUFFER = 2048; private final String[] files; private final String zipFile; public ZipHelper(String[] files, String zipFile) { this.files = files; this.zipFile = zipFile; } public void Zip() { try { BufferedInputStream origin; FileOutputStream dest = new FileOutputStream(zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; for (String f : files) { FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(f.substring(f.lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } + out.closeEntry(); origin.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } } }
true
true
public void Zip() { try { BufferedInputStream origin; FileOutputStream dest = new FileOutputStream(zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; for (String f : files) { FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(f.substring(f.lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
public void Zip() { try { BufferedInputStream origin; FileOutputStream dest = new FileOutputStream(zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; for (String f : files) { FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(f.substring(f.lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } out.closeEntry(); origin.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/OpenSudoku/src/cz/romario/opensudoku/gui/inputmethod/IMPopupDialog.java b/OpenSudoku/src/cz/romario/opensudoku/gui/inputmethod/IMPopupDialog.java index 37f46b1..cdb661a 100644 --- a/OpenSudoku/src/cz/romario/opensudoku/gui/inputmethod/IMPopupDialog.java +++ b/OpenSudoku/src/cz/romario/opensudoku/gui/inputmethod/IMPopupDialog.java @@ -1,391 +1,391 @@ /* * Copyright (C) 2009 Roman Masek * * This file is part of OpenSudoku. * * OpenSudoku 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. * * OpenSudoku 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 OpenSudoku. If not, see <http://www.gnu.org/licenses/>. * */ package cz.romario.opensudoku.gui.inputmethod; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import android.app.Dialog; import android.content.Context; import android.graphics.LightingColorFilter; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import android.widget.ToggleButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout.LayoutParams; import cz.romario.opensudoku.R; public class IMPopupDialog extends Dialog { private Context mContext; private LayoutInflater mInflater; private TabHost mTabHost; // buttons from "Select number" tab private Map<Integer,Button> mNumberButtons = new HashMap<Integer, Button>(); // buttons from "Edit note" tab private Map<Integer,ToggleButton> mNoteNumberButtons = new HashMap<Integer, ToggleButton>(); // selected number on "Select number" tab (0 if nothing is selected). private int mSelectedNumber; // selected numbers on "Edit note" tab private Set<Integer> mNoteSelectedNumbers = new HashSet<Integer>(); private OnNumberEditListener mOnNumberEditListener; private OnNoteEditListener mOnNoteEditListener; public IMPopupDialog(Context context) { super(context); mContext = context; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mTabHost = createTabView(); // hide dialog's title TextView title = (TextView)findViewById(android.R.id.title); title.setVisibility(View.GONE); setContentView(mTabHost); } /** LightingColorFilter bkgColorFilter = new LightingColorFilter( mContext.getResources().getColor(R.color.im_number_button_completed_background), 0); * Registers a callback to be invoked when number is selected. * @param l */ public void setOnNumberEditListener(OnNumberEditListener l) { mOnNumberEditListener = l; } /** * Register a callback to be invoked when note is edited. * @param l */ public void setOnNoteEditListener(OnNoteEditListener l) { mOnNoteEditListener = l; } public void resetButtons() { for (Button b : mNumberButtons.values()) { b.setBackgroundResource(R.drawable.btn_default_bg); } for (Button b : mNoteNumberButtons.values()) { b.setBackgroundResource(R.drawable.btn_toggle_bg); } for (Map.Entry<Integer, ToggleButton> entry: mNoteNumberButtons.entrySet()) { entry.getValue().setText("" + entry.getKey()); } } // TODO: vsude jinde pouzivam misto number value public void updateNumber(Integer number) { mSelectedNumber = number; LightingColorFilter selBkgColorFilter = new LightingColorFilter( mContext.getResources().getColor(R.color.im_number_button_selected_background), 0); for (Map.Entry<Integer, Button> entry : mNumberButtons.entrySet()) { Button b = entry.getValue(); if (entry.getKey().equals(mSelectedNumber)) { b.setTextAppearance(mContext, android.R.style.TextAppearance_Large_Inverse); b.getBackground().setColorFilter(selBkgColorFilter); } else { b.setTextAppearance(mContext, android.R.style.TextAppearance_Widget_Button); b.getBackground().setColorFilter(null); } } } /** * Updates selected numbers in note. * @param numbers */ public void updateNote(Collection<Integer> numbers) { mNoteSelectedNumbers = new HashSet<Integer>(); if (numbers != null) { for (int number : numbers) { mNoteSelectedNumbers.add(number); } } for (Integer number : mNoteNumberButtons.keySet()) { mNoteNumberButtons.get(number).setChecked(mNoteSelectedNumbers.contains(number)); } } // public void enableAllNumbers() { // for (Button b : mNumberButtons.values()) { // b.setEnabled(true); // } // for (Button b : mNoteNumberButtons.values()) { // b.setEnabled(true); // } // } // public void setNumberEnabled(int number, boolean enabled) { // mNumberButtons.get(number).setEnabled(enabled); // mNoteNumberButtons.get(number).setEnabled(enabled); // } public void highlightNumber(int number) { int completedTextColor = mContext.getResources().getColor(R.color.im_number_button_completed_text); if (number == mSelectedNumber) { mNumberButtons.get(number).setTextColor(completedTextColor); } else { mNumberButtons.get(number).setBackgroundResource(R.drawable.btn_completed_bg); } mNoteNumberButtons.get(number).setBackgroundResource(R.drawable.btn_toggle_completed_bg); } public void setValueCount(int number, int count) { mNumberButtons.get(number).setText(number + " (" + count + ")"); } /** * Creates view with two tabs, first for number in cell selection, second for * note editing. * * @return */ private TabHost createTabView() { - TabHost tabHost = new TabHost(mContext); + TabHost tabHost = new TabHost(mContext, null); //tabHost.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tabHost.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); LinearLayout linearLayout = new LinearLayout(mContext); //linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); linearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); TabWidget tabWidget = new TabWidget(mContext); tabWidget.setId(android.R.id.tabs); FrameLayout frameLayout = new FrameLayout(mContext); frameLayout.setId(android.R.id.tabcontent); linearLayout.addView(tabWidget); linearLayout.addView(frameLayout); tabHost.addView(linearLayout); tabHost.setup(); final View editNumberView = createEditNumberView(); final View editNoteView = createEditNoteView(); tabHost.addTab(tabHost.newTabSpec("number") .setIndicator(mContext.getString(R.string.select_number)) .setContent(new TabHost.TabContentFactory() { @Override public View createTabContent(String tag) { return editNumberView; } })); tabHost.addTab(tabHost.newTabSpec("note") .setIndicator(mContext.getString(R.string.edit_note)) .setContent(new TabHost.TabContentFactory() { @Override public View createTabContent(String tag) { return editNoteView; } })); return tabHost; } /** * Creates view for number in cell editing. * @return */ private View createEditNumberView() { View v = mInflater.inflate(R.layout.im_popup_edit_value, null); mNumberButtons.put(1, (Button)v.findViewById(R.id.button_1)); mNumberButtons.put(2, (Button)v.findViewById(R.id.button_2)); mNumberButtons.put(3, (Button)v.findViewById(R.id.button_3)); mNumberButtons.put(4, (Button)v.findViewById(R.id.button_4)); mNumberButtons.put(5, (Button)v.findViewById(R.id.button_5)); mNumberButtons.put(6, (Button)v.findViewById(R.id.button_6)); mNumberButtons.put(7, (Button)v.findViewById(R.id.button_7)); mNumberButtons.put(8, (Button)v.findViewById(R.id.button_8)); mNumberButtons.put(9, (Button)v.findViewById(R.id.button_9)); for (Integer num : mNumberButtons.keySet()) { Button b = mNumberButtons.get(num); b.setTag(num); b.setOnClickListener(editNumberButtonClickListener); } Button closeButton = (Button)v.findViewById(R.id.button_close); closeButton.setOnClickListener(closeButtonListener); Button clearButton = (Button)v.findViewById(R.id.button_clear); clearButton.setOnClickListener(clearButtonListener); return v; } /** * Creates view for note editing. * @return */ private View createEditNoteView() { View v = mInflater.inflate(R.layout.im_popup_edit_note, null); mNoteNumberButtons.put(1, (ToggleButton)v.findViewById(R.id.button_1)); mNoteNumberButtons.put(2, (ToggleButton)v.findViewById(R.id.button_2)); mNoteNumberButtons.put(3, (ToggleButton)v.findViewById(R.id.button_3)); mNoteNumberButtons.put(4, (ToggleButton)v.findViewById(R.id.button_4)); mNoteNumberButtons.put(5, (ToggleButton)v.findViewById(R.id.button_5)); mNoteNumberButtons.put(6, (ToggleButton)v.findViewById(R.id.button_6)); mNoteNumberButtons.put(7, (ToggleButton)v.findViewById(R.id.button_7)); mNoteNumberButtons.put(8, (ToggleButton)v.findViewById(R.id.button_8)); mNoteNumberButtons.put(9, (ToggleButton)v.findViewById(R.id.button_9)); for (Integer num : mNoteNumberButtons.keySet()) { ToggleButton b = mNoteNumberButtons.get(num); b.setTag(num); b.setOnCheckedChangeListener(editNoteCheckedChangeListener); } Button closeButton = (Button)v.findViewById(R.id.button_close); closeButton.setOnClickListener(closeButtonListener); Button clearButton = (Button)v.findViewById(R.id.button_clear); clearButton.setOnClickListener(clearButtonListener); return v; } /** * Occurs when user selects number in "Select number" tab. */ private View.OnClickListener editNumberButtonClickListener = new View.OnClickListener() { @Override public void onClick(View v) { Integer number = (Integer)v.getTag(); if (mOnNumberEditListener != null) { mOnNumberEditListener.onNumberEdit(number); } dismiss(); } }; /** * Occurs when user checks or unchecks number in "Edit note" tab. */ private OnCheckedChangeListener editNoteCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Integer number = (Integer)buttonView.getTag(); if (isChecked) { mNoteSelectedNumbers.add(number); } else { mNoteSelectedNumbers.remove(number); } } }; /** * Occurs when user presses "Clear" button. */ private View.OnClickListener clearButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { String currentTab = mTabHost.getCurrentTabTag(); if (currentTab.equals("number")) { if (mOnNumberEditListener != null) { mOnNumberEditListener.onNumberEdit(0); // 0 as clear } dismiss(); } else { for (ToggleButton b : mNoteNumberButtons.values()) { b.setChecked(false); mNoteSelectedNumbers.remove(b.getTag()); } } } }; /** * Occurs when user presses "Close" button. */ private View.OnClickListener closeButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { if (mOnNoteEditListener != null) { Integer[] numbers = new Integer[mNoteSelectedNumbers.size()]; mOnNoteEditListener.onNoteEdit(mNoteSelectedNumbers.toArray(numbers)); } dismiss(); } }; /** * Interface definition for a callback to be invoked, when user selects number, which * should be entered in the sudoku cell. * * @author romario * */ public interface OnNumberEditListener { boolean onNumberEdit(int number); } /** * Interface definition for a callback to be invoked, when user selects new note * content. * * @author romario * */ public interface OnNoteEditListener { boolean onNoteEdit(Integer[] number); } }
true
true
private TabHost createTabView() { TabHost tabHost = new TabHost(mContext); //tabHost.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tabHost.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); LinearLayout linearLayout = new LinearLayout(mContext); //linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); linearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); TabWidget tabWidget = new TabWidget(mContext); tabWidget.setId(android.R.id.tabs); FrameLayout frameLayout = new FrameLayout(mContext); frameLayout.setId(android.R.id.tabcontent); linearLayout.addView(tabWidget); linearLayout.addView(frameLayout); tabHost.addView(linearLayout); tabHost.setup(); final View editNumberView = createEditNumberView(); final View editNoteView = createEditNoteView(); tabHost.addTab(tabHost.newTabSpec("number") .setIndicator(mContext.getString(R.string.select_number)) .setContent(new TabHost.TabContentFactory() { @Override public View createTabContent(String tag) { return editNumberView; } })); tabHost.addTab(tabHost.newTabSpec("note") .setIndicator(mContext.getString(R.string.edit_note)) .setContent(new TabHost.TabContentFactory() { @Override public View createTabContent(String tag) { return editNoteView; } })); return tabHost; }
private TabHost createTabView() { TabHost tabHost = new TabHost(mContext, null); //tabHost.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tabHost.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); LinearLayout linearLayout = new LinearLayout(mContext); //linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); linearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); TabWidget tabWidget = new TabWidget(mContext); tabWidget.setId(android.R.id.tabs); FrameLayout frameLayout = new FrameLayout(mContext); frameLayout.setId(android.R.id.tabcontent); linearLayout.addView(tabWidget); linearLayout.addView(frameLayout); tabHost.addView(linearLayout); tabHost.setup(); final View editNumberView = createEditNumberView(); final View editNoteView = createEditNoteView(); tabHost.addTab(tabHost.newTabSpec("number") .setIndicator(mContext.getString(R.string.select_number)) .setContent(new TabHost.TabContentFactory() { @Override public View createTabContent(String tag) { return editNumberView; } })); tabHost.addTab(tabHost.newTabSpec("note") .setIndicator(mContext.getString(R.string.edit_note)) .setContent(new TabHost.TabContentFactory() { @Override public View createTabContent(String tag) { return editNoteView; } })); return tabHost; }
diff --git a/src/java/net/sf/picard/metrics/MetricsFile.java b/src/java/net/sf/picard/metrics/MetricsFile.java index d6de3741..484c2781 100644 --- a/src/java/net/sf/picard/metrics/MetricsFile.java +++ b/src/java/net/sf/picard/metrics/MetricsFile.java @@ -1,453 +1,453 @@ /* * The MIT License * * Copyright (c) 2009 The Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.sf.picard.metrics; import net.sf.picard.PicardException; import net.sf.picard.util.FormatUtil; import net.sf.picard.util.Histogram; import net.sf.samtools.util.StringUtil; import java.io.*; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.TreeSet; /** * Contains a set of metrics that can be written to a file and parsed back * again. The set of metrics is composed of zero or more instances of a class, * BEAN, that extends {@link MetricBase} (all instances must be of the same type) * and may optionally include one or more histograms that share the same key set. * * @author Tim Fennell */ public class MetricsFile<BEAN extends MetricBase, HKEY extends Comparable> { public static final String MAJOR_HEADER_PREFIX = "## "; public static final String MINOR_HEADER_PREFIX = "# "; public static final String SEPARATOR = "\t"; public static final String HISTO_HEADER = "## HISTOGRAM\t"; public static final String METRIC_HEADER = "## METRICS CLASS\t"; private final List<Header> headers = new ArrayList<Header>(); private final List<BEAN> metrics = new ArrayList<BEAN>(); private final List<Histogram<HKEY>> histograms = new ArrayList<Histogram<HKEY>>(); /** Adds a header to the collection of metrics. */ public void addHeader(Header h) { this.headers.add(h); } /** Returns the list of headers. */ public List<Header> getHeaders() { return Collections.unmodifiableList(this.headers); } /** Adds a bean to the collection of metrics. */ public void addMetric(BEAN bean) { this.metrics.add(bean); } /** Returns the list of headers. */ public List<BEAN> getMetrics() { return Collections.unmodifiableList(this.metrics); } /** Returns the histogram contained in the metrics file if any. */ public Histogram<HKEY> getHistogram() { if (histograms.size() > 0) return this.histograms.get(0); else return null; } /** Sets the histogram contained in the metrics file. */ public void setHistogram(Histogram<HKEY> histogram) { if (this.histograms.isEmpty()) { if (histogram != null) this.histograms.add(histogram); } else { this.histograms.set(0, histogram); } } /** Adds a histogram to the list of histograms in the metrics file. */ public void addHistogram(Histogram<HKEY> histogram) { this.histograms.add(histogram); } /** Returns the number of histograms added to the metrics file. */ public int getNumHistograms() { return this.histograms.size(); } /** Returns the list of headers with the specified type. */ public List<Header> getHeaders(Class<? extends Header> type) { List<Header> tmp = new ArrayList<Header>(); for (Header h : this.headers) { if (h.getClass().equals(type)) { tmp.add(h); } } return tmp; } /** * Writes out the metrics file to the supplied file. The file is written out * headers first, metrics second and histogram third. * * @param f a File into which to write the metrics */ public void write(File f) { FileWriter w = null; try { w = new FileWriter(f); write(w); } catch (IOException ioe) { throw new PicardException("Could not write metrics to file: " + f.getAbsolutePath(), ioe); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } } } /** * Writes out the metrics file to the supplied writer. The file is written out * headers first, metrics second and histogram third. * * @param w a Writer into which to write the metrics */ public void write(Writer w) { try { FormatUtil formatter = new FormatUtil(); BufferedWriter out = new BufferedWriter(w); printHeaders(out); out.newLine(); printBeanMetrics(out, formatter); out.newLine(); printHistogram(out, formatter); out.newLine(); out.flush(); } catch (IOException ioe) { throw new PicardException("Could not write metrics file.", ioe); } } /** Prints the headers into the provided PrintWriter. */ private void printHeaders(BufferedWriter out) throws IOException { for (Header h : this.headers) { out.append(MAJOR_HEADER_PREFIX); out.append(h.getClass().getName()); out.newLine(); out.append(MINOR_HEADER_PREFIX); out.append(h.toString()); out.newLine(); } } /** Prints each of the metrics entries into the provided PrintWriter. */ private void printBeanMetrics(BufferedWriter out, FormatUtil formatter) throws IOException { if (this.metrics.isEmpty()) { return; } // Write out a header row with the type of the metric class out.append(METRIC_HEADER + getBeanType().getName()); out.newLine(); // Write out the column headers Field[] fields = getBeanType().getFields(); final int fieldCount = fields.length; for (int i=0; i<fieldCount; ++i) { out.append(fields[i].getName()); if (i < fieldCount - 1) { out.append(MetricsFile.SEPARATOR); } else { out.newLine(); } } // Write out each of the data rows for (BEAN bean : this.metrics) { for (int i=0; i<fieldCount; ++i) { try { Object value = fields[i].get(bean); out.append(StringUtil.assertCharactersNotInString(formatter.format(value), '\t', '\n')); if (i < fieldCount - 1) { out.append(MetricsFile.SEPARATOR); } else { out.newLine(); } } catch (IllegalAccessException iae) { throw new PicardException("Could not read property " + fields[i].getName() + " from class of type " + bean.getClass()); } } } out.flush(); } /** Prints the histogram if one is present. */ private void printHistogram(BufferedWriter out, FormatUtil formatter) throws IOException { if (this.histograms.isEmpty()) { return; } // Build a combined key set java.util.Set<HKEY> keys = new TreeSet<HKEY>(); for (Histogram<HKEY> histo : histograms) { if (histo != null) keys.addAll(histo.keySet()); } // Add a header for the histogram key type out.append(HISTO_HEADER + this.histograms.get(0).keySet().iterator().next().getClass().getName()); out.newLine(); // Output a header row out.append(StringUtil.assertCharactersNotInString(this.histograms.get(0).getBinLabel(), '\t', '\n')); for (Histogram<HKEY> histo : this.histograms) { out.append(SEPARATOR); out.append(StringUtil.assertCharactersNotInString(histo.getValueLabel(), '\t', '\n')); } out.newLine(); for (HKEY key : keys) { out.append(key.toString()); for (Histogram<HKEY> histo : this.histograms) { Histogram<HKEY>.Bin bin = histo.get(key); final double value = (bin == null ? 0 : bin.getValue()); out.append(SEPARATOR); out.append(formatter.format(value)); } out.newLine(); } } /** Gets the type of the metrics bean being used. */ private Class<?> getBeanType() { if (this.metrics == null || this.metrics.isEmpty()) { return null; } else { return this.metrics.get(0).getClass(); } } /** Reads the Metrics in from the given reader. */ public void read(Reader r) { BufferedReader in = new BufferedReader(r); FormatUtil formatter = new FormatUtil(); String line = null; try { // First read the headers Header header = null; boolean inHeader = true; while ((line = in.readLine()) != null && inHeader) { line = line.trim(); // A blank line signals the end of the headers, otherwise parse out // the header types and values and build the headers. if ("".equals(line)) { inHeader = false; } else if (line.startsWith(MAJOR_HEADER_PREFIX)) { if (header != null) { throw new IllegalStateException("Consecutive header class lines encountered."); } String className = line.substring(MAJOR_HEADER_PREFIX.length()).trim(); try { header = (Header) loadClass(className).newInstance(); } catch (Exception e) { throw new PicardException("Error load and/or instantiating an instance of " + className, e); } } else if (line.startsWith(MINOR_HEADER_PREFIX)) { if (header == null) { throw new IllegalStateException("Header class must precede header value:" + line); } header.parse(line.substring(MINOR_HEADER_PREFIX.length())); this.headers.add(header); header = null; } else { throw new PicardException("Illegal state. Found following string in metrics file header: " + line); } } if (line == null) { throw new PicardException("No lines in metrics file after header."); } // Then read the metrics if there are any while (!line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine().trim(); } if (line.startsWith(METRIC_HEADER)) { // Get the metric class from the header String className = line.split(SEPARATOR)[1]; Class<?> type = null; try { type = loadClass(className); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not locate class with name " + className, cnfe); } // Read the next line with the column headers String[] fieldNames = in.readLine().split(SEPARATOR); Field[] fields = new Field[fieldNames.length]; for (int i=0; i<fieldNames.length; ++i) { try { fields[i] = type.getField(fieldNames[i]); } catch (Exception e) { throw new PicardException("Could not get field with name " + fieldNames[i] + " from class " + type.getName()); } } // Now read the values while ((line = in.readLine()) != null) { line = line.trim(); if ("".equals(line)) { break; } else { - String[] values = line.split(SEPARATOR); + String[] values = line.split(SEPARATOR, -1); BEAN bean = null; try { bean = (BEAN) type.newInstance(); } catch (Exception e) { throw new PicardException("Error instantiating a " + type.getName(), e); } for (int i=0; i<fields.length; ++i) { Object value = null; if (values[i] != null && values[i].length() > 0) { value = formatter.parseObject(values[i], fields[i].getType()); } try { fields[i].set(bean, value); } catch (Exception e) { throw new PicardException("Error setting field " + fields[i].getName() + " on class of type " + type.getName(), e); } } this.metrics.add(bean); } } } // Then read the histograms if any are present while (line != null && !line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine(); } if (line != null && line.startsWith(HISTO_HEADER)) { // Get the key type of the histogram String keyClassName = line.split(SEPARATOR)[1].trim(); Class<?> keyClass = null; try { keyClass = loadClass(keyClassName); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not load class with name " + keyClassName); } // Read the next line with the bin and value labels String[] labels = in.readLine().split(SEPARATOR); for (int i=1; i<labels.length; ++i) { this.histograms.add(new Histogram<HKEY>(labels[0], labels[i])); } // Read the entries in the histograms while ((line = in.readLine()) != null && !"".equals(line)) { String[] fields = line.trim().split(SEPARATOR); HKEY key = (HKEY) formatter.parseObject(fields[0], keyClass); for (int i=1; i<fields.length; ++i) { double value = formatter.parseDouble(fields[i]); this.histograms.get(i-1).increment(key, value); } } } } catch (IOException ioe) { throw new PicardException("Could not read metrics from reader.", ioe); } } /** Attempts to load a class, taking into account that some classes have "migrated" from the broad to sf. */ private Class<?> loadClass(String className) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException cnfe) { if (className.startsWith("edu.mit.broad.picard")) { return loadClass(className.replace("edu.mit.broad.picard", "net.sf.picard")); } else { throw cnfe; } } } /** Checks that the headers, metrics and histogram are all equal. */ @Override public boolean equals(Object o) { if (o == null) { return false; } if (getClass() != o.getClass()) { return false; } MetricsFile that = (MetricsFile) o; if (!this.headers.equals(that.headers)) { return false; } if (!this.metrics.equals(that.metrics)) { return false; } if (!this.histograms.equals(that.histograms)) { return false; } return true; } @Override public int hashCode() { int result = headers.hashCode(); result = 31 * result + metrics.hashCode(); return result; } }
true
true
public void read(Reader r) { BufferedReader in = new BufferedReader(r); FormatUtil formatter = new FormatUtil(); String line = null; try { // First read the headers Header header = null; boolean inHeader = true; while ((line = in.readLine()) != null && inHeader) { line = line.trim(); // A blank line signals the end of the headers, otherwise parse out // the header types and values and build the headers. if ("".equals(line)) { inHeader = false; } else if (line.startsWith(MAJOR_HEADER_PREFIX)) { if (header != null) { throw new IllegalStateException("Consecutive header class lines encountered."); } String className = line.substring(MAJOR_HEADER_PREFIX.length()).trim(); try { header = (Header) loadClass(className).newInstance(); } catch (Exception e) { throw new PicardException("Error load and/or instantiating an instance of " + className, e); } } else if (line.startsWith(MINOR_HEADER_PREFIX)) { if (header == null) { throw new IllegalStateException("Header class must precede header value:" + line); } header.parse(line.substring(MINOR_HEADER_PREFIX.length())); this.headers.add(header); header = null; } else { throw new PicardException("Illegal state. Found following string in metrics file header: " + line); } } if (line == null) { throw new PicardException("No lines in metrics file after header."); } // Then read the metrics if there are any while (!line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine().trim(); } if (line.startsWith(METRIC_HEADER)) { // Get the metric class from the header String className = line.split(SEPARATOR)[1]; Class<?> type = null; try { type = loadClass(className); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not locate class with name " + className, cnfe); } // Read the next line with the column headers String[] fieldNames = in.readLine().split(SEPARATOR); Field[] fields = new Field[fieldNames.length]; for (int i=0; i<fieldNames.length; ++i) { try { fields[i] = type.getField(fieldNames[i]); } catch (Exception e) { throw new PicardException("Could not get field with name " + fieldNames[i] + " from class " + type.getName()); } } // Now read the values while ((line = in.readLine()) != null) { line = line.trim(); if ("".equals(line)) { break; } else { String[] values = line.split(SEPARATOR); BEAN bean = null; try { bean = (BEAN) type.newInstance(); } catch (Exception e) { throw new PicardException("Error instantiating a " + type.getName(), e); } for (int i=0; i<fields.length; ++i) { Object value = null; if (values[i] != null && values[i].length() > 0) { value = formatter.parseObject(values[i], fields[i].getType()); } try { fields[i].set(bean, value); } catch (Exception e) { throw new PicardException("Error setting field " + fields[i].getName() + " on class of type " + type.getName(), e); } } this.metrics.add(bean); } } } // Then read the histograms if any are present while (line != null && !line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine(); } if (line != null && line.startsWith(HISTO_HEADER)) { // Get the key type of the histogram String keyClassName = line.split(SEPARATOR)[1].trim(); Class<?> keyClass = null; try { keyClass = loadClass(keyClassName); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not load class with name " + keyClassName); } // Read the next line with the bin and value labels String[] labels = in.readLine().split(SEPARATOR); for (int i=1; i<labels.length; ++i) { this.histograms.add(new Histogram<HKEY>(labels[0], labels[i])); } // Read the entries in the histograms while ((line = in.readLine()) != null && !"".equals(line)) { String[] fields = line.trim().split(SEPARATOR); HKEY key = (HKEY) formatter.parseObject(fields[0], keyClass); for (int i=1; i<fields.length; ++i) { double value = formatter.parseDouble(fields[i]); this.histograms.get(i-1).increment(key, value); } } } } catch (IOException ioe) { throw new PicardException("Could not read metrics from reader.", ioe); } }
public void read(Reader r) { BufferedReader in = new BufferedReader(r); FormatUtil formatter = new FormatUtil(); String line = null; try { // First read the headers Header header = null; boolean inHeader = true; while ((line = in.readLine()) != null && inHeader) { line = line.trim(); // A blank line signals the end of the headers, otherwise parse out // the header types and values and build the headers. if ("".equals(line)) { inHeader = false; } else if (line.startsWith(MAJOR_HEADER_PREFIX)) { if (header != null) { throw new IllegalStateException("Consecutive header class lines encountered."); } String className = line.substring(MAJOR_HEADER_PREFIX.length()).trim(); try { header = (Header) loadClass(className).newInstance(); } catch (Exception e) { throw new PicardException("Error load and/or instantiating an instance of " + className, e); } } else if (line.startsWith(MINOR_HEADER_PREFIX)) { if (header == null) { throw new IllegalStateException("Header class must precede header value:" + line); } header.parse(line.substring(MINOR_HEADER_PREFIX.length())); this.headers.add(header); header = null; } else { throw new PicardException("Illegal state. Found following string in metrics file header: " + line); } } if (line == null) { throw new PicardException("No lines in metrics file after header."); } // Then read the metrics if there are any while (!line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine().trim(); } if (line.startsWith(METRIC_HEADER)) { // Get the metric class from the header String className = line.split(SEPARATOR)[1]; Class<?> type = null; try { type = loadClass(className); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not locate class with name " + className, cnfe); } // Read the next line with the column headers String[] fieldNames = in.readLine().split(SEPARATOR); Field[] fields = new Field[fieldNames.length]; for (int i=0; i<fieldNames.length; ++i) { try { fields[i] = type.getField(fieldNames[i]); } catch (Exception e) { throw new PicardException("Could not get field with name " + fieldNames[i] + " from class " + type.getName()); } } // Now read the values while ((line = in.readLine()) != null) { line = line.trim(); if ("".equals(line)) { break; } else { String[] values = line.split(SEPARATOR, -1); BEAN bean = null; try { bean = (BEAN) type.newInstance(); } catch (Exception e) { throw new PicardException("Error instantiating a " + type.getName(), e); } for (int i=0; i<fields.length; ++i) { Object value = null; if (values[i] != null && values[i].length() > 0) { value = formatter.parseObject(values[i], fields[i].getType()); } try { fields[i].set(bean, value); } catch (Exception e) { throw new PicardException("Error setting field " + fields[i].getName() + " on class of type " + type.getName(), e); } } this.metrics.add(bean); } } } // Then read the histograms if any are present while (line != null && !line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine(); } if (line != null && line.startsWith(HISTO_HEADER)) { // Get the key type of the histogram String keyClassName = line.split(SEPARATOR)[1].trim(); Class<?> keyClass = null; try { keyClass = loadClass(keyClassName); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not load class with name " + keyClassName); } // Read the next line with the bin and value labels String[] labels = in.readLine().split(SEPARATOR); for (int i=1; i<labels.length; ++i) { this.histograms.add(new Histogram<HKEY>(labels[0], labels[i])); } // Read the entries in the histograms while ((line = in.readLine()) != null && !"".equals(line)) { String[] fields = line.trim().split(SEPARATOR); HKEY key = (HKEY) formatter.parseObject(fields[0], keyClass); for (int i=1; i<fields.length; ++i) { double value = formatter.parseDouble(fields[i]); this.histograms.get(i-1).increment(key, value); } } } } catch (IOException ioe) { throw new PicardException("Could not read metrics from reader.", ioe); } }
diff --git a/commons/src/main/java/org/soluvas/commons/shell/ExtCommandSupport.java b/commons/src/main/java/org/soluvas/commons/shell/ExtCommandSupport.java index 76b5f101..eaefb9e2 100644 --- a/commons/src/main/java/org/soluvas/commons/shell/ExtCommandSupport.java +++ b/commons/src/main/java/org/soluvas/commons/shell/ExtCommandSupport.java @@ -1,34 +1,38 @@ package org.soluvas.commons.shell; import org.apache.felix.service.command.CommandSession; import org.apache.karaf.shell.console.AbstractAction; import org.soluvas.commons.ShellProgressMonitor; import org.soluvas.commons.impl.ShellProgressMonitorImpl; import org.soluvas.commons.locale.LocaleContext; import org.soluvas.commons.util.ThreadLocalProgress; /** * @author agus * */ public abstract class ExtCommandSupport extends AbstractAction { /** * Tenant for the currently executing {@link CommandSession}. * May be {@literal null} if no session is executing. */ // protected TenantRef tenant; /** * @todo Proper locale support. */ protected LocaleContext localeContext = new LocaleContext(); protected ShellProgressMonitor monitor = new ShellProgressMonitorImpl(); @Override public Object execute(CommandSession session) throws Exception { try (ThreadLocalProgress progress = new ThreadLocalProgress(monitor)) { return super.execute(session); + } finally { + // Subclasses usually forget to do this, so we'll do this for them :) + System.out.flush(); + System.err.flush(); } } }
true
true
public Object execute(CommandSession session) throws Exception { try (ThreadLocalProgress progress = new ThreadLocalProgress(monitor)) { return super.execute(session); } }
public Object execute(CommandSession session) throws Exception { try (ThreadLocalProgress progress = new ThreadLocalProgress(monitor)) { return super.execute(session); } finally { // Subclasses usually forget to do this, so we'll do this for them :) System.out.flush(); System.err.flush(); } }
diff --git a/src/java/org/apache/nutch/parse/ParseOutputFormat.java b/src/java/org/apache/nutch/parse/ParseOutputFormat.java index 9955ea01..f89896f7 100644 --- a/src/java/org/apache/nutch/parse/ParseOutputFormat.java +++ b/src/java/org/apache/nutch/parse/ParseOutputFormat.java @@ -1,170 +1,172 @@ /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.parse; // Commons Logging imports import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.*; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.fetcher.Fetcher; import org.apache.hadoop.fs.*; import org.apache.hadoop.mapred.*; import org.apache.nutch.scoring.ScoringFilterException; import org.apache.nutch.scoring.ScoringFilters; import org.apache.nutch.util.StringUtil; import org.apache.nutch.net.*; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import org.apache.hadoop.util.Progressable; /* Parse content in a segment. */ public class ParseOutputFormat implements OutputFormat { private static final Log LOG = LogFactory.getLog(ParseOutputFormat.class); private URLNormalizers urlNormalizers; private URLFilters filters; private ScoringFilters scfilters; public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException { if (fs.exists(new Path(job.getOutputPath(), CrawlDatum.PARSE_DIR_NAME))) throw new IOException("Segment already parsed!"); } public RecordWriter getRecordWriter(FileSystem fs, JobConf job, String name, Progressable progress) throws IOException { this.urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_OUTLINK); this.filters = new URLFilters(job); this.scfilters = new ScoringFilters(job); final float interval = job.getFloat("db.default.fetch.interval", 30f); final boolean ignoreExternalLinks = job.getBoolean("db.ignore.external.links", false); Path text = new Path(new Path(job.getOutputPath(), ParseText.DIR_NAME), name); Path data = new Path(new Path(job.getOutputPath(), ParseData.DIR_NAME), name); Path crawl = new Path(new Path(job.getOutputPath(), CrawlDatum.PARSE_DIR_NAME), name); final MapFile.Writer textOut = new MapFile.Writer(fs, text.toString(), UTF8.class, ParseText.class); final MapFile.Writer dataOut = new MapFile.Writer(fs, data.toString(), UTF8.class,ParseData.class,true); final SequenceFile.Writer crawlOut = new SequenceFile.Writer(fs, crawl, UTF8.class, CrawlDatum.class); return new RecordWriter() { public void write(WritableComparable key, Writable value) throws IOException { Parse parse = (Parse)value; String fromUrl = key.toString(); String fromHost = null; String toHost = null; textOut.append(key, new ParseText(parse.getText())); ParseData parseData = parse.getData(); // recover the signature prepared by Fetcher or ParseSegment String sig = parseData.getContentMeta().get(Fetcher.SIGNATURE_KEY); if (sig != null) { byte[] signature = StringUtil.fromHexString(sig); if (signature != null) { // append a CrawlDatum with a signature CrawlDatum d = new CrawlDatum(CrawlDatum.STATUS_SIGNATURE, 0.0f); d.setSignature(signature); crawlOut.append(key, d); } } // collect outlinks for subsequent db update Outlink[] links = parseData.getOutlinks(); if (ignoreExternalLinks) { try { fromHost = new URL(fromUrl).getHost().toLowerCase(); } catch (MalformedURLException e) { fromHost = null; } } else { fromHost = null; } String[] toUrls = new String[links.length]; int validCount = 0; for (int i = 0; i < links.length; i++) { String toUrl = links[i].getToUrl(); try { toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_OUTLINK); // normalize the url toUrl = filters.filter(toUrl); // filter the url } catch (Exception e) { toUrl = null; } + // ignore links to self (or anchors within the page) + if (fromUrl.equals(toUrl)) toUrl = null; if (toUrl != null) validCount++; toUrls[i] = toUrl; } CrawlDatum adjust = null; // compute score contributions and adjustment to the original score for (int i = 0; i < toUrls.length; i++) { if (toUrls[i] == null) continue; if (ignoreExternalLinks) { try { toHost = new URL(toUrls[i]).getHost().toLowerCase(); } catch (MalformedURLException e) { toHost = null; } if (toHost == null || !toHost.equals(fromHost)) { // external links continue; // skip it } } CrawlDatum target = new CrawlDatum(CrawlDatum.STATUS_LINKED, interval); UTF8 targetUrl = new UTF8(toUrls[i]); adjust = null; try { adjust = scfilters.distributeScoreToOutlink((UTF8)key, targetUrl, parseData, target, null, links.length, validCount); } catch (ScoringFilterException e) { if (LOG.isWarnEnabled()) { LOG.warn("Cannot distribute score from " + key + " to " + targetUrl + " - skipped (" + e.getMessage()); } continue; } crawlOut.append(targetUrl, target); if (adjust != null) crawlOut.append(key, adjust); } dataOut.append(key, parseData); } public void close(Reporter reporter) throws IOException { textOut.close(); dataOut.close(); crawlOut.close(); } }; } }
true
true
public RecordWriter getRecordWriter(FileSystem fs, JobConf job, String name, Progressable progress) throws IOException { this.urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_OUTLINK); this.filters = new URLFilters(job); this.scfilters = new ScoringFilters(job); final float interval = job.getFloat("db.default.fetch.interval", 30f); final boolean ignoreExternalLinks = job.getBoolean("db.ignore.external.links", false); Path text = new Path(new Path(job.getOutputPath(), ParseText.DIR_NAME), name); Path data = new Path(new Path(job.getOutputPath(), ParseData.DIR_NAME), name); Path crawl = new Path(new Path(job.getOutputPath(), CrawlDatum.PARSE_DIR_NAME), name); final MapFile.Writer textOut = new MapFile.Writer(fs, text.toString(), UTF8.class, ParseText.class); final MapFile.Writer dataOut = new MapFile.Writer(fs, data.toString(), UTF8.class,ParseData.class,true); final SequenceFile.Writer crawlOut = new SequenceFile.Writer(fs, crawl, UTF8.class, CrawlDatum.class); return new RecordWriter() { public void write(WritableComparable key, Writable value) throws IOException { Parse parse = (Parse)value; String fromUrl = key.toString(); String fromHost = null; String toHost = null; textOut.append(key, new ParseText(parse.getText())); ParseData parseData = parse.getData(); // recover the signature prepared by Fetcher or ParseSegment String sig = parseData.getContentMeta().get(Fetcher.SIGNATURE_KEY); if (sig != null) { byte[] signature = StringUtil.fromHexString(sig); if (signature != null) { // append a CrawlDatum with a signature CrawlDatum d = new CrawlDatum(CrawlDatum.STATUS_SIGNATURE, 0.0f); d.setSignature(signature); crawlOut.append(key, d); } } // collect outlinks for subsequent db update Outlink[] links = parseData.getOutlinks(); if (ignoreExternalLinks) { try { fromHost = new URL(fromUrl).getHost().toLowerCase(); } catch (MalformedURLException e) { fromHost = null; } } else { fromHost = null; } String[] toUrls = new String[links.length]; int validCount = 0; for (int i = 0; i < links.length; i++) { String toUrl = links[i].getToUrl(); try { toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_OUTLINK); // normalize the url toUrl = filters.filter(toUrl); // filter the url } catch (Exception e) { toUrl = null; } if (toUrl != null) validCount++; toUrls[i] = toUrl; } CrawlDatum adjust = null; // compute score contributions and adjustment to the original score for (int i = 0; i < toUrls.length; i++) { if (toUrls[i] == null) continue; if (ignoreExternalLinks) { try { toHost = new URL(toUrls[i]).getHost().toLowerCase(); } catch (MalformedURLException e) { toHost = null; } if (toHost == null || !toHost.equals(fromHost)) { // external links continue; // skip it } } CrawlDatum target = new CrawlDatum(CrawlDatum.STATUS_LINKED, interval); UTF8 targetUrl = new UTF8(toUrls[i]); adjust = null; try { adjust = scfilters.distributeScoreToOutlink((UTF8)key, targetUrl, parseData, target, null, links.length, validCount); } catch (ScoringFilterException e) { if (LOG.isWarnEnabled()) { LOG.warn("Cannot distribute score from " + key + " to " + targetUrl + " - skipped (" + e.getMessage()); } continue; } crawlOut.append(targetUrl, target); if (adjust != null) crawlOut.append(key, adjust); } dataOut.append(key, parseData); } public void close(Reporter reporter) throws IOException { textOut.close(); dataOut.close(); crawlOut.close(); } }; }
public RecordWriter getRecordWriter(FileSystem fs, JobConf job, String name, Progressable progress) throws IOException { this.urlNormalizers = new URLNormalizers(job, URLNormalizers.SCOPE_OUTLINK); this.filters = new URLFilters(job); this.scfilters = new ScoringFilters(job); final float interval = job.getFloat("db.default.fetch.interval", 30f); final boolean ignoreExternalLinks = job.getBoolean("db.ignore.external.links", false); Path text = new Path(new Path(job.getOutputPath(), ParseText.DIR_NAME), name); Path data = new Path(new Path(job.getOutputPath(), ParseData.DIR_NAME), name); Path crawl = new Path(new Path(job.getOutputPath(), CrawlDatum.PARSE_DIR_NAME), name); final MapFile.Writer textOut = new MapFile.Writer(fs, text.toString(), UTF8.class, ParseText.class); final MapFile.Writer dataOut = new MapFile.Writer(fs, data.toString(), UTF8.class,ParseData.class,true); final SequenceFile.Writer crawlOut = new SequenceFile.Writer(fs, crawl, UTF8.class, CrawlDatum.class); return new RecordWriter() { public void write(WritableComparable key, Writable value) throws IOException { Parse parse = (Parse)value; String fromUrl = key.toString(); String fromHost = null; String toHost = null; textOut.append(key, new ParseText(parse.getText())); ParseData parseData = parse.getData(); // recover the signature prepared by Fetcher or ParseSegment String sig = parseData.getContentMeta().get(Fetcher.SIGNATURE_KEY); if (sig != null) { byte[] signature = StringUtil.fromHexString(sig); if (signature != null) { // append a CrawlDatum with a signature CrawlDatum d = new CrawlDatum(CrawlDatum.STATUS_SIGNATURE, 0.0f); d.setSignature(signature); crawlOut.append(key, d); } } // collect outlinks for subsequent db update Outlink[] links = parseData.getOutlinks(); if (ignoreExternalLinks) { try { fromHost = new URL(fromUrl).getHost().toLowerCase(); } catch (MalformedURLException e) { fromHost = null; } } else { fromHost = null; } String[] toUrls = new String[links.length]; int validCount = 0; for (int i = 0; i < links.length; i++) { String toUrl = links[i].getToUrl(); try { toUrl = urlNormalizers.normalize(toUrl, URLNormalizers.SCOPE_OUTLINK); // normalize the url toUrl = filters.filter(toUrl); // filter the url } catch (Exception e) { toUrl = null; } // ignore links to self (or anchors within the page) if (fromUrl.equals(toUrl)) toUrl = null; if (toUrl != null) validCount++; toUrls[i] = toUrl; } CrawlDatum adjust = null; // compute score contributions and adjustment to the original score for (int i = 0; i < toUrls.length; i++) { if (toUrls[i] == null) continue; if (ignoreExternalLinks) { try { toHost = new URL(toUrls[i]).getHost().toLowerCase(); } catch (MalformedURLException e) { toHost = null; } if (toHost == null || !toHost.equals(fromHost)) { // external links continue; // skip it } } CrawlDatum target = new CrawlDatum(CrawlDatum.STATUS_LINKED, interval); UTF8 targetUrl = new UTF8(toUrls[i]); adjust = null; try { adjust = scfilters.distributeScoreToOutlink((UTF8)key, targetUrl, parseData, target, null, links.length, validCount); } catch (ScoringFilterException e) { if (LOG.isWarnEnabled()) { LOG.warn("Cannot distribute score from " + key + " to " + targetUrl + " - skipped (" + e.getMessage()); } continue; } crawlOut.append(targetUrl, target); if (adjust != null) crawlOut.append(key, adjust); } dataOut.append(key, parseData); } public void close(Reporter reporter) throws IOException { textOut.close(); dataOut.close(); crawlOut.close(); } }; }
diff --git a/modules/activiti-bpmn-converter/src/main/java/org/activiti/bpmn/converter/BpmnXMLConverter.java b/modules/activiti-bpmn-converter/src/main/java/org/activiti/bpmn/converter/BpmnXMLConverter.java index a65ba5595..f5245838f 100644 --- a/modules/activiti-bpmn-converter/src/main/java/org/activiti/bpmn/converter/BpmnXMLConverter.java +++ b/modules/activiti-bpmn-converter/src/main/java/org/activiti/bpmn/converter/BpmnXMLConverter.java @@ -1,555 +1,555 @@ /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.bpmn.converter; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.XMLConstants; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.activiti.bpmn.constants.BpmnXMLConstants; import org.activiti.bpmn.converter.alfresco.AlfrescoStartEventXMLConverter; import org.activiti.bpmn.converter.alfresco.AlfrescoUserTaskXMLConverter; import org.activiti.bpmn.converter.child.DocumentationParser; import org.activiti.bpmn.converter.child.ExecutionListenerParser; import org.activiti.bpmn.converter.child.IOSpecificationParser; import org.activiti.bpmn.converter.child.MultiInstanceParser; import org.activiti.bpmn.converter.export.ActivitiListenerExport; import org.activiti.bpmn.converter.export.BPMNDIExport; import org.activiti.bpmn.converter.export.DefinitionsRootExport; import org.activiti.bpmn.converter.export.MultiInstanceExport; import org.activiti.bpmn.converter.export.PoolExport; import org.activiti.bpmn.converter.export.ProcessExport; import org.activiti.bpmn.converter.export.SignalAndMessageDefinitionExport; import org.activiti.bpmn.converter.parser.BpmnEdgeParser; import org.activiti.bpmn.converter.parser.BpmnShapeParser; import org.activiti.bpmn.converter.parser.ImportParser; import org.activiti.bpmn.converter.parser.InterfaceParser; import org.activiti.bpmn.converter.parser.ItemDefinitionParser; import org.activiti.bpmn.converter.parser.LaneParser; import org.activiti.bpmn.converter.parser.MessageParser; import org.activiti.bpmn.converter.parser.PotentialStarterParser; import org.activiti.bpmn.converter.parser.ProcessParser; import org.activiti.bpmn.converter.parser.SignalParser; import org.activiti.bpmn.converter.parser.SubProcessParser; import org.activiti.bpmn.converter.util.InputStreamProvider; import org.activiti.bpmn.exceptions.XMLException; import org.activiti.bpmn.model.Activity; import org.activiti.bpmn.model.Artifact; import org.activiti.bpmn.model.BaseElement; import org.activiti.bpmn.model.BoundaryEvent; import org.activiti.bpmn.model.BpmnModel; import org.activiti.bpmn.model.EventSubProcess; import org.activiti.bpmn.model.FlowElement; import org.activiti.bpmn.model.FlowNode; import org.activiti.bpmn.model.Pool; import org.activiti.bpmn.model.Process; import org.activiti.bpmn.model.SequenceFlow; import org.activiti.bpmn.model.SubProcess; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; /** * @author Tijs Rademakers * @author Joram Barrez */ public class BpmnXMLConverter implements BpmnXMLConstants { protected static final Logger LOGGER = LoggerFactory.getLogger(BpmnXMLConverter.class); protected static final String BPMN_XSD = "org/activiti/impl/bpmn/parser/BPMN20.xsd"; protected static Map<String, Class<? extends BaseBpmnXMLConverter>> convertersToBpmnMap = new HashMap<String, Class<? extends BaseBpmnXMLConverter>>(); protected static Map<Class<? extends BaseElement>, Class<? extends BaseBpmnXMLConverter>> convertersToXMLMap = new HashMap<Class<? extends BaseElement>, Class<? extends BaseBpmnXMLConverter>>(); protected ClassLoader classloader; protected List<String> userTaskFormTypes; protected List<String> startEventFormTypes; static { // events addConverter(EndEventXMLConverter.getXMLType(), EndEventXMLConverter.getBpmnElementType(), EndEventXMLConverter.class); addConverter(StartEventXMLConverter.getXMLType(), StartEventXMLConverter.getBpmnElementType(), StartEventXMLConverter.class); // tasks addConverter(BusinessRuleTaskXMLConverter.getXMLType(), BusinessRuleTaskXMLConverter.getBpmnElementType(), BusinessRuleTaskXMLConverter.class); addConverter(ManualTaskXMLConverter.getXMLType(), ManualTaskXMLConverter.getBpmnElementType(), ManualTaskXMLConverter.class); addConverter(ReceiveTaskXMLConverter.getXMLType(), ReceiveTaskXMLConverter.getBpmnElementType(), ReceiveTaskXMLConverter.class); addConverter(ScriptTaskXMLConverter.getXMLType(), ScriptTaskXMLConverter.getBpmnElementType(), ScriptTaskXMLConverter.class); addConverter(ServiceTaskXMLConverter.getXMLType(), ServiceTaskXMLConverter.getBpmnElementType(), ServiceTaskXMLConverter.class); addConverter(SendTaskXMLConverter.getXMLType(), SendTaskXMLConverter.getBpmnElementType(), SendTaskXMLConverter.class); addConverter(UserTaskXMLConverter.getXMLType(), UserTaskXMLConverter.getBpmnElementType(), UserTaskXMLConverter.class); addConverter(TaskXMLConverter.getXMLType(), TaskXMLConverter.getBpmnElementType(), TaskXMLConverter.class); addConverter(CallActivityXMLConverter.getXMLType(), CallActivityXMLConverter.getBpmnElementType(), CallActivityXMLConverter.class); // gateways addConverter(EventGatewayXMLConverter.getXMLType(), EventGatewayXMLConverter.getBpmnElementType(), EventGatewayXMLConverter.class); addConverter(ExclusiveGatewayXMLConverter.getXMLType(), ExclusiveGatewayXMLConverter.getBpmnElementType(), ExclusiveGatewayXMLConverter.class); addConverter(InclusiveGatewayXMLConverter.getXMLType(), InclusiveGatewayXMLConverter.getBpmnElementType(), InclusiveGatewayXMLConverter.class); addConverter(ParallelGatewayXMLConverter.getXMLType(), ParallelGatewayXMLConverter.getBpmnElementType(), ParallelGatewayXMLConverter.class); // connectors addConverter(SequenceFlowXMLConverter.getXMLType(), SequenceFlowXMLConverter.getBpmnElementType(), SequenceFlowXMLConverter.class); // catch, throw and boundary event addConverter(CatchEventXMLConverter.getXMLType(), CatchEventXMLConverter.getBpmnElementType(), CatchEventXMLConverter.class); addConverter(ThrowEventXMLConverter.getXMLType(), ThrowEventXMLConverter.getBpmnElementType(), ThrowEventXMLConverter.class); addConverter(BoundaryEventXMLConverter.getXMLType(), BoundaryEventXMLConverter.getBpmnElementType(), BoundaryEventXMLConverter.class); // artifacts addConverter(TextAnnotationXMLConverter.getXMLType(), TextAnnotationXMLConverter.getBpmnElementType(), TextAnnotationXMLConverter.class); addConverter(AssociationXMLConverter.getXMLType(), AssociationXMLConverter.getBpmnElementType(), AssociationXMLConverter.class); // Alfresco types addConverter(AlfrescoStartEventXMLConverter.getXMLType(), AlfrescoStartEventXMLConverter.getBpmnElementType(), AlfrescoStartEventXMLConverter.class); addConverter(AlfrescoUserTaskXMLConverter.getXMLType(), AlfrescoUserTaskXMLConverter.getBpmnElementType(), AlfrescoUserTaskXMLConverter.class); } private static void addConverter(String elementName, Class<? extends BaseElement> elementClass, Class<? extends BaseBpmnXMLConverter> converter) { convertersToBpmnMap.put(elementName, converter); convertersToXMLMap.put(elementClass, converter); } public void setClassloader(ClassLoader classloader) { this.classloader = classloader; } public void setUserTaskFormTypes(List<String> userTaskFormTypes) { this.userTaskFormTypes = userTaskFormTypes; } public void setStartEventFormTypes(List<String> startEventFormTypes) { this.startEventFormTypes = startEventFormTypes; } public void validateModel(InputStreamProvider inputStreamProvider) throws Exception { Schema schema = createSchema(); Validator validator = schema.newValidator(); validator.validate(new StreamSource(inputStreamProvider.getInputStream())); } public void validateModel(XMLStreamReader xmlStreamReader) throws Exception { Schema schema = createSchema(); Validator validator = schema.newValidator(); validator.validate(new StAXSource(xmlStreamReader)); } protected Schema createSchema() throws SAXException { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null; if (classloader != null) { schema = factory.newSchema(classloader.getResource(BPMN_XSD)); } if (schema == null) { schema = factory.newSchema(BpmnXMLConverter.class.getClassLoader().getResource(BPMN_XSD)); } if (schema == null) { throw new XMLException("BPMN XSD could not be found"); } return schema; } public BpmnModel convertToBpmnModel(InputStreamProvider inputStreamProvider, boolean validateSchema, boolean enableSafeBpmnXml) { XMLInputFactory xif = XMLInputFactory.newInstance(); if (xif.isPropertySupported(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES)) { xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); } if (xif.isPropertySupported(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES)) { xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } if (xif.isPropertySupported(XMLInputFactory.SUPPORT_DTD)) { xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); } InputStreamReader in = null; try { in = new InputStreamReader(inputStreamProvider.getInputStream(), "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(in); try { if (validateSchema) { if (!enableSafeBpmnXml) { validateModel(inputStreamProvider); } else { validateModel(xtr); } // The input stream is closed after schema validation in = new InputStreamReader(inputStreamProvider.getInputStream(), "UTF-8"); xtr = xif.createXMLStreamReader(in); } } catch (Exception e) { throw new RuntimeException("Could not validate XML with BPMN 2.0 XSD", e); } // XML conversion return convertToBpmnModel(xtr); } catch (UnsupportedEncodingException e) { throw new RuntimeException("The bpmn 2.0 xml is not UTF8 encoded", e); } catch (XMLStreamException e) { throw new RuntimeException("Error while reading the BPMN 2.0 XML", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOGGER.info("Problem closing BPMN input stream", e); } } } } public BpmnModel convertToBpmnModel(XMLStreamReader xtr) { BpmnModel model = new BpmnModel(); try { Process activeProcess = null; List<SubProcess> activeSubProcessList = new ArrayList<SubProcess>(); while (xtr.hasNext()) { try { xtr.next(); } catch(Exception e) { LOGGER.error("Error reading XML document", e); throw new XMLException("Error reading XML", e); } if (xtr.isEndElement() && ELEMENT_SUBPROCESS.equals(xtr.getLocalName())) { activeSubProcessList.remove(activeSubProcessList.size() - 1); } if (xtr.isEndElement() && ELEMENT_TRANSACTION.equals(xtr.getLocalName())) { activeSubProcessList.remove(activeSubProcessList.size() - 1); } if (xtr.isStartElement() == false) continue; if (ELEMENT_DEFINITIONS.equals(xtr.getLocalName())) { model.setTargetNamespace(xtr.getAttributeValue(null, TARGET_NAMESPACE_ATTRIBUTE)); for (int i = 0; i < xtr.getNamespaceCount(); i++) { String prefix = xtr.getNamespacePrefix(i); if (prefix != null) { model.addNamespace(prefix, xtr.getNamespaceURI(i)); } } } else if (ELEMENT_SIGNAL.equals(xtr.getLocalName())) { new SignalParser().parse(xtr, model); } else if (ELEMENT_MESSAGE.equals(xtr.getLocalName())) { new MessageParser().parse(xtr, model); } else if (ELEMENT_ERROR.equals(xtr.getLocalName())) { if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_ID))) { model.addError(xtr.getAttributeValue(null, ATTRIBUTE_ID), xtr.getAttributeValue(null, ATTRIBUTE_ERROR_CODE)); } } else if (ELEMENT_IMPORT.equals(xtr.getLocalName())) { new ImportParser().parse(xtr, model); } else if (ELEMENT_ITEM_DEFINITION.equals(xtr.getLocalName())) { new ItemDefinitionParser().parse(xtr, model); } else if (ELEMENT_INTERFACE.equals(xtr.getLocalName())) { new InterfaceParser().parse(xtr, model); } else if (ELEMENT_IOSPECIFICATION.equals(xtr.getLocalName())) { new IOSpecificationParser().parseChildElement(xtr, activeProcess, model); } else if (ELEMENT_PARTICIPANT.equals(xtr.getLocalName())) { if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_ID))) { Pool pool = new Pool(); pool.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); pool.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME)); pool.setProcessRef(xtr.getAttributeValue(null, ATTRIBUTE_PROCESS_REF)); model.getPools().add(pool); } } else if (ELEMENT_PROCESS.equals(xtr.getLocalName())) { Process process = new ProcessParser().parse(xtr, model); if (process != null) { activeProcess = process; } } else if (ELEMENT_POTENTIAL_STARTER.equals(xtr.getLocalName())) { new PotentialStarterParser().parse(xtr, activeProcess); } else if (ELEMENT_LANE.equals(xtr.getLocalName())) { new LaneParser().parse(xtr, activeProcess); } else if (ELEMENT_DOCUMENTATION.equals(xtr.getLocalName())) { BaseElement parentElement = null; if(activeSubProcessList.size() > 0) { parentElement = activeSubProcessList.get(activeSubProcessList.size() - 1); } else if(activeProcess != null) { parentElement = activeProcess; } new DocumentationParser().parseChildElement(xtr, parentElement, model); } else if (ELEMENT_SUBPROCESS.equals(xtr.getLocalName())) { new SubProcessParser().parse(xtr, activeSubProcessList, activeProcess); } else if (ELEMENT_TRANSACTION.equals(xtr.getLocalName())) { new SubProcessParser().parse(xtr, activeSubProcessList, activeProcess); } else if (ELEMENT_DI_SHAPE.equals(xtr.getLocalName())) { new BpmnShapeParser().parse(xtr, model); } else if (ELEMENT_DI_EDGE.equals(xtr.getLocalName())) { new BpmnEdgeParser().parse(xtr, model); } else if (activeSubProcessList.size() == 0 && ELEMENT_EXECUTION_LISTENER.equals(xtr.getLocalName())) { new ExecutionListenerParser().parseChildElement(xtr, activeProcess, model); } else { if (activeSubProcessList.size() > 0 && ELEMENT_EXECUTION_LISTENER.equalsIgnoreCase(xtr.getLocalName())) { new ExecutionListenerParser().parseChildElement(xtr, activeSubProcessList.get(activeSubProcessList.size() - 1), model); } else if (activeSubProcessList.size() > 0 && ELEMENT_MULTIINSTANCE.equalsIgnoreCase(xtr.getLocalName())) { new MultiInstanceParser().parseChildElement(xtr, activeSubProcessList.get(activeSubProcessList.size() - 1), model); } else if (convertersToBpmnMap.containsKey(xtr.getLocalName())) { - if (activeProcess.isExecutable()) { + if (activeProcess != null && activeProcess.isExecutable()) { Class<? extends BaseBpmnXMLConverter> converterClass = convertersToBpmnMap.get(xtr.getLocalName()); BaseBpmnXMLConverter converter = converterClass.newInstance(); if (userTaskFormTypes != null && ELEMENT_TASK_USER.equals(xtr.getLocalName())) { UserTaskXMLConverter userTaskConverter = (UserTaskXMLConverter) converter; for (String formType : userTaskFormTypes) { userTaskConverter.addFormType(formType); } } else if (startEventFormTypes != null && ELEMENT_EVENT_START.equals(xtr.getLocalName())) { StartEventXMLConverter startEventConverter = (StartEventXMLConverter) converter; for (String formType : startEventFormTypes) { startEventConverter.addFormType(formType); } } converter.convertToBpmnModel(xtr, model, activeProcess, activeSubProcessList); } } } } for (Process process : model.getProcesses()) { processFlowElements(process.getFlowElements(), process); } } catch (Exception e) { LOGGER.error("Error processing BPMN document", e); throw new XMLException("Error processing BPMN document", e); } return model; } private void processFlowElements(Collection<FlowElement> flowElementList, BaseElement parentScope) { for (FlowElement flowElement : flowElementList) { if (flowElement instanceof SequenceFlow) { SequenceFlow sequenceFlow = (SequenceFlow) flowElement; FlowNode sourceNode = getFlowNodeFromScope(sequenceFlow.getSourceRef(), parentScope); if (sourceNode != null) { sourceNode.getOutgoingFlows().add(sequenceFlow); } FlowNode targetNode = getFlowNodeFromScope(sequenceFlow.getTargetRef(), parentScope); if (targetNode != null) { targetNode.getIncomingFlows().add(sequenceFlow); } } else if (flowElement instanceof BoundaryEvent) { BoundaryEvent boundaryEvent = (BoundaryEvent) flowElement; FlowElement attachedToElement = getFlowNodeFromScope(boundaryEvent.getAttachedToRefId(), parentScope); if(attachedToElement != null) { boundaryEvent.setAttachedToRef((Activity) attachedToElement); ((Activity) attachedToElement).getBoundaryEvents().add(boundaryEvent); } } else if(flowElement instanceof SubProcess) { SubProcess subProcess = (SubProcess) flowElement; processFlowElements(subProcess.getFlowElements(), subProcess); } } } private FlowNode getFlowNodeFromScope(String elementId, BaseElement scope) { FlowNode flowNode = null; if (StringUtils.isNotEmpty(elementId)) { if (scope instanceof Process) { flowNode = (FlowNode) ((Process) scope).getFlowElement(elementId); } else if (scope instanceof SubProcess) { flowNode = (FlowNode) ((SubProcess) scope).getFlowElement(elementId); } } return flowNode; } public byte[] convertToXML(BpmnModel model) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLOutputFactory xof = XMLOutputFactory.newInstance(); OutputStreamWriter out = new OutputStreamWriter(outputStream, "UTF-8"); XMLStreamWriter writer = xof.createXMLStreamWriter(out); XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer); DefinitionsRootExport.writeRootElement(model, xtw); SignalAndMessageDefinitionExport.writeSignalsAndMessages(model, xtw); PoolExport.writePools(model, xtw); for (Process process : model.getProcesses()) { if(process.getFlowElements().size() == 0 && process.getLanes().size() == 0) { // empty process, ignore it continue; } ProcessExport.writeProcess(process, xtw); for (FlowElement flowElement : process.getFlowElements()) { createXML(flowElement, model, xtw); } for (Artifact artifact : process.getArtifacts()) { createXML(artifact, model, xtw); } // end process element xtw.writeEndElement(); } BPMNDIExport.writeBPMNDI(model, xtw); // end definitions root element xtw.writeEndElement(); xtw.writeEndDocument(); xtw.flush(); outputStream.close(); xtw.close(); return outputStream.toByteArray(); } catch (Exception e) { LOGGER.error("Error writing BPMN XML", e); throw new XMLException("Error writing BPMN XML", e); } } private void createXML(FlowElement flowElement, BpmnModel model, XMLStreamWriter xtw) throws Exception { if (flowElement instanceof SubProcess) { SubProcess subProcess = (SubProcess) flowElement; xtw.writeStartElement(ELEMENT_SUBPROCESS); xtw.writeAttribute(ATTRIBUTE_ID, subProcess.getId()); if (StringUtils.isNotEmpty(subProcess.getName())) { xtw.writeAttribute(ATTRIBUTE_NAME, subProcess.getName()); } else { xtw.writeAttribute(ATTRIBUTE_NAME, "subProcess"); } if (subProcess instanceof EventSubProcess) { xtw.writeAttribute(ATTRIBUTE_TRIGGERED_BY, ATTRIBUTE_VALUE_TRUE); } if (StringUtils.isNotEmpty(subProcess.getDocumentation())) { xtw.writeStartElement(ELEMENT_DOCUMENTATION); xtw.writeCharacters(subProcess.getDocumentation()); xtw.writeEndElement(); } boolean wroteListener = ActivitiListenerExport.writeListeners(subProcess, false, xtw); if (wroteListener) { // closing extensions element xtw.writeEndElement(); } MultiInstanceExport.writeMultiInstance(subProcess, xtw); for (FlowElement subElement : subProcess.getFlowElements()) { createXML(subElement, model, xtw); } for (Artifact artifact : subProcess.getArtifacts()) { createXML(artifact, model, xtw); } xtw.writeEndElement(); } else { Class<? extends BaseBpmnXMLConverter> converter = convertersToXMLMap.get(flowElement.getClass()); if (converter == null) { throw new XMLException("No converter for " + flowElement.getClass() + " found"); } converter.newInstance().convertToXML(xtw, flowElement, model); } } private void createXML(Artifact artifact, BpmnModel model, XMLStreamWriter xtw) throws Exception { Class<? extends BaseBpmnXMLConverter> converter = convertersToXMLMap.get(artifact.getClass()); if (converter == null) { throw new XMLException("No converter for " + artifact.getClass() + " found"); } converter.newInstance().convertToXML(xtw, artifact, model); } }
true
true
public BpmnModel convertToBpmnModel(XMLStreamReader xtr) { BpmnModel model = new BpmnModel(); try { Process activeProcess = null; List<SubProcess> activeSubProcessList = new ArrayList<SubProcess>(); while (xtr.hasNext()) { try { xtr.next(); } catch(Exception e) { LOGGER.error("Error reading XML document", e); throw new XMLException("Error reading XML", e); } if (xtr.isEndElement() && ELEMENT_SUBPROCESS.equals(xtr.getLocalName())) { activeSubProcessList.remove(activeSubProcessList.size() - 1); } if (xtr.isEndElement() && ELEMENT_TRANSACTION.equals(xtr.getLocalName())) { activeSubProcessList.remove(activeSubProcessList.size() - 1); } if (xtr.isStartElement() == false) continue; if (ELEMENT_DEFINITIONS.equals(xtr.getLocalName())) { model.setTargetNamespace(xtr.getAttributeValue(null, TARGET_NAMESPACE_ATTRIBUTE)); for (int i = 0; i < xtr.getNamespaceCount(); i++) { String prefix = xtr.getNamespacePrefix(i); if (prefix != null) { model.addNamespace(prefix, xtr.getNamespaceURI(i)); } } } else if (ELEMENT_SIGNAL.equals(xtr.getLocalName())) { new SignalParser().parse(xtr, model); } else if (ELEMENT_MESSAGE.equals(xtr.getLocalName())) { new MessageParser().parse(xtr, model); } else if (ELEMENT_ERROR.equals(xtr.getLocalName())) { if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_ID))) { model.addError(xtr.getAttributeValue(null, ATTRIBUTE_ID), xtr.getAttributeValue(null, ATTRIBUTE_ERROR_CODE)); } } else if (ELEMENT_IMPORT.equals(xtr.getLocalName())) { new ImportParser().parse(xtr, model); } else if (ELEMENT_ITEM_DEFINITION.equals(xtr.getLocalName())) { new ItemDefinitionParser().parse(xtr, model); } else if (ELEMENT_INTERFACE.equals(xtr.getLocalName())) { new InterfaceParser().parse(xtr, model); } else if (ELEMENT_IOSPECIFICATION.equals(xtr.getLocalName())) { new IOSpecificationParser().parseChildElement(xtr, activeProcess, model); } else if (ELEMENT_PARTICIPANT.equals(xtr.getLocalName())) { if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_ID))) { Pool pool = new Pool(); pool.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); pool.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME)); pool.setProcessRef(xtr.getAttributeValue(null, ATTRIBUTE_PROCESS_REF)); model.getPools().add(pool); } } else if (ELEMENT_PROCESS.equals(xtr.getLocalName())) { Process process = new ProcessParser().parse(xtr, model); if (process != null) { activeProcess = process; } } else if (ELEMENT_POTENTIAL_STARTER.equals(xtr.getLocalName())) { new PotentialStarterParser().parse(xtr, activeProcess); } else if (ELEMENT_LANE.equals(xtr.getLocalName())) { new LaneParser().parse(xtr, activeProcess); } else if (ELEMENT_DOCUMENTATION.equals(xtr.getLocalName())) { BaseElement parentElement = null; if(activeSubProcessList.size() > 0) { parentElement = activeSubProcessList.get(activeSubProcessList.size() - 1); } else if(activeProcess != null) { parentElement = activeProcess; } new DocumentationParser().parseChildElement(xtr, parentElement, model); } else if (ELEMENT_SUBPROCESS.equals(xtr.getLocalName())) { new SubProcessParser().parse(xtr, activeSubProcessList, activeProcess); } else if (ELEMENT_TRANSACTION.equals(xtr.getLocalName())) { new SubProcessParser().parse(xtr, activeSubProcessList, activeProcess); } else if (ELEMENT_DI_SHAPE.equals(xtr.getLocalName())) { new BpmnShapeParser().parse(xtr, model); } else if (ELEMENT_DI_EDGE.equals(xtr.getLocalName())) { new BpmnEdgeParser().parse(xtr, model); } else if (activeSubProcessList.size() == 0 && ELEMENT_EXECUTION_LISTENER.equals(xtr.getLocalName())) { new ExecutionListenerParser().parseChildElement(xtr, activeProcess, model); } else { if (activeSubProcessList.size() > 0 && ELEMENT_EXECUTION_LISTENER.equalsIgnoreCase(xtr.getLocalName())) { new ExecutionListenerParser().parseChildElement(xtr, activeSubProcessList.get(activeSubProcessList.size() - 1), model); } else if (activeSubProcessList.size() > 0 && ELEMENT_MULTIINSTANCE.equalsIgnoreCase(xtr.getLocalName())) { new MultiInstanceParser().parseChildElement(xtr, activeSubProcessList.get(activeSubProcessList.size() - 1), model); } else if (convertersToBpmnMap.containsKey(xtr.getLocalName())) { if (activeProcess.isExecutable()) { Class<? extends BaseBpmnXMLConverter> converterClass = convertersToBpmnMap.get(xtr.getLocalName()); BaseBpmnXMLConverter converter = converterClass.newInstance(); if (userTaskFormTypes != null && ELEMENT_TASK_USER.equals(xtr.getLocalName())) { UserTaskXMLConverter userTaskConverter = (UserTaskXMLConverter) converter; for (String formType : userTaskFormTypes) { userTaskConverter.addFormType(formType); } } else if (startEventFormTypes != null && ELEMENT_EVENT_START.equals(xtr.getLocalName())) { StartEventXMLConverter startEventConverter = (StartEventXMLConverter) converter; for (String formType : startEventFormTypes) { startEventConverter.addFormType(formType); } } converter.convertToBpmnModel(xtr, model, activeProcess, activeSubProcessList); } } } } for (Process process : model.getProcesses()) { processFlowElements(process.getFlowElements(), process); } } catch (Exception e) { LOGGER.error("Error processing BPMN document", e); throw new XMLException("Error processing BPMN document", e); } return model; }
public BpmnModel convertToBpmnModel(XMLStreamReader xtr) { BpmnModel model = new BpmnModel(); try { Process activeProcess = null; List<SubProcess> activeSubProcessList = new ArrayList<SubProcess>(); while (xtr.hasNext()) { try { xtr.next(); } catch(Exception e) { LOGGER.error("Error reading XML document", e); throw new XMLException("Error reading XML", e); } if (xtr.isEndElement() && ELEMENT_SUBPROCESS.equals(xtr.getLocalName())) { activeSubProcessList.remove(activeSubProcessList.size() - 1); } if (xtr.isEndElement() && ELEMENT_TRANSACTION.equals(xtr.getLocalName())) { activeSubProcessList.remove(activeSubProcessList.size() - 1); } if (xtr.isStartElement() == false) continue; if (ELEMENT_DEFINITIONS.equals(xtr.getLocalName())) { model.setTargetNamespace(xtr.getAttributeValue(null, TARGET_NAMESPACE_ATTRIBUTE)); for (int i = 0; i < xtr.getNamespaceCount(); i++) { String prefix = xtr.getNamespacePrefix(i); if (prefix != null) { model.addNamespace(prefix, xtr.getNamespaceURI(i)); } } } else if (ELEMENT_SIGNAL.equals(xtr.getLocalName())) { new SignalParser().parse(xtr, model); } else if (ELEMENT_MESSAGE.equals(xtr.getLocalName())) { new MessageParser().parse(xtr, model); } else if (ELEMENT_ERROR.equals(xtr.getLocalName())) { if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_ID))) { model.addError(xtr.getAttributeValue(null, ATTRIBUTE_ID), xtr.getAttributeValue(null, ATTRIBUTE_ERROR_CODE)); } } else if (ELEMENT_IMPORT.equals(xtr.getLocalName())) { new ImportParser().parse(xtr, model); } else if (ELEMENT_ITEM_DEFINITION.equals(xtr.getLocalName())) { new ItemDefinitionParser().parse(xtr, model); } else if (ELEMENT_INTERFACE.equals(xtr.getLocalName())) { new InterfaceParser().parse(xtr, model); } else if (ELEMENT_IOSPECIFICATION.equals(xtr.getLocalName())) { new IOSpecificationParser().parseChildElement(xtr, activeProcess, model); } else if (ELEMENT_PARTICIPANT.equals(xtr.getLocalName())) { if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_ID))) { Pool pool = new Pool(); pool.setId(xtr.getAttributeValue(null, ATTRIBUTE_ID)); pool.setName(xtr.getAttributeValue(null, ATTRIBUTE_NAME)); pool.setProcessRef(xtr.getAttributeValue(null, ATTRIBUTE_PROCESS_REF)); model.getPools().add(pool); } } else if (ELEMENT_PROCESS.equals(xtr.getLocalName())) { Process process = new ProcessParser().parse(xtr, model); if (process != null) { activeProcess = process; } } else if (ELEMENT_POTENTIAL_STARTER.equals(xtr.getLocalName())) { new PotentialStarterParser().parse(xtr, activeProcess); } else if (ELEMENT_LANE.equals(xtr.getLocalName())) { new LaneParser().parse(xtr, activeProcess); } else if (ELEMENT_DOCUMENTATION.equals(xtr.getLocalName())) { BaseElement parentElement = null; if(activeSubProcessList.size() > 0) { parentElement = activeSubProcessList.get(activeSubProcessList.size() - 1); } else if(activeProcess != null) { parentElement = activeProcess; } new DocumentationParser().parseChildElement(xtr, parentElement, model); } else if (ELEMENT_SUBPROCESS.equals(xtr.getLocalName())) { new SubProcessParser().parse(xtr, activeSubProcessList, activeProcess); } else if (ELEMENT_TRANSACTION.equals(xtr.getLocalName())) { new SubProcessParser().parse(xtr, activeSubProcessList, activeProcess); } else if (ELEMENT_DI_SHAPE.equals(xtr.getLocalName())) { new BpmnShapeParser().parse(xtr, model); } else if (ELEMENT_DI_EDGE.equals(xtr.getLocalName())) { new BpmnEdgeParser().parse(xtr, model); } else if (activeSubProcessList.size() == 0 && ELEMENT_EXECUTION_LISTENER.equals(xtr.getLocalName())) { new ExecutionListenerParser().parseChildElement(xtr, activeProcess, model); } else { if (activeSubProcessList.size() > 0 && ELEMENT_EXECUTION_LISTENER.equalsIgnoreCase(xtr.getLocalName())) { new ExecutionListenerParser().parseChildElement(xtr, activeSubProcessList.get(activeSubProcessList.size() - 1), model); } else if (activeSubProcessList.size() > 0 && ELEMENT_MULTIINSTANCE.equalsIgnoreCase(xtr.getLocalName())) { new MultiInstanceParser().parseChildElement(xtr, activeSubProcessList.get(activeSubProcessList.size() - 1), model); } else if (convertersToBpmnMap.containsKey(xtr.getLocalName())) { if (activeProcess != null && activeProcess.isExecutable()) { Class<? extends BaseBpmnXMLConverter> converterClass = convertersToBpmnMap.get(xtr.getLocalName()); BaseBpmnXMLConverter converter = converterClass.newInstance(); if (userTaskFormTypes != null && ELEMENT_TASK_USER.equals(xtr.getLocalName())) { UserTaskXMLConverter userTaskConverter = (UserTaskXMLConverter) converter; for (String formType : userTaskFormTypes) { userTaskConverter.addFormType(formType); } } else if (startEventFormTypes != null && ELEMENT_EVENT_START.equals(xtr.getLocalName())) { StartEventXMLConverter startEventConverter = (StartEventXMLConverter) converter; for (String formType : startEventFormTypes) { startEventConverter.addFormType(formType); } } converter.convertToBpmnModel(xtr, model, activeProcess, activeSubProcessList); } } } } for (Process process : model.getProcesses()) { processFlowElements(process.getFlowElements(), process); } } catch (Exception e) { LOGGER.error("Error processing BPMN document", e); throw new XMLException("Error processing BPMN document", e); } return model; }
diff --git a/src/org/proofpad/DoubleCheckResult.java b/src/org/proofpad/DoubleCheckResult.java index f4ca48c..d283e3c 100755 --- a/src/org/proofpad/DoubleCheckResult.java +++ b/src/org/proofpad/DoubleCheckResult.java @@ -1,96 +1,97 @@ package org.proofpad; import java.awt.Color; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JToggleButton; import javax.swing.UIManager; public class DoubleCheckResult extends JPanel { private static final long serialVersionUID = -2822280272207904268L; final static Icon openIcon = (Icon) UIManager.get("Tree.expandedIcon"); final static Icon closedIcon = (Icon) UIManager.get("Tree.collapsedIcon"); public DoubleCheckResult(String output) { setBackground(Color.WHITE); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); String[] lines = output.split("\n"); ArrayList<String> failures = new ArrayList<String>(); ArrayList<String> successes = new ArrayList<String>(); for (int i = 1; i < lines.length; i++) { String header = lines[i]; if (header.isEmpty()) break; StringBuilder sb = new StringBuilder(); i++; + if (i >= lines.length) break; String line = lines[i]; do { sb.append(line); sb.append('\n'); i++; if (i >= lines.length) break; line = lines[i]; } while (line.startsWith(" ")); i--; if (header.startsWith("Failure")) { failures.add(sb.toString()); } else { successes.add(sb.toString()); } } JToggleButton showHideFailures = new JToggleButton("Failed runs", true); JToggleButton showHideSuccesses = new JToggleButton("Successful runs", false); JPanel failurePanel = new JPanel(); failurePanel.setLayout(new BoxLayout(failurePanel, BoxLayout.Y_AXIS)); failurePanel.setBackground(Color.WHITE); JPanel successPanel = new JPanel(); successPanel.setLayout(new BoxLayout(successPanel, BoxLayout.Y_AXIS)); successPanel.setBackground(Color.WHITE); successPanel.setVisible(false); addCases(failures, failurePanel); linkToggleWithPanel(showHideFailures, failurePanel); addCases(successes, successPanel); linkToggleWithPanel(showHideSuccesses, successPanel); add(showHideFailures); add(failurePanel); add(showHideSuccesses); add(successPanel); } private static void addCases(ArrayList<String> cases, JPanel casePanel) { for (String caseStr : cases) { JTextArea caseComp = new JTextArea(caseStr); caseComp.setFont(Prefs.font.get()); caseComp.setEditable(false); caseComp.setAlignmentX(LEFT_ALIGNMENT); casePanel.add(caseComp); } } private static void linkToggleWithPanel(final JToggleButton b, final JPanel p) { p.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0)); b.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); b.setIcon(b.isSelected() ? openIcon : closedIcon); b.setFont(b.getFont().deriveFont(14f)); b.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { p.setVisible(true); b.setIcon(openIcon); } else { p.setVisible(false); b.setIcon(closedIcon); } } }); } }
true
true
public DoubleCheckResult(String output) { setBackground(Color.WHITE); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); String[] lines = output.split("\n"); ArrayList<String> failures = new ArrayList<String>(); ArrayList<String> successes = new ArrayList<String>(); for (int i = 1; i < lines.length; i++) { String header = lines[i]; if (header.isEmpty()) break; StringBuilder sb = new StringBuilder(); i++; String line = lines[i]; do { sb.append(line); sb.append('\n'); i++; if (i >= lines.length) break; line = lines[i]; } while (line.startsWith(" ")); i--; if (header.startsWith("Failure")) { failures.add(sb.toString()); } else { successes.add(sb.toString()); } } JToggleButton showHideFailures = new JToggleButton("Failed runs", true); JToggleButton showHideSuccesses = new JToggleButton("Successful runs", false); JPanel failurePanel = new JPanel(); failurePanel.setLayout(new BoxLayout(failurePanel, BoxLayout.Y_AXIS)); failurePanel.setBackground(Color.WHITE); JPanel successPanel = new JPanel(); successPanel.setLayout(new BoxLayout(successPanel, BoxLayout.Y_AXIS)); successPanel.setBackground(Color.WHITE); successPanel.setVisible(false); addCases(failures, failurePanel); linkToggleWithPanel(showHideFailures, failurePanel); addCases(successes, successPanel); linkToggleWithPanel(showHideSuccesses, successPanel); add(showHideFailures); add(failurePanel); add(showHideSuccesses); add(successPanel); }
public DoubleCheckResult(String output) { setBackground(Color.WHITE); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); String[] lines = output.split("\n"); ArrayList<String> failures = new ArrayList<String>(); ArrayList<String> successes = new ArrayList<String>(); for (int i = 1; i < lines.length; i++) { String header = lines[i]; if (header.isEmpty()) break; StringBuilder sb = new StringBuilder(); i++; if (i >= lines.length) break; String line = lines[i]; do { sb.append(line); sb.append('\n'); i++; if (i >= lines.length) break; line = lines[i]; } while (line.startsWith(" ")); i--; if (header.startsWith("Failure")) { failures.add(sb.toString()); } else { successes.add(sb.toString()); } } JToggleButton showHideFailures = new JToggleButton("Failed runs", true); JToggleButton showHideSuccesses = new JToggleButton("Successful runs", false); JPanel failurePanel = new JPanel(); failurePanel.setLayout(new BoxLayout(failurePanel, BoxLayout.Y_AXIS)); failurePanel.setBackground(Color.WHITE); JPanel successPanel = new JPanel(); successPanel.setLayout(new BoxLayout(successPanel, BoxLayout.Y_AXIS)); successPanel.setBackground(Color.WHITE); successPanel.setVisible(false); addCases(failures, failurePanel); linkToggleWithPanel(showHideFailures, failurePanel); addCases(successes, successPanel); linkToggleWithPanel(showHideSuccesses, successPanel); add(showHideFailures); add(failurePanel); add(showHideSuccesses); add(successPanel); }
diff --git a/src/gutenberg/workers/Vault.java b/src/gutenberg/workers/Vault.java index 66cf826..4ee9eba 100644 --- a/src/gutenberg/workers/Vault.java +++ b/src/gutenberg/workers/Vault.java @@ -1,98 +1,98 @@ package gutenberg.workers; import gutenberg.blocs.ManifestType; import java.io.ByteArrayOutputStream; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; public class Vault { public Vault(Config config) { VAULT = config.getPath(Resource.vault); SHARED = config.getPath(Resource.shared); } public Vault() throws Exception { Config config = new Config(); VAULT = config.getPath(Resource.vault); SHARED = config.getPath(Resource.shared); } /** * @param id - question id * @param filter - type of content e.g. "tex", "gnuplot" etc. * @return returns file contents for given id * @throws Exception */ public String[] getContent(String id, String filter) throws Exception { System.out.println("[vault] : Looking inside " + VAULT + "/" + id); File directory = new File(VAULT + "/" + id); File[] files = directory.listFiles(new NameFilter(filter)); String[] contents = new String[files.length]; for (int i = 0; i < files.length; i++) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Files.copy(files[i].toPath(), baos); contents[i] = baos.toString(); } return contents; } /** * @param id - question id * @param filter - type of content e.g. "tex", "gnuplot" etc. * @return Files * @throws Exception */ public File[] getFiles(String id, String filter) throws Exception { File directory = new File(VAULT + "/" + id); return directory.listFiles(new NameFilter(filter)); } public File[] getFiles(String[] id, String filter) throws Exception { ArrayList<File> fileSet = new ArrayList<File>(); File[] files = null; for (int i = 0; i < id.length; i++) { files = getFiles(id[i], filter); for (int j = 0; j < files.length; j++) { fileSet.add(files[j]); } } return fileSet.toArray(new File[0]); } /** * Creates a question in the Vault * * @param quizMasterId - id of person creating question * @return Manifest * @throws Exception */ public ManifestType createQuestion(String quizMasterId) throws Exception { String hexTimestamp = Long.toString(System.currentTimeMillis(), Character.MAX_RADIX); String dirName = quizMasterId + "-" + hexTimestamp.substring(0, 3) + "-" + hexTimestamp.substring(3); Path questionDir = new File(VAULT).toPath().resolve(dirName); Files.createDirectory(questionDir); Path shared = new File(SHARED).toPath(); Files.copy(shared.resolve(texFile), questionDir.resolve(texFile)); Files.copy(shared.resolve(plotFile), questionDir.resolve(plotFile)); - Files.createSymbolicLink(shared.resolve(makeFile), questionDir.resolve(makeFile)); + Files.createSymbolicLink(questionDir.resolve(makeFile), shared.resolve(makeFile)); ManifestType manifest = new ManifestType(); manifest.setRoot(questionDir.toString()); return manifest; } public String getPath() throws Exception { return this.VAULT; } private String VAULT, SHARED; private final String texFile = "question.tex", plotFile = "figure.gnuplot", makeFile = "individual.mk"; }
true
true
public ManifestType createQuestion(String quizMasterId) throws Exception { String hexTimestamp = Long.toString(System.currentTimeMillis(), Character.MAX_RADIX); String dirName = quizMasterId + "-" + hexTimestamp.substring(0, 3) + "-" + hexTimestamp.substring(3); Path questionDir = new File(VAULT).toPath().resolve(dirName); Files.createDirectory(questionDir); Path shared = new File(SHARED).toPath(); Files.copy(shared.resolve(texFile), questionDir.resolve(texFile)); Files.copy(shared.resolve(plotFile), questionDir.resolve(plotFile)); Files.createSymbolicLink(shared.resolve(makeFile), questionDir.resolve(makeFile)); ManifestType manifest = new ManifestType(); manifest.setRoot(questionDir.toString()); return manifest; }
public ManifestType createQuestion(String quizMasterId) throws Exception { String hexTimestamp = Long.toString(System.currentTimeMillis(), Character.MAX_RADIX); String dirName = quizMasterId + "-" + hexTimestamp.substring(0, 3) + "-" + hexTimestamp.substring(3); Path questionDir = new File(VAULT).toPath().resolve(dirName); Files.createDirectory(questionDir); Path shared = new File(SHARED).toPath(); Files.copy(shared.resolve(texFile), questionDir.resolve(texFile)); Files.copy(shared.resolve(plotFile), questionDir.resolve(plotFile)); Files.createSymbolicLink(questionDir.resolve(makeFile), shared.resolve(makeFile)); ManifestType manifest = new ManifestType(); manifest.setRoot(questionDir.toString()); return manifest; }
diff --git a/src/main/java/emcshop/gui/lib/ClickableLabel.java b/src/main/java/emcshop/gui/lib/ClickableLabel.java index f5e5fb9..8692ff0 100644 --- a/src/main/java/emcshop/gui/lib/ClickableLabel.java +++ b/src/main/java/emcshop/gui/lib/ClickableLabel.java @@ -1,92 +1,97 @@ package emcshop.gui.lib; import java.awt.Cursor; import java.awt.Desktop; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.net.URI; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Icon; import javax.swing.JLabel; /** * A label that, when clicked, will open a browser window and load a webpage. * @author Michael Angstadt */ @SuppressWarnings("serial") public class ClickableLabel extends JLabel implements MouseListener { private static final Logger logger = Logger.getLogger(ClickableLabel.class.getName()); private static final Desktop desktop; static { Desktop d = null; if (Desktop.isDesktopSupported()) { d = Desktop.getDesktop(); if (d != null && !d.isSupported(Desktop.Action.BROWSE)) { d = null; } } desktop = d; } private URI uri; /** * @param image the label image * @param url the webpage URL */ public ClickableLabel(Icon image, String url) { super(image); init(url); } /** * @param text the label text * @param url the webpage URL */ public ClickableLabel(String text, String url) { super(text); init(url); } private void init(String url) { - uri = URI.create(url); + try { + uri = URI.create(url); + } catch (IllegalArgumentException e) { + logger.log(Level.SEVERE, "Bad URI, cannot make label clickable.", e); + return; + } if (desktop != null) { //only set these things if the user's computer supports opening a browser window setCursor(new Cursor(Cursor.HAND_CURSOR)); addMouseListener(this); } } @Override public void mouseClicked(MouseEvent arg0) { try { desktop.browse(uri); } catch (IOException e) { logger.log(Level.WARNING, "Problem opening webpage.", e); } } @Override public void mouseEntered(MouseEvent e) { //empty } @Override public void mouseExited(MouseEvent e) { //empty } @Override public void mousePressed(MouseEvent e) { //empty } @Override public void mouseReleased(MouseEvent e) { //empty } }
true
true
private void init(String url) { uri = URI.create(url); if (desktop != null) { //only set these things if the user's computer supports opening a browser window setCursor(new Cursor(Cursor.HAND_CURSOR)); addMouseListener(this); } }
private void init(String url) { try { uri = URI.create(url); } catch (IllegalArgumentException e) { logger.log(Level.SEVERE, "Bad URI, cannot make label clickable.", e); return; } if (desktop != null) { //only set these things if the user's computer supports opening a browser window setCursor(new Cursor(Cursor.HAND_CURSOR)); addMouseListener(this); } }
diff --git a/src/de/uni_potsdam/hpi/openmensa/RetrieveFeedTask.java b/src/de/uni_potsdam/hpi/openmensa/RetrieveFeedTask.java index 23d5704..d359339 100644 --- a/src/de/uni_potsdam/hpi/openmensa/RetrieveFeedTask.java +++ b/src/de/uni_potsdam/hpi/openmensa/RetrieveFeedTask.java @@ -1,145 +1,145 @@ package de.uni_potsdam.hpi.openmensa; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.util.Log; import com.google.gson.Gson; /** * An abstract feed fetcher. Override the parseFromJSON and * onPostExecuteFinished methods in your concrete implementation. * * @author dominik */ public abstract class RetrieveFeedTask extends AsyncTask<String, Integer, Integer> { private Exception exception; private ProgressDialog dialog; private Builder builder; protected Context context; protected Gson gson = new Gson(); protected String name = ""; public static final String TAG = MainActivity.TAG; public static final Boolean LOGV = MainActivity.LOGV; private final int DEFAULT_BUFFER_SIZE = 1024; protected String fetchedJSON; public RetrieveFeedTask(Context context) { // progress dialog dialog = new ProgressDialog(context); dialog.setTitle("Fetching ..."); if (name.length() > 0) { dialog.setMessage(String.format("Fetching the %s", name)); } dialog.setIndeterminate(false); dialog.setMax(100); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // error dialog that may be needed builder = new AlertDialog.Builder(context) .setNegativeButton("Okay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); ; } @Override protected void onPreExecute() { super.onPreExecute(); dialog.show(); } protected abstract void parseFromJSON(); protected Integer doInBackground(String... urls) { for (String url : urls) { try { URL feed = new URL(url); URLConnection urlConnection = feed.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( urlConnection.getInputStream())); // urlConnection.connect(); StringBuilder builder = new StringBuilder(); long fileLength = urlConnection.getContentLength(); long total = 0; int count; // content length is sometimes not sent if (fileLength < 0) { dialog.setIndeterminate(true); } else { dialog.setMax((int) fileLength); } char buf[] = new char[DEFAULT_BUFFER_SIZE]; while ((count = in.read(buf, 0, DEFAULT_BUFFER_SIZE)) > 0) { total += count; // publishing the progress.... - publishProgress((int) (fileLength)); + publishProgress((int) (total)); builder.append(buf, 0, count); } handleJson(builder.toString()); } catch (Exception ex) { this.exception = ex; } } return urls.length; } private void handleJson(String string) { fetchedJSON = string; parseFromJSON(); } protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); dialog.setProgress(progress[0]); } protected void onPostExecute(Integer urlsCount) { if (this.exception != null) { Log.w(TAG, "Exception: " + exception.getMessage()); if (LOGV) { Log.d(TAG, Log.getStackTraceString(exception)); } showErrorMessage(this.exception); } else { onPostExecuteFinished(); } if (dialog.isShowing()) { dialog.dismiss(); } } protected abstract void onPostExecuteFinished(); private void showErrorMessage(Exception ex) { builder.setTitle(ex.getClass().getName()); builder.setMessage(ex.toString()); builder.show(); } public String getFetchedJSON() { return fetchedJSON; } }
true
true
protected Integer doInBackground(String... urls) { for (String url : urls) { try { URL feed = new URL(url); URLConnection urlConnection = feed.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( urlConnection.getInputStream())); // urlConnection.connect(); StringBuilder builder = new StringBuilder(); long fileLength = urlConnection.getContentLength(); long total = 0; int count; // content length is sometimes not sent if (fileLength < 0) { dialog.setIndeterminate(true); } else { dialog.setMax((int) fileLength); } char buf[] = new char[DEFAULT_BUFFER_SIZE]; while ((count = in.read(buf, 0, DEFAULT_BUFFER_SIZE)) > 0) { total += count; // publishing the progress.... publishProgress((int) (fileLength)); builder.append(buf, 0, count); } handleJson(builder.toString()); } catch (Exception ex) { this.exception = ex; } } return urls.length; }
protected Integer doInBackground(String... urls) { for (String url : urls) { try { URL feed = new URL(url); URLConnection urlConnection = feed.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( urlConnection.getInputStream())); // urlConnection.connect(); StringBuilder builder = new StringBuilder(); long fileLength = urlConnection.getContentLength(); long total = 0; int count; // content length is sometimes not sent if (fileLength < 0) { dialog.setIndeterminate(true); } else { dialog.setMax((int) fileLength); } char buf[] = new char[DEFAULT_BUFFER_SIZE]; while ((count = in.read(buf, 0, DEFAULT_BUFFER_SIZE)) > 0) { total += count; // publishing the progress.... publishProgress((int) (total)); builder.append(buf, 0, count); } handleJson(builder.toString()); } catch (Exception ex) { this.exception = ex; } } return urls.length; }
diff --git a/modules/compute/org/molgenis/compute/commandline/WorkflowGeneratorCommandLine.java b/modules/compute/org/molgenis/compute/commandline/WorkflowGeneratorCommandLine.java index fbdd92469..cffe11f30 100644 --- a/modules/compute/org/molgenis/compute/commandline/WorkflowGeneratorCommandLine.java +++ b/modules/compute/org/molgenis/compute/commandline/WorkflowGeneratorCommandLine.java @@ -1,518 +1,518 @@ package org.molgenis.compute.commandline; import org.molgenis.compute.ComputeJob; import org.molgenis.compute.ComputeParameter; import org.molgenis.compute.ComputeProtocol; import org.molgenis.compute.pipelinemodel.FileToSaveRemotely; import org.molgenis.compute.pipelinemodel.Pipeline; import org.molgenis.compute.pipelinemodel.Script; import org.molgenis.compute.pipelinemodel.Step; import org.molgenis.compute.scriptserver.MCF; import org.molgenis.compute.ui.DatabaseUpdater; import org.molgenis.compute.workflowgenerator.ParameterWeaver; import org.molgenis.framework.db.Database; import org.molgenis.protocol.Workflow; import org.molgenis.protocol.WorkflowElement; import org.molgenis.protocol.WorkflowElementParameter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by IntelliJ IDEA. * User: georgebyelas * Date: 18/10/2011 * Time: 10:43 * To change this template use File | Settings | File Templates. */ public class WorkflowGeneratorCommandLine { private static final String INTERPRETER_BASH = "bash"; private static final String INTERPRETER_R = "R"; private static final String INTERPRETER_JDL = "jdl"; private boolean flagJustGenerate = false; private static final String LOG = "log";// reserved word for logging feature type used in ComputeFeature private static final String DATE_FORMAT_NOW = "yyyy-MM-dd-HH-mm-ss"; private SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); //format to run pipeline in compute private Pipeline pipeline = null; private Step currentStep = null; private String strCurrentPipelineStep = "INITIAL"; private int pipelineElementNumber = 0; private int stepNumber = 0; private List<ComputeParameter> allComputeParameters = null; //compute private MCF mcf = null; private DatabaseUpdater updater = null; //map of all compute features/values private Hashtable<String, String> weavingValues = null; Hashtable<String, String> userValues = null; //whole workflow application private ComputeJob wholeWorkflowApp = null; //some necessary values private Workflow target = null; private String applicationName = null; private ParameterWeaver weaver = new ParameterWeaver(); private String remoteLocation = null; private boolean isToWriteLocally = false; private String localLocation = "/"; private List<ComputeProtocol> cProtocols = null; private List<WorkflowElementParameter> wfeParameters = null; //quick solution //can be refactored later to have the same basis for command-line and db solutions private List<ComputeJob> applications = null; private String submit = null; //for the submission script a job should have an id number private Hashtable<String, String> submitIDs = null; int intSubmitID = -1; public void processSingleWorksheet(ComputeBundle bundle, Hashtable<String, String> userValues, String applicationName /* should be unique somehow */) throws IOException, ParseException { applications = new Vector<ComputeJob>(); submitIDs = new Hashtable<String, String>(); this.cProtocols = bundle.getComputeProtocols(); this.wfeParameters = bundle.getWorkflowElementParameters(); this.userValues = userValues; this.applicationName = applicationName; System.out.println(">>> generate apps"); //create new pipeline and set current step to null pipeline = new Pipeline(); currentStep = null; stepNumber = 0; pipelineElementNumber = 0; //!!!!commented application for the whole workflow // wholeWorkflowApp = new ComputeApplication(); //get the chosen workflow // Workflow workflow = db.query(Workflow.class).find().get(0); // wholeWorkflowApp.setProtocol(workflow); // wholeWorkflowApp.setInterpreter("WorkflowInterpreter"); //it would be nice to select compute features of only selected workflow allComputeParameters = bundle.getComputeParameters(); System.out.println("we have so many features: " + allComputeParameters.size()); //add few parameters //wholeWorkflowApp.setTime(now()); //set app name everywhere and add to database //wholeWorkflowApp.setName(applicationName); pipeline.setId(applicationName); weaver.setJobID(applicationName); // db.beginTx(); // db.add(wholeWorkflowApp); //process workflow elements List<WorkflowElement> workflowElements = bundle.getWorkflowElements(); for (int i = 0; i < workflowElements.size(); i++) { WorkflowElement workflowElement = workflowElements.get(i); processWorkflowElement(workflowElement); } String logfile = weaver.getLogfilename(); pipeline.setPipelinelogpath(logfile); //executePipeline(db, pipeline); } public Date now() { Calendar cal = Calendar.getInstance(); return cal.getTime(); } public void executePipeline(Database db, Pipeline pipeline) { if (mcf != null && !flagJustGenerate) { mcf.setPipeline(pipeline); } else System.out.println(pipeline.toString()); } private void processWorkflowElement(WorkflowElement workflowElement) throws ParseException, IOException { weavingValues = new Hashtable<String, String>(); weavingValues.putAll(userValues); System.out.println(">>> workflow element: " + workflowElement.getName()); //create complex features, which will be processed after simple features Vector<ComputeParameter> featuresToDerive = new Vector<ComputeParameter>(); //get protocol and template ComputeProtocol protocol = findProtocol(workflowElement.getProtocol_Name()); //process compute features for (ComputeParameter computeFeature : allComputeParameters) { if (computeFeature.getDefaultValue() == null) continue; else if (computeFeature.getDefaultValue().contains("${")) { featuresToDerive.addElement(computeFeature); } else { weavingValues.put(computeFeature.getName(), computeFeature.getDefaultValue() != null ? computeFeature.getDefaultValue() : ""); } } //process workflow element parameters List<WorkflowElementParameter> workflowElementParameters = findWorkflowElementParameters(workflowElement.getName()); for (WorkflowElementParameter par : workflowElementParameters) { ComputeParameter feature = findComputeFeature(par.getParameter_Name()); weavingValues.put(par.getParameter_Name(), feature.getDefaultValue()); } generateComputeApplication(workflowElement, protocol, weavingValues, featuresToDerive); } private List<WorkflowElementParameter> findWorkflowElementParameters(String name) { List<WorkflowElementParameter> result = new Vector<WorkflowElementParameter>(); for (WorkflowElementParameter p : wfeParameters) { if (p.getWorkflowElement_Name().equalsIgnoreCase(name)) result.add(p); } return result; } private ComputeProtocol findProtocol(String protocol_name) { for (ComputeProtocol c : cProtocols) { if (c.getName().equalsIgnoreCase(protocol_name)) return c; } return null; } private ComputeParameter findComputeFeature(String targetName) { for (ComputeParameter f : allComputeParameters) { if (f.getName().equalsIgnoreCase(targetName)) return f; } return null; } private void generateComputeApplication(WorkflowElement workflowElement, ComputeProtocol protocol, Hashtable<String, String> weavingValues, Vector<ComputeParameter> featuresToDerive) throws IOException, ParseException { ComputeJob app = new ComputeJob(); app.setProtocol(protocol); app.setWorkflowElement(workflowElement); app.setTime(now()); String appName = applicationName + "_" + workflowElement.getName();// + "_" + pipelineElementNumber; app.setName(appName); System.out.println("---application---> " + appName); String protocolTemplate = protocol.getScriptTemplate(); //weave complex features for (int i = 0; i < featuresToDerive.size(); i++) { ComputeParameter feature = featuresToDerive.elementAt(i); String featureName = feature.getName(); String featureTemplate = feature.getDefaultValue(); String featureValue = weaver.weaveFreemarker(featureTemplate, weavingValues); weavingValues.put(featureName, featureValue); } String result = weaver.weaveFreemarker(protocolTemplate, weavingValues); app.setComputeScript(result); app.setInterpreter(protocol.getInterpreter()); applications.add(app); pipelineElementNumber++; if (this.weavingValues.containsKey("outputdir")) { remoteLocation = this.weavingValues.get("outputdir"); remoteLocation += System.getProperty("file.separator") + applicationName; } else { throw new RuntimeException("remote directory on the cluster is not specified in parameter.txt"); } String targetId = null; if (this.weavingValues.containsKey("scriptName")) { targetId = this.weavingValues.get("scriptName"); } else { throw new RuntimeException("ERROR you have to set scriptName in your parameters.txt"); } //create compute pipeline String scriptID = app.getName() + targetId; weaver.setScriptID(scriptID); weaver.setDefaults(); if (protocol.getWalltime() != null) { weaver.setWalltime(protocol.getWalltime()); //quick fix for the cluster queue // if (protocol.getWalltime().equalsIgnoreCase("00:30:00")) // { weaver.setClusterQueue("test"); // } // else // weaver.setClusterQueue("nodes"); } if (protocol.getCores() != null) weaver.setCores(protocol.getCores() + ""); if (protocol.getMem() != null) weaver.setMemoryReq(protocol.getMem() + ""); //at some point of time can be added for the verification weaver.setVerificationCommand("\n"); weaver.setDatasetLocation(remoteLocation); String scriptRemoteLocation = remoteLocation;// + "scripts/"; String logfile = weaver.getLogfilename(); Script pipelineScript = null; if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_BASH)) { pipelineScript = makeShScript(scriptID, scriptRemoteLocation, result); } else if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_R)) { pipelineScript = makeRScript(scriptID, scriptRemoteLocation, result); } else if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_JDL)) { pipelineScript = makeJDLScript(scriptID, scriptRemoteLocation, result); } pipeline.setPipelinelogpath(logfile); submitIDs.put(workflowElement.getName(), ""+intSubmitID); if (isToWriteLocally) weaver.writeToFile(localLocation + scriptID + ".sh", new String(pipelineScript.getScriptData())); List<String> strPreviousWorkflowElements = workflowElement.getPreviousSteps_Name(); String strDependancy = ""; for(String previousWorkflowElement : strPreviousWorkflowElements) { String jobSubmitID = submitIDs.get(previousWorkflowElement); if(strDependancy.equalsIgnoreCase("")) - strDependancy += "job_" + jobSubmitID; + strDependancy += "$job_" + jobSubmitID; else - strDependancy += ":job_" + jobSubmitID; + strDependancy += ":$job_" + jobSubmitID; } if(!strDependancy.equalsIgnoreCase("")) strDependancy = "-W depend=afterok:" + strDependancy; weaver.setSubmitID(""+intSubmitID); weaver.setDependancy(strDependancy); String depend = weaver.makeSumbit(); submit +=depend; if (strPreviousWorkflowElements.size() == 0)//script does not depend on other scripts { if (currentStep == null) //it is a first script in the pipeline { Step step = new Step(workflowElement.getName()); step.setNumber(stepNumber); stepNumber++; currentStep = step; pipeline.addStep(step); } currentStep.addScript(pipelineScript); } else //scripts depends on previous scripts { String strPrevious = strPreviousWorkflowElements.get(0); if (!strPrevious.equalsIgnoreCase(strCurrentPipelineStep)) { //Step step = new Step("step_" + app.getName()); Step step = new Step(workflowElement.getName()); step.setNumber(stepNumber); stepNumber++; currentStep = step; pipeline.addStep(step); } currentStep.addScript(pipelineScript); strCurrentPipelineStep = strPrevious; } intSubmitID++; } //here the first trial of generation for the grid //will be refactored later private Script makeJDLScript(String scriptID, String scriptRemoteLocation, String result) { String gridHeader = weaver.makeGridHeader(); String downloadTop = weaver.makeGridDownload(weavingValues); String uploadBottom = weaver.makeGridUpload(weavingValues); //some special fields should be specified for the jdl file //error and output logs weavingValues.put("error_log", "err_" + scriptID + ".log"); weavingValues.put("output_log", "out_" + scriptID + ".log"); //extra files to be download and upload - now empty weavingValues.put("extra_input", ""); weavingValues.put("extra_output", ""); String jdlfile = weaver.makeJDL(weavingValues); System.out.println("name: " + scriptID); System.out.println("remote location: " + scriptRemoteLocation); System.out.println("command: " + result); String script = gridHeader + "\n" + downloadTop + "\n" + result + "\n" + uploadBottom; System.out.println("jdl-file: \n" + jdlfile); System.out.println("-------\nscript: \n" + script); Script scriptFile = new Script(scriptID, scriptRemoteLocation, script.getBytes()); FileToSaveRemotely jdlFile = new FileToSaveRemotely(scriptID + ".jdl", jdlfile.getBytes()); scriptFile.addFileToTransfer(jdlFile); return scriptFile; } private Script makeRScript(String scriptID, String scriptRemoteLocation, String result) { weaver.setActualCommand("cd " + scriptRemoteLocation + "\n R CMD BATCH " + scriptRemoteLocation + "myscript.R"); String scriptFile = weaver.makeScript(); Script script = new Script(scriptID, scriptRemoteLocation, scriptFile.getBytes()); FileToSaveRemotely rScript = new FileToSaveRemotely("myscript.R", result.getBytes()); script.addFileToTransfer(rScript); System.out.println("Rscript" + result); return script; //todo test it!!!! } private Script makeShScript(String scriptID, String scriptRemoteLocation, String result) { weaver.setActualCommand(result); String scriptFile = weaver.makeScript(); return new Script(scriptID, scriptRemoteLocation, scriptFile.getBytes()); } //root remote location should be set public void setRemoteLocation(String remoteLocation) { this.remoteLocation = remoteLocation; } public void setToWriteLocally(boolean toWriteLocally) { isToWriteLocally = toWriteLocally; } public void setLocalLocation(String localLocation) { this.localLocation = localLocation; } public Pipeline getCurrectPipeline() { return pipeline; } public void setFlagJustGenerate(boolean b) { flagJustGenerate = b; } public String getFormattedTime() { //SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); return sdf.format(now()); } public List<ComputeJob> getComputeApplications() { return applications; } public Pipeline getPipeline() { return pipeline; } public void setNewRun() { submit = new String(); intSubmitID = 1; } public void flashSumbitScript() { weaver.writeToFile(localLocation + "submit.sh", submit); } }
false
true
private void generateComputeApplication(WorkflowElement workflowElement, ComputeProtocol protocol, Hashtable<String, String> weavingValues, Vector<ComputeParameter> featuresToDerive) throws IOException, ParseException { ComputeJob app = new ComputeJob(); app.setProtocol(protocol); app.setWorkflowElement(workflowElement); app.setTime(now()); String appName = applicationName + "_" + workflowElement.getName();// + "_" + pipelineElementNumber; app.setName(appName); System.out.println("---application---> " + appName); String protocolTemplate = protocol.getScriptTemplate(); //weave complex features for (int i = 0; i < featuresToDerive.size(); i++) { ComputeParameter feature = featuresToDerive.elementAt(i); String featureName = feature.getName(); String featureTemplate = feature.getDefaultValue(); String featureValue = weaver.weaveFreemarker(featureTemplate, weavingValues); weavingValues.put(featureName, featureValue); } String result = weaver.weaveFreemarker(protocolTemplate, weavingValues); app.setComputeScript(result); app.setInterpreter(protocol.getInterpreter()); applications.add(app); pipelineElementNumber++; if (this.weavingValues.containsKey("outputdir")) { remoteLocation = this.weavingValues.get("outputdir"); remoteLocation += System.getProperty("file.separator") + applicationName; } else { throw new RuntimeException("remote directory on the cluster is not specified in parameter.txt"); } String targetId = null; if (this.weavingValues.containsKey("scriptName")) { targetId = this.weavingValues.get("scriptName"); } else { throw new RuntimeException("ERROR you have to set scriptName in your parameters.txt"); } //create compute pipeline String scriptID = app.getName() + targetId; weaver.setScriptID(scriptID); weaver.setDefaults(); if (protocol.getWalltime() != null) { weaver.setWalltime(protocol.getWalltime()); //quick fix for the cluster queue // if (protocol.getWalltime().equalsIgnoreCase("00:30:00")) // { weaver.setClusterQueue("test"); // } // else // weaver.setClusterQueue("nodes"); } if (protocol.getCores() != null) weaver.setCores(protocol.getCores() + ""); if (protocol.getMem() != null) weaver.setMemoryReq(protocol.getMem() + ""); //at some point of time can be added for the verification weaver.setVerificationCommand("\n"); weaver.setDatasetLocation(remoteLocation); String scriptRemoteLocation = remoteLocation;// + "scripts/"; String logfile = weaver.getLogfilename(); Script pipelineScript = null; if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_BASH)) { pipelineScript = makeShScript(scriptID, scriptRemoteLocation, result); } else if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_R)) { pipelineScript = makeRScript(scriptID, scriptRemoteLocation, result); } else if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_JDL)) { pipelineScript = makeJDLScript(scriptID, scriptRemoteLocation, result); } pipeline.setPipelinelogpath(logfile); submitIDs.put(workflowElement.getName(), ""+intSubmitID); if (isToWriteLocally) weaver.writeToFile(localLocation + scriptID + ".sh", new String(pipelineScript.getScriptData())); List<String> strPreviousWorkflowElements = workflowElement.getPreviousSteps_Name(); String strDependancy = ""; for(String previousWorkflowElement : strPreviousWorkflowElements) { String jobSubmitID = submitIDs.get(previousWorkflowElement); if(strDependancy.equalsIgnoreCase("")) strDependancy += "job_" + jobSubmitID; else strDependancy += ":job_" + jobSubmitID; } if(!strDependancy.equalsIgnoreCase("")) strDependancy = "-W depend=afterok:" + strDependancy; weaver.setSubmitID(""+intSubmitID); weaver.setDependancy(strDependancy); String depend = weaver.makeSumbit(); submit +=depend; if (strPreviousWorkflowElements.size() == 0)//script does not depend on other scripts { if (currentStep == null) //it is a first script in the pipeline { Step step = new Step(workflowElement.getName()); step.setNumber(stepNumber); stepNumber++; currentStep = step; pipeline.addStep(step); } currentStep.addScript(pipelineScript); } else //scripts depends on previous scripts { String strPrevious = strPreviousWorkflowElements.get(0); if (!strPrevious.equalsIgnoreCase(strCurrentPipelineStep)) { //Step step = new Step("step_" + app.getName()); Step step = new Step(workflowElement.getName()); step.setNumber(stepNumber); stepNumber++; currentStep = step; pipeline.addStep(step); } currentStep.addScript(pipelineScript); strCurrentPipelineStep = strPrevious; } intSubmitID++; }
private void generateComputeApplication(WorkflowElement workflowElement, ComputeProtocol protocol, Hashtable<String, String> weavingValues, Vector<ComputeParameter> featuresToDerive) throws IOException, ParseException { ComputeJob app = new ComputeJob(); app.setProtocol(protocol); app.setWorkflowElement(workflowElement); app.setTime(now()); String appName = applicationName + "_" + workflowElement.getName();// + "_" + pipelineElementNumber; app.setName(appName); System.out.println("---application---> " + appName); String protocolTemplate = protocol.getScriptTemplate(); //weave complex features for (int i = 0; i < featuresToDerive.size(); i++) { ComputeParameter feature = featuresToDerive.elementAt(i); String featureName = feature.getName(); String featureTemplate = feature.getDefaultValue(); String featureValue = weaver.weaveFreemarker(featureTemplate, weavingValues); weavingValues.put(featureName, featureValue); } String result = weaver.weaveFreemarker(protocolTemplate, weavingValues); app.setComputeScript(result); app.setInterpreter(protocol.getInterpreter()); applications.add(app); pipelineElementNumber++; if (this.weavingValues.containsKey("outputdir")) { remoteLocation = this.weavingValues.get("outputdir"); remoteLocation += System.getProperty("file.separator") + applicationName; } else { throw new RuntimeException("remote directory on the cluster is not specified in parameter.txt"); } String targetId = null; if (this.weavingValues.containsKey("scriptName")) { targetId = this.weavingValues.get("scriptName"); } else { throw new RuntimeException("ERROR you have to set scriptName in your parameters.txt"); } //create compute pipeline String scriptID = app.getName() + targetId; weaver.setScriptID(scriptID); weaver.setDefaults(); if (protocol.getWalltime() != null) { weaver.setWalltime(protocol.getWalltime()); //quick fix for the cluster queue // if (protocol.getWalltime().equalsIgnoreCase("00:30:00")) // { weaver.setClusterQueue("test"); // } // else // weaver.setClusterQueue("nodes"); } if (protocol.getCores() != null) weaver.setCores(protocol.getCores() + ""); if (protocol.getMem() != null) weaver.setMemoryReq(protocol.getMem() + ""); //at some point of time can be added for the verification weaver.setVerificationCommand("\n"); weaver.setDatasetLocation(remoteLocation); String scriptRemoteLocation = remoteLocation;// + "scripts/"; String logfile = weaver.getLogfilename(); Script pipelineScript = null; if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_BASH)) { pipelineScript = makeShScript(scriptID, scriptRemoteLocation, result); } else if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_R)) { pipelineScript = makeRScript(scriptID, scriptRemoteLocation, result); } else if (protocol.getInterpreter().equalsIgnoreCase(INTERPRETER_JDL)) { pipelineScript = makeJDLScript(scriptID, scriptRemoteLocation, result); } pipeline.setPipelinelogpath(logfile); submitIDs.put(workflowElement.getName(), ""+intSubmitID); if (isToWriteLocally) weaver.writeToFile(localLocation + scriptID + ".sh", new String(pipelineScript.getScriptData())); List<String> strPreviousWorkflowElements = workflowElement.getPreviousSteps_Name(); String strDependancy = ""; for(String previousWorkflowElement : strPreviousWorkflowElements) { String jobSubmitID = submitIDs.get(previousWorkflowElement); if(strDependancy.equalsIgnoreCase("")) strDependancy += "$job_" + jobSubmitID; else strDependancy += ":$job_" + jobSubmitID; } if(!strDependancy.equalsIgnoreCase("")) strDependancy = "-W depend=afterok:" + strDependancy; weaver.setSubmitID(""+intSubmitID); weaver.setDependancy(strDependancy); String depend = weaver.makeSumbit(); submit +=depend; if (strPreviousWorkflowElements.size() == 0)//script does not depend on other scripts { if (currentStep == null) //it is a first script in the pipeline { Step step = new Step(workflowElement.getName()); step.setNumber(stepNumber); stepNumber++; currentStep = step; pipeline.addStep(step); } currentStep.addScript(pipelineScript); } else //scripts depends on previous scripts { String strPrevious = strPreviousWorkflowElements.get(0); if (!strPrevious.equalsIgnoreCase(strCurrentPipelineStep)) { //Step step = new Step("step_" + app.getName()); Step step = new Step(workflowElement.getName()); step.setNumber(stepNumber); stepNumber++; currentStep = step; pipeline.addStep(step); } currentStep.addScript(pipelineScript); strCurrentPipelineStep = strPrevious; } intSubmitID++; }
diff --git a/src/com/jpii/navalbattle/pavo/gui/OmniMap.java b/src/com/jpii/navalbattle/pavo/gui/OmniMap.java index 3f05950e..7c2fbb29 100644 --- a/src/com/jpii/navalbattle/pavo/gui/OmniMap.java +++ b/src/com/jpii/navalbattle/pavo/gui/OmniMap.java @@ -1,144 +1,148 @@ /* * Copyright (C) 2012 JPII and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jpii.navalbattle.pavo.gui; import java.awt.event.*; import java.awt.image.*; import java.awt.*; import maximusvladimir.dagen.Rand; import com.jpii.navalbattle.pavo.Game; import com.jpii.navalbattle.pavo.ProceduralLayeredMapGenerator; import com.jpii.navalbattle.pavo.PavoHelper; import com.jpii.navalbattle.pavo.Renderable; import com.jpii.navalbattle.pavo.World; import com.jpii.navalbattle.pavo.grid.Entity; import com.jpii.navalbattle.pavo.grid.EntityManager; import com.jpii.navalbattle.pavo.io.PavoImage; import com.jpii.navalbattle.renderer.Helper; import com.jpii.navalbattle.renderer.RenderConstants; public class OmniMap extends Renderable { private static final long serialVersionUID = 1L; int mx,my; World w; PavoImage terrain; public OmniMap(World w) { super(); this.w = w; setSize(100,100); buffer = (new PavoImage(getWidth(), getHeight(),BufferedImage.TYPE_INT_RGB)); terrain = (new PavoImage(getWidth(), getHeight(),BufferedImage.TYPE_INT_RGB)); writeBuffer(); } public void mouseMoved(MouseEvent me) { mx = me.getX(); my = me.getY(); render(); } public boolean mouseDown(MouseEvent me) { int ax = me.getX() - (Game.Settings.currentWidth - 158); int ay = me.getY() - 40; if (ax > 100 || ay > 100 || ax < 0 || ay < 0) return false; int sw = (int)(((150 * Game.Settings.currentWidth)/(PavoHelper.getGameWidth(w.getWorldSize())*100))/3.33333333333f); int sh = (int)(((150 * Game.Settings.currentHeight)/(PavoHelper.getGameHeight(w.getWorldSize())*100))/3.333333333333f); if (!w.getGame().isAClient()) w.getGame().getSelfServer().send("bounds:"+sw+","+sh); else w.getGame().getSelfClient().send("bounds:"+sw+","+sh); w.setLoc( ((-(ax-sw)*PavoHelper.getGameWidth(w.getWorldSize()))), ((-(ay-sh)*PavoHelper.getGameHeight(w.getWorldSize()))) ); render(); w.forceRender(); return true; } public boolean mouseDragged(MouseEvent me) { return mouseDown(me); } public void writeBuffer() { Graphics2D g = PavoHelper.createGraphics(terrain); Rand rand = new Rand(Game.Settings.seed); for (int x = 0; x < 100/3; x++) { for (int y = 0; y < 100/3; y++) { int strx = x * PavoHelper.getGameWidth(w.getWorldSize()); int stry = y * PavoHelper.getGameHeight(w.getWorldSize()); float frsh = ProceduralLayeredMapGenerator.getPoint(strx,stry); float lsy = frsh; if (lsy < 0.4) { int rgs = Helper.colorSnap((int)(lsy*102)); g.setColor(new Color(63+rand.nextInt(-7,7),60+rand.nextInt(-7,7),rand.nextInt(90, 100)+rgs)); } else if (lsy < 0.55) { Color base1 = PavoHelper.Lerp(RenderConstants.GEN_SAND_COLOR,new Color(52,79,13),((lsy-0.4)/0.15)); base1 = Helper.randomise(base1, 8, rand, false); g.setColor(base1); } else{ Color base1 = PavoHelper.Lerp(new Color(52,79,13),new Color(100,92,40),((lsy-0.55)/0.45)); base1 = Helper.randomise(base1, 8, rand, false); g.setColor(base1); } g.fillRect(x*3,y*3,4,4); } } g.dispose(); } int mpx = 0,mpy=0; public void setMultiplayer(int xx, int zz) { mpx = xx; mpy = zz; render(); } public void render() { Graphics2D g = PavoHelper.createGraphics(getBuffer()); g.drawImage(terrain, 0,0,null); int rwx = (int)(-w.getScreenX()*100)/(PavoHelper.getGameWidth(w.getWorldSize()) * 100); int rwy = (int)(-w.getScreenY()*100)/(PavoHelper.getGameHeight(w.getWorldSize()) * 100); int sw = (int)((150 * Game.Settings.currentWidth)/(PavoHelper.getGameWidth(w.getWorldSize())*100)); int sh = (int)((150 * Game.Settings.currentHeight)/(PavoHelper.getGameHeight(w.getWorldSize())*100)); int rwmx = (int) (Math.abs(mpx-(Game.Settings.currentWidth/2)) * 33.333333 / (PavoHelper.getGameWidth(w.getWorldSize()) * 100))*3; int rwmy = (int) (Math.abs(mpy-(Game.Settings.currentHeight/2)) * 33.333333 / (PavoHelper.getGameHeight(w.getWorldSize()) * 100))*3; g.setColor(Color.red); g.drawRect(rwx-1,rwy-1,sw/2,sh/2); if (w.getGame().isConnectedToClientOrServer()) { g.setColor(Color.yellow); g.drawRect(rwmx-1,rwmy-1,sw/2,sh/2); } EntityManager eme = w.getEntityManager(); g.setColor(Color.cyan); for (int c = 0; c < eme.getTotalEntities(); c++) { Entity ent = eme.getEntity(c); + if (ent instanceof PortEntity) + g.setColor(Color.green); + else + g.setColor(Color.cyan); int rdx = (int)(((ent.getLocation().getCol()*50)*100)/(PavoHelper.getGameWidth(w.getWorldSize()) * 100)); int rdy = (int)(((ent.getLocation().getRow()*50)*100)/(PavoHelper.getGameHeight(w.getWorldSize()) * 100)); g.drawLine(rdx,rdy,rdx,rdy); } g.setColor(new Color(100, 78, 47)); g.drawRect(1, 1, width - 3, 100 - 3); g.setColor(new Color(74, 30, 3)); g.drawRect(0, 0, width - 1, 100 - 1); g.dispose(); } }
true
true
public void render() { Graphics2D g = PavoHelper.createGraphics(getBuffer()); g.drawImage(terrain, 0,0,null); int rwx = (int)(-w.getScreenX()*100)/(PavoHelper.getGameWidth(w.getWorldSize()) * 100); int rwy = (int)(-w.getScreenY()*100)/(PavoHelper.getGameHeight(w.getWorldSize()) * 100); int sw = (int)((150 * Game.Settings.currentWidth)/(PavoHelper.getGameWidth(w.getWorldSize())*100)); int sh = (int)((150 * Game.Settings.currentHeight)/(PavoHelper.getGameHeight(w.getWorldSize())*100)); int rwmx = (int) (Math.abs(mpx-(Game.Settings.currentWidth/2)) * 33.333333 / (PavoHelper.getGameWidth(w.getWorldSize()) * 100))*3; int rwmy = (int) (Math.abs(mpy-(Game.Settings.currentHeight/2)) * 33.333333 / (PavoHelper.getGameHeight(w.getWorldSize()) * 100))*3; g.setColor(Color.red); g.drawRect(rwx-1,rwy-1,sw/2,sh/2); if (w.getGame().isConnectedToClientOrServer()) { g.setColor(Color.yellow); g.drawRect(rwmx-1,rwmy-1,sw/2,sh/2); } EntityManager eme = w.getEntityManager(); g.setColor(Color.cyan); for (int c = 0; c < eme.getTotalEntities(); c++) { Entity ent = eme.getEntity(c); int rdx = (int)(((ent.getLocation().getCol()*50)*100)/(PavoHelper.getGameWidth(w.getWorldSize()) * 100)); int rdy = (int)(((ent.getLocation().getRow()*50)*100)/(PavoHelper.getGameHeight(w.getWorldSize()) * 100)); g.drawLine(rdx,rdy,rdx,rdy); } g.setColor(new Color(100, 78, 47)); g.drawRect(1, 1, width - 3, 100 - 3); g.setColor(new Color(74, 30, 3)); g.drawRect(0, 0, width - 1, 100 - 1); g.dispose(); }
public void render() { Graphics2D g = PavoHelper.createGraphics(getBuffer()); g.drawImage(terrain, 0,0,null); int rwx = (int)(-w.getScreenX()*100)/(PavoHelper.getGameWidth(w.getWorldSize()) * 100); int rwy = (int)(-w.getScreenY()*100)/(PavoHelper.getGameHeight(w.getWorldSize()) * 100); int sw = (int)((150 * Game.Settings.currentWidth)/(PavoHelper.getGameWidth(w.getWorldSize())*100)); int sh = (int)((150 * Game.Settings.currentHeight)/(PavoHelper.getGameHeight(w.getWorldSize())*100)); int rwmx = (int) (Math.abs(mpx-(Game.Settings.currentWidth/2)) * 33.333333 / (PavoHelper.getGameWidth(w.getWorldSize()) * 100))*3; int rwmy = (int) (Math.abs(mpy-(Game.Settings.currentHeight/2)) * 33.333333 / (PavoHelper.getGameHeight(w.getWorldSize()) * 100))*3; g.setColor(Color.red); g.drawRect(rwx-1,rwy-1,sw/2,sh/2); if (w.getGame().isConnectedToClientOrServer()) { g.setColor(Color.yellow); g.drawRect(rwmx-1,rwmy-1,sw/2,sh/2); } EntityManager eme = w.getEntityManager(); g.setColor(Color.cyan); for (int c = 0; c < eme.getTotalEntities(); c++) { Entity ent = eme.getEntity(c); if (ent instanceof PortEntity) g.setColor(Color.green); else g.setColor(Color.cyan); int rdx = (int)(((ent.getLocation().getCol()*50)*100)/(PavoHelper.getGameWidth(w.getWorldSize()) * 100)); int rdy = (int)(((ent.getLocation().getRow()*50)*100)/(PavoHelper.getGameHeight(w.getWorldSize()) * 100)); g.drawLine(rdx,rdy,rdx,rdy); } g.setColor(new Color(100, 78, 47)); g.drawRect(1, 1, width - 3, 100 - 3); g.setColor(new Color(74, 30, 3)); g.drawRect(0, 0, width - 1, 100 - 1); g.dispose(); }
diff --git a/src/jvm/final_project/view/CheckInPanel.java b/src/jvm/final_project/view/CheckInPanel.java index bab320e..6ffd726 100644 --- a/src/jvm/final_project/view/CheckInPanel.java +++ b/src/jvm/final_project/view/CheckInPanel.java @@ -1,477 +1,477 @@ package final_project.view; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; import javax.swing.event.*; import javax.swing.table.*; import final_project.control.Constants; import final_project.control.TournamentController; import net.java.balloontip.BalloonTip; import net.java.balloontip.BalloonTip.*; public class CheckInPanel extends JPanel implements ActionListener, Constants { /** * */ private static final long serialVersionUID = 1L; private JTable table; private TournamentController tournament; private SignInTableModel model; private TableRowSorter<SignInTableModel> sorter; private JScrollPane scrollPane; private JSearchTextField searchField; private JButton signInAll, unsignInAll, importXml, registerPersonButton, startPoolRound; private Collection<BalloonTip> balloons; private BalloonTip signInPlayerTip, registerNewPlayerTip, signInAllTip, unsignInAllTip, stripSetupTip, poolSizeTip; private CheckInPlayerPanel signInPlayerPane; private RegisterNewPlayerPanel registerNewPlayerPane; private ConfirmationPanel signInAllPane, unsignInAllPane; private StripSetupPanel stripSetupPane; private PoolSizeInfoPanel poolSizeInfoPane; private File xmlFile; private JLabel fileLabel; /** * Create the panel. */ public CheckInPanel(TournamentController t) { super(); tournament = t; initializeGridBagLayout(); initializeTable(); initializeComponents(); initializeSearch(); initializeBalloons(); } private void initializeComponents() { setOpaque(false); signInAll = new JButton("Sign In All"); signInAll.addActionListener(this); GridBagConstraints gbc_signInAll = new GridBagConstraints(); gbc_signInAll.anchor = GridBagConstraints.EAST; gbc_signInAll.insets = new Insets(0, 0, 5, 5); gbc_signInAll.gridx = 1; gbc_signInAll.gridy = 1; add(signInAll, gbc_signInAll); unsignInAll = new JButton("Unsign In All"); unsignInAll.addActionListener(this); GridBagConstraints gbc_unsignInAll = new GridBagConstraints(); gbc_unsignInAll.anchor = GridBagConstraints.WEST; gbc_unsignInAll.insets = new Insets(0, 0, 5, 5); gbc_unsignInAll.gridx = 2; gbc_unsignInAll.gridy = 1; add(unsignInAll, gbc_unsignInAll); registerPersonButton = new JButton("Register Person"); GridBagConstraints gbc_registerPersonButton = new GridBagConstraints(); gbc_registerPersonButton.insets = new Insets(0, 0, 5, 5); gbc_registerPersonButton.gridx = 5; gbc_registerPersonButton.gridy = 1; add(registerPersonButton, gbc_registerPersonButton); registerPersonButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { registerNewPlayerPane.setNoResults(false); registerNewPlayerPane.getNameTextField().requestFocusInWindow(); registerNewPlayerPane.getNameTextField().setText(""); registerNewPlayerPane.getPhoneNumberTextField().setText(""); hideAllBalloons(); registerNewPlayerTip.setVisible(true); } }); scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.gridwidth = 5; gbc_scrollPane.insets = new Insets(0, 0, 5, 5); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 1; gbc_scrollPane.gridy = 2; add(scrollPane, gbc_scrollPane); scrollPane.setViewportView(table); importXml = new JButton("Import XML"); GridBagConstraints gbc_btnImportXml = new GridBagConstraints(); gbc_btnImportXml.insets = new Insets(0, 0, 5, 5); gbc_btnImportXml.gridx = 1; gbc_btnImportXml.gridy = 3; add(importXml, gbc_btnImportXml); importXml.addActionListener(this); fileLabel = new JLabel(""); GridBagConstraints gbc_label = new GridBagConstraints(); gbc_label.anchor = GridBagConstraints.WEST; gbc_label.gridwidth = 3; gbc_label.insets = new Insets(0, 0, 5, 5); gbc_label.gridx = 2; gbc_label.gridy = 3; add(fileLabel, gbc_label); startPoolRound = new JButton("Start Pool Round"); GridBagConstraints gbc_startPoolRound = new GridBagConstraints(); gbc_startPoolRound.insets = new Insets(0, 0, 5, 5); gbc_startPoolRound.gridx = 5; gbc_startPoolRound.gridy = 3; add(startPoolRound, gbc_startPoolRound); startPoolRound.addActionListener(this); } private void initializeSearch() { searchField = new JSearchTextField(); searchField.getDocument().addDocumentListener( new DocumentListener() { public void changedUpdate(DocumentEvent e) { filter(); } public void insertUpdate(DocumentEvent e) { filter(); } public void removeUpdate(DocumentEvent e) { filter(); } }); GridBagConstraints gbc_txtSearch = new GridBagConstraints(); gbc_txtSearch.gridwidth = 2; gbc_txtSearch.fill = GridBagConstraints.HORIZONTAL; gbc_txtSearch.insets = new Insets(0, 0, 5, 5); gbc_txtSearch.gridx = 3; gbc_txtSearch.gridy = 1; add(searchField, gbc_txtSearch); searchField.setColumns(10); searchField.addKeyListener (new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { signInSelectedPlayer(true); } } }); } private void signInSelectedPlayer(boolean checkAs) { hideAllBalloons(); //changed to table.convertColumIndexToView to prevent bug where user rearranges column ordering int id = (Integer)table.getValueAt(table.getSelectedRow(), table.convertColumnIndexToView(4)); //Getting the ID DOES THIS WORK?? //Checking in the fencer as the checkAs boolean System.out.println("ID and boolean: " + id + " " + checkAs); Object[][] newData = tournament.checkInFencer(id, checkAs); model.setData(newData); searchField.setText(""); this.repaint(); } private void initializeTable() { //Set up table with custom sorter model = new SignInTableModel(); model.addTableModelListener(model); sorter = new TableRowSorter<SignInTableModel>(model); table = new JTable(model); table.setRowSorter(sorter); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); table.setFillsViewportHeight(true); table.grabFocus(); table.getRowSorter().toggleSortOrder(0); } private void initializeGridBagLayout() { GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{0, 88, 102, 102, 102, 102, 0, 0}; gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0}; gridBagLayout.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE}; setLayout(gridBagLayout); } private void initializeBalloons() { balloons = new ArrayList<BalloonTip>(); //setup tooltips signInPlayerPane = new CheckInPlayerPanel(); signInPlayerTip = new BalloonTip(registerPersonButton, signInPlayerPane, new DefaultBalloonStyle(), false); signInPlayerTip.setOpacity(0.9f); signInPlayerPane.getCancelButton().addActionListener(this); signInPlayerPane.getSignInButton().addActionListener(this); registerNewPlayerPane = new RegisterNewPlayerPanel(); registerNewPlayerTip = new BalloonTip(registerPersonButton, registerNewPlayerPane, new DefaultBalloonStyle(), false); registerNewPlayerTip.setOpacity(0.9f); registerNewPlayerPane.getCancelButton().addActionListener(this); registerNewPlayerPane.getDoneButton().addActionListener(this); signInAllPane = new ConfirmationPanel("sign in"); signInAllTip = new BalloonTip(signInAll, signInAllPane, new DefaultBalloonStyle(), false); signInAllTip.setOpacity(0.9f); signInAllPane.getCancelButton().addActionListener(this); signInAllPane.getYesButton().addActionListener(this); unsignInAllPane = new ConfirmationPanel("un-sign in"); unsignInAllTip = new BalloonTip(unsignInAll, unsignInAllPane, new DefaultBalloonStyle(), false); unsignInAllTip.setOpacity(0.9f); unsignInAllPane.getCancelButton().addActionListener(this); unsignInAllPane.getYesButton().addActionListener(this); stripSetupPane = new StripSetupPanel(); stripSetupTip = new BalloonTip(startPoolRound, stripSetupPane, new DefaultBalloonStyle(), Orientation.RIGHT_ABOVE, AttachLocation.ALIGNED, 10, 10, false); stripSetupTip.setOpacity(0.9f); stripSetupPane.getCancelButton().addActionListener(this); stripSetupPane.getDoneButton().addActionListener(this); poolSizeInfoPane = new PoolSizeInfoPanel(tournament); poolSizeTip = new BalloonTip(startPoolRound, poolSizeInfoPane, new DefaultBalloonStyle(), Orientation.RIGHT_ABOVE, AttachLocation.ALIGNED, 10, 10, false); poolSizeTip.setOpacity(0.9f); balloons.add(signInPlayerTip); balloons.add(registerNewPlayerTip); balloons.add(signInAllTip); balloons.add(unsignInAllTip); balloons.add(stripSetupTip); balloons.add(poolSizeTip); hideAllBalloons(); } private void filter() { RowFilter<SignInTableModel, Object> rf = null; //If current expression doesn't parse, don't update. try { rf = RowFilter.regexFilter("(?i)" + searchField.getText()); } catch (java.util.regex.PatternSyntaxException e) { return; } sorter.setRowFilter(rf); if (table.getRowCount() == 0) { //Hide other tooltips hideAllBalloons(); //Make tooltip visible registerNewPlayerTip.setVisible(true); //Clear any old text registerNewPlayerPane.setNoResults(true); registerNewPlayerPane.getNameTextField().setText(""); registerNewPlayerPane.getPhoneNumberTextField().setText(""); //Decide whether entered text is a name or phone number try { Long.parseLong(searchField.getText()); registerNewPlayerPane.getPhoneNumberTextField().setText(searchField.getText()); searchField.setNextFocusableComponent(registerNewPlayerPane.getNameTextField()); } catch (NumberFormatException e) { registerNewPlayerPane.getNameTextField().setText(searchField.getText()); searchField.setNextFocusableComponent(registerNewPlayerPane.getPhoneNumberTextField()); } } else if (table.getRowCount() == 1) { //Hide other tooltip registerNewPlayerTip.setVisible(false); //select this row ListSelectionModel selectionModel = table.getSelectionModel(); selectionModel.setSelectionInterval(0, 0); //Make tooltip visible signInPlayerPane.getResultLabel().setText("<html><i>Exact Match Found:</i> <b>" + table.getValueAt(0, 0) + "</b></html>"); searchField.setNextFocusableComponent(signInPlayerPane.getSignInButton()); hideAllBalloons(); signInPlayerTip.setVisible(true); } else { hideAllBalloons(); } } class SignInTableModel extends AbstractTableModel implements TableModelListener { private static final long serialVersionUID = 1L; private String[] columnNames = {"Name", "Team", "Group", "Signed In", "ID"}; private Object[][] data = tournament.giveSignInPanelInfo(); public void setData(Object[][] newData) { data = newData; } @Override public int getColumnCount() { return columnNames.length; } @Override public int getRowCount() { return data.length; } @Override public String getColumnName(int col) { return columnNames[col]; } @Override public Object getValueAt(int row, int col) { return data[row][col]; } @Override public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } @Override public boolean isCellEditable(int row, int col) { if (col < 2) { return false; } else { return true; } } @Override public void setValueAt(Object value, int row, int col) { if(data.length == 0) return; data[row][col] = value; fireTableCellUpdated(row, col); } @Override public void tableChanged(TableModelEvent e) { int row = e.getFirstRow(); int column = e.getColumn(); TableModel model = (TableModel)e.getSource(); Object data = model.getValueAt(row, column); //TODO TOTALLY broken if(column == 3){ //If the column is the signedIn button col System.out.println("Changed: " + data); signInSelectedPlayer((Boolean)data); } //Fix for weird sorting sorter.sort(); table.clearSelection(); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == importXml) { //Import xml file JFileChooser fileChooser = new JFileChooser(); int returnValue = fileChooser.showOpenDialog(importXml); if (returnValue == JFileChooser.APPROVE_OPTION) { xmlFile = fileChooser.getSelectedFile(); fileLabel.setText(xmlFile.getPath()); } } else if (e.getSource() == startPoolRound) { hideAllBalloons(); stripSetupTip.setVisible(true); } else if (e.getSource() == signInPlayerPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == signInPlayerPane.getSignInButton()) { signInSelectedPlayer(true); } else if (e.getSource() == registerNewPlayerPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == registerNewPlayerPane.getDoneButton()) { hideAllBalloons(); //Getting the info out of the registerNewPlayerPane String number = registerNewPlayerPane.getPhoneNumberTextField().getText(); String name = registerNewPlayerPane.getNameTextField().getText(); String firstName = "", lastName = ""; int nameSplit = name.lastIndexOf(' '); if (nameSplit > 0) { firstName = name.substring(0, nameSplit); lastName = name.substring(nameSplit+1, name.length()); } else { firstName = name; lastName = ""; } int rank = Integer.parseInt(registerNewPlayerPane.getRankField().getText()); //TODO: Need to make it impossible to click done unless all fields are filled out /* Registering player and resetting the data in the table */ Object[][] newData = tournament.registerAndCheckInFencer(number, firstName, lastName, rank); model.setData(newData); this.getSearchField().setText(""); //Making sure the table is updated nicely - //model.modelStructureChanged(); - sorter.sort(); + sorter.modelStructureChanged(); + //sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == signInAll) { //Make new signInAllTooltip hideAllBalloons(); signInAllTip.setVisible(true); } else if (e.getSource() == unsignInAll) { hideAllBalloons(); unsignInAllTip.setVisible(true); } else if (e.getSource() == signInAllPane.getCancelButton() || e.getSource() == unsignInAllPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == signInAllPane.getYesButton()) { hideAllBalloons(); //Checking in all as true! Object[][] newData = tournament.checkInAll(true); model.setData(newData); //Fix for weird sorting sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == unsignInAllPane.getYesButton()) { hideAllBalloons(); //Checking in all as false Object[][] newData = tournament.checkInAll(false); model.setData(newData); //Fix for weird sorting sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == stripSetupPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == stripSetupPane.getDoneButton()) { hideAllBalloons(); //Getting the strip arrangement from the editor int row = (Integer) stripSetupPane.getRowSpinner().getValue(); int col = (Integer) stripSetupPane.getColSpinner().getValue(); tournament.setStripSizes(EVENT_ID, row, col); //Registering all of the current players into the event tournament.addAllPlayersToEvent(EVENT_ID); poolSizeTip.setVisible(true); Object[][] newData = tournament.getPoolSizeInfoTable(); poolSizeInfoPane.setData(newData); this.repaint(); } } public JSearchTextField getSearchField() { return searchField; } public JButton getAddFencerButton() { return registerPersonButton; } private void hideAllBalloons() { for (BalloonTip b : balloons) b.setVisible(false); } }
true
true
public void actionPerformed(ActionEvent e) { if (e.getSource() == importXml) { //Import xml file JFileChooser fileChooser = new JFileChooser(); int returnValue = fileChooser.showOpenDialog(importXml); if (returnValue == JFileChooser.APPROVE_OPTION) { xmlFile = fileChooser.getSelectedFile(); fileLabel.setText(xmlFile.getPath()); } } else if (e.getSource() == startPoolRound) { hideAllBalloons(); stripSetupTip.setVisible(true); } else if (e.getSource() == signInPlayerPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == signInPlayerPane.getSignInButton()) { signInSelectedPlayer(true); } else if (e.getSource() == registerNewPlayerPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == registerNewPlayerPane.getDoneButton()) { hideAllBalloons(); //Getting the info out of the registerNewPlayerPane String number = registerNewPlayerPane.getPhoneNumberTextField().getText(); String name = registerNewPlayerPane.getNameTextField().getText(); String firstName = "", lastName = ""; int nameSplit = name.lastIndexOf(' '); if (nameSplit > 0) { firstName = name.substring(0, nameSplit); lastName = name.substring(nameSplit+1, name.length()); } else { firstName = name; lastName = ""; } int rank = Integer.parseInt(registerNewPlayerPane.getRankField().getText()); //TODO: Need to make it impossible to click done unless all fields are filled out /* Registering player and resetting the data in the table */ Object[][] newData = tournament.registerAndCheckInFencer(number, firstName, lastName, rank); model.setData(newData); this.getSearchField().setText(""); //Making sure the table is updated nicely //model.modelStructureChanged(); sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == signInAll) { //Make new signInAllTooltip hideAllBalloons(); signInAllTip.setVisible(true); } else if (e.getSource() == unsignInAll) { hideAllBalloons(); unsignInAllTip.setVisible(true); } else if (e.getSource() == signInAllPane.getCancelButton() || e.getSource() == unsignInAllPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == signInAllPane.getYesButton()) { hideAllBalloons(); //Checking in all as true! Object[][] newData = tournament.checkInAll(true); model.setData(newData); //Fix for weird sorting sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == unsignInAllPane.getYesButton()) { hideAllBalloons(); //Checking in all as false Object[][] newData = tournament.checkInAll(false); model.setData(newData); //Fix for weird sorting sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == stripSetupPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == stripSetupPane.getDoneButton()) { hideAllBalloons(); //Getting the strip arrangement from the editor int row = (Integer) stripSetupPane.getRowSpinner().getValue(); int col = (Integer) stripSetupPane.getColSpinner().getValue(); tournament.setStripSizes(EVENT_ID, row, col); //Registering all of the current players into the event tournament.addAllPlayersToEvent(EVENT_ID); poolSizeTip.setVisible(true); Object[][] newData = tournament.getPoolSizeInfoTable(); poolSizeInfoPane.setData(newData); this.repaint(); } }
public void actionPerformed(ActionEvent e) { if (e.getSource() == importXml) { //Import xml file JFileChooser fileChooser = new JFileChooser(); int returnValue = fileChooser.showOpenDialog(importXml); if (returnValue == JFileChooser.APPROVE_OPTION) { xmlFile = fileChooser.getSelectedFile(); fileLabel.setText(xmlFile.getPath()); } } else if (e.getSource() == startPoolRound) { hideAllBalloons(); stripSetupTip.setVisible(true); } else if (e.getSource() == signInPlayerPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == signInPlayerPane.getSignInButton()) { signInSelectedPlayer(true); } else if (e.getSource() == registerNewPlayerPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == registerNewPlayerPane.getDoneButton()) { hideAllBalloons(); //Getting the info out of the registerNewPlayerPane String number = registerNewPlayerPane.getPhoneNumberTextField().getText(); String name = registerNewPlayerPane.getNameTextField().getText(); String firstName = "", lastName = ""; int nameSplit = name.lastIndexOf(' '); if (nameSplit > 0) { firstName = name.substring(0, nameSplit); lastName = name.substring(nameSplit+1, name.length()); } else { firstName = name; lastName = ""; } int rank = Integer.parseInt(registerNewPlayerPane.getRankField().getText()); //TODO: Need to make it impossible to click done unless all fields are filled out /* Registering player and resetting the data in the table */ Object[][] newData = tournament.registerAndCheckInFencer(number, firstName, lastName, rank); model.setData(newData); this.getSearchField().setText(""); //Making sure the table is updated nicely sorter.modelStructureChanged(); //sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == signInAll) { //Make new signInAllTooltip hideAllBalloons(); signInAllTip.setVisible(true); } else if (e.getSource() == unsignInAll) { hideAllBalloons(); unsignInAllTip.setVisible(true); } else if (e.getSource() == signInAllPane.getCancelButton() || e.getSource() == unsignInAllPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == signInAllPane.getYesButton()) { hideAllBalloons(); //Checking in all as true! Object[][] newData = tournament.checkInAll(true); model.setData(newData); //Fix for weird sorting sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == unsignInAllPane.getYesButton()) { hideAllBalloons(); //Checking in all as false Object[][] newData = tournament.checkInAll(false); model.setData(newData); //Fix for weird sorting sorter.sort(); table.clearSelection(); this.repaint(); } else if (e.getSource() == stripSetupPane.getCancelButton()) { hideAllBalloons(); } else if (e.getSource() == stripSetupPane.getDoneButton()) { hideAllBalloons(); //Getting the strip arrangement from the editor int row = (Integer) stripSetupPane.getRowSpinner().getValue(); int col = (Integer) stripSetupPane.getColSpinner().getValue(); tournament.setStripSizes(EVENT_ID, row, col); //Registering all of the current players into the event tournament.addAllPlayersToEvent(EVENT_ID); poolSizeTip.setVisible(true); Object[][] newData = tournament.getPoolSizeInfoTable(); poolSizeInfoPane.setData(newData); this.repaint(); } }
diff --git a/src/com/imdeity/deitynether/Config.java b/src/com/imdeity/deitynether/Config.java index 2e14179..ed74883 100644 --- a/src/com/imdeity/deitynether/Config.java +++ b/src/com/imdeity/deitynether/Config.java @@ -1,135 +1,135 @@ package com.imdeity.deitynether; import java.io.File; import java.io.IOException; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.configuration.file.YamlConfiguration; public class Config{ YamlConfiguration config = null; File file = null; public Config(File file){ config = YamlConfiguration.loadConfiguration(file); this.file = file; } public void loadDefaults(){ if(!config.contains("world.nether.days-until-next-regen")) //World options config.set("world.nether.days-until-next-regen", 7); if(!config.contains("world.nether.wait-time-in-hours")) config.set("world.nether.wait-time-in-hours", 12); if(!config.contains("world.nether.name")) config.set("world.nether.name", "world_nether"); if(!config.contains("world.nether.pigman-gold-drop-chance")) config.set("world.nether.pigman-gold-drop-chance", 10); if(!config.contains("world.nether.gold-blocks-need")) config.set("world.nether.gold-blocks-needed", 1); if(!config.contains("world.main.name")) config.set("world.main.name", "world"); if(!config.contains("spawn.main-world.x")) //World spawn options - config.set("spawn.main.x", 100); + config.set("spawn.main.x", 0); if(!config.contains("spawn.main.y")) config.set("spawn.main.y", 64); if(!config.contains("spawn.main.z")) - config.set("spawn.main.z", 100); + config.set("spawn.main.z", 0); if(!config.contains("spawn.nether.x")) - config.set("spawn.nether.x", 100); + config.set("spawn.nether.x", 0); if(!config.contains("spawn.nether.y")) config.set("spawn.nether.y", 64); if(!config.contains("spawn.nether.z")) - config.set("spawn.nether.z", 100); + config.set("spawn.nether.z", 0); if(!config.contains("mysql.database.name")) //MySQL options config.set("mysql.database.name", "kingdoms"); if(!config.contains("mysql.database.username")) config.set("mysql.database.username", "root"); if(!config.contains("mysql.database.password")) config.set("mysql.database.password", "root"); if(!config.contains("mysql.server.address")) config.set("mysql.server.address", "localhost"); if(!config.contains("mysql.server.port")) config.set("mysql.server.port", 3306); save(); } private void save(){ try { config.save(file); } catch (IOException e) { e.printStackTrace(); } } public int getDaysUntilNextRegen(){ return getInt("world.nether.days-until-next-regen"); } public int getDropChance(){ return getInt("world.nether.pigman-gold-drop-chance"); } public String getMainWorldName(){ return getString("world.main.name"); } public Location getMainWorldSpawn(){ int x = getInt("spawn.main.x"); int y = getInt("spawn.main.y"); int z = getInt("spawn.main.z"); World world = Bukkit.getServer().getWorld(getMainWorldName()); return new Location(world, x, y, z); } public int getNeededGold(){ return getInt("world.nether.gold-blocks-needed"); } public String getMySqlDatabaseName(){ return getString("mysql.database.name"); } public String getMySqlDatabaseUsername(){ return getString("mysql.database.username"); } public String getMySqlDatabasePassword(){ return getString("mysql.database.password"); } public String getMySqlServerAddress(){ return getString("mysql.server.address"); } public int getMySqlServerPort(){ return getInt("mysql.server.port"); } public Location getNetherWorldSpawn(){ int x = getInt("spawn.nether.x"); int y = getInt("spawn.nether.y"); int z = getInt("spawn.nether.z"); World world = Bukkit.getServer().getWorld(getNetherWorldName()); return new Location(world, x, y, z); } public int getWaitTime(){ return getInt("world.nether.wait-time-in-hours") * 3600; } public String getNetherWorldName(){ return getString("world.nether.name"); } public String getString(String path){ return config.getString(path); } public int getInt(String path){ return config.getInt(path); } }
false
true
public void loadDefaults(){ if(!config.contains("world.nether.days-until-next-regen")) //World options config.set("world.nether.days-until-next-regen", 7); if(!config.contains("world.nether.wait-time-in-hours")) config.set("world.nether.wait-time-in-hours", 12); if(!config.contains("world.nether.name")) config.set("world.nether.name", "world_nether"); if(!config.contains("world.nether.pigman-gold-drop-chance")) config.set("world.nether.pigman-gold-drop-chance", 10); if(!config.contains("world.nether.gold-blocks-need")) config.set("world.nether.gold-blocks-needed", 1); if(!config.contains("world.main.name")) config.set("world.main.name", "world"); if(!config.contains("spawn.main-world.x")) //World spawn options config.set("spawn.main.x", 100); if(!config.contains("spawn.main.y")) config.set("spawn.main.y", 64); if(!config.contains("spawn.main.z")) config.set("spawn.main.z", 100); if(!config.contains("spawn.nether.x")) config.set("spawn.nether.x", 100); if(!config.contains("spawn.nether.y")) config.set("spawn.nether.y", 64); if(!config.contains("spawn.nether.z")) config.set("spawn.nether.z", 100); if(!config.contains("mysql.database.name")) //MySQL options config.set("mysql.database.name", "kingdoms"); if(!config.contains("mysql.database.username")) config.set("mysql.database.username", "root"); if(!config.contains("mysql.database.password")) config.set("mysql.database.password", "root"); if(!config.contains("mysql.server.address")) config.set("mysql.server.address", "localhost"); if(!config.contains("mysql.server.port")) config.set("mysql.server.port", 3306); save(); }
public void loadDefaults(){ if(!config.contains("world.nether.days-until-next-regen")) //World options config.set("world.nether.days-until-next-regen", 7); if(!config.contains("world.nether.wait-time-in-hours")) config.set("world.nether.wait-time-in-hours", 12); if(!config.contains("world.nether.name")) config.set("world.nether.name", "world_nether"); if(!config.contains("world.nether.pigman-gold-drop-chance")) config.set("world.nether.pigman-gold-drop-chance", 10); if(!config.contains("world.nether.gold-blocks-need")) config.set("world.nether.gold-blocks-needed", 1); if(!config.contains("world.main.name")) config.set("world.main.name", "world"); if(!config.contains("spawn.main-world.x")) //World spawn options config.set("spawn.main.x", 0); if(!config.contains("spawn.main.y")) config.set("spawn.main.y", 64); if(!config.contains("spawn.main.z")) config.set("spawn.main.z", 0); if(!config.contains("spawn.nether.x")) config.set("spawn.nether.x", 0); if(!config.contains("spawn.nether.y")) config.set("spawn.nether.y", 64); if(!config.contains("spawn.nether.z")) config.set("spawn.nether.z", 0); if(!config.contains("mysql.database.name")) //MySQL options config.set("mysql.database.name", "kingdoms"); if(!config.contains("mysql.database.username")) config.set("mysql.database.username", "root"); if(!config.contains("mysql.database.password")) config.set("mysql.database.password", "root"); if(!config.contains("mysql.server.address")) config.set("mysql.server.address", "localhost"); if(!config.contains("mysql.server.port")) config.set("mysql.server.port", 3306); save(); }
diff --git a/src/main/java/clisk/Util.java b/src/main/java/clisk/Util.java index 01371e3..a617886 100644 --- a/src/main/java/clisk/Util.java +++ b/src/main/java/clisk/Util.java @@ -1,225 +1,224 @@ package clisk; import java.awt.Dimension; import java.awt.FileDialog; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.StringReader; import javax.imageio.ImageIO; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import clojure.lang.Compiler; public class Util { /** * Create a new blank BufferedImage * @param w * @param h * @return */ public static BufferedImage newImage(int w, int h) { BufferedImage result=new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); return result; } public static BufferedImage scaleImage(BufferedImage img, int w, int h) { BufferedImage result=new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB); Graphics2D g=(Graphics2D) result.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g.drawImage(img, 0, 0, w, h, null); return result; } public static int clamp (int v) { if (v<0) return 0; if (v>255) return 255; return v; } public static int toARGB(double r, double g, double b) { return getARGBQuick( clamp((int)(r*256)), clamp((int)(g*256)), clamp((int)(b*256)), 255); } public static int toARGB(double r, double g, double b, double a) { return getARGBQuick( clamp((int)(r*256)), clamp((int)(g*256)), clamp((int)(b*256)), clamp((int)(a*256))); } public static int getARGBQuick(int r, int g, int b, int a) { return (a<<24)|(r<<16)|(g<<8)|b; } @SuppressWarnings("serial") public static JFrame frame(final BufferedImage image) { final JFrame f=new JFrame("Clisk Image"); - f.setAutoRequestFocus(false); // f.setFocusableWindowState(false); JMenuBar menuBar=new JMenuBar(); JMenu menu=new JMenu("File"); menuBar.add(menu); final JMenuItem jmi=new JMenuItem("Save As..."); menu.add(jmi); jmi.addActionListener(new ActionListener () { @Override public void actionPerformed(ActionEvent arg0) { FileDialog fileDialog = new FileDialog(f, "Save Image As...", FileDialog.SAVE); fileDialog.setFile("*.png"); fileDialog.setVisible(true); String fileName = fileDialog.getFile(); if (fileName !=null) { File outputFile=new File(fileDialog.getDirectory(), fileName); try { ImageIO.write(image, "png", outputFile); System.out.println("Saving: "+ outputFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } } }); JComponent c=new JComponent() { public void paint(Graphics g) { g.drawImage(image,0,0,null); } }; c.setMinimumSize(new Dimension(image.getWidth(null),image.getHeight(null))); f.setMinimumSize(new Dimension(image.getWidth(null)+20,image.getHeight(null)+100)); f.add(c); f.setJMenuBar(menuBar); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.pack(); return f; } /** * Shows an image in a new clisk JFrame * @param image * @return */ public static JFrame show(final BufferedImage image) { JFrame f=frame(image); f.setFocusable(false); f.setVisible(true); f.setFocusable(true); f.pack(); return f; } /** * Shows an image generated from the given script in a new clisk JFrame * @param script * @return */ public static JFrame show(String script) { return show(Generator.generate(script)); } public static final long longHash(long a) { a ^= (a << 21); a ^= (a >>> 35); a ^= (a << 4); return a; } public static final long hash (double x) { return longHash(longHash( 0x8000+Long.rotateLeft( longHash(Double.doubleToRawLongBits(x)),17))); } public static final long hash (double x, double y) { return longHash(longHash( hash(x)+Long.rotateLeft(longHash(Double.doubleToRawLongBits(y)),17))); } public static final long hash (double x, double y, double z) { return longHash(longHash( hash(x,y)+Long.rotateLeft(longHash(Double.doubleToRawLongBits(z)),17))); } public static final long hash (double x, double y, double z, double t) { return longHash(longHash( hash(x,y,z)+Long.rotateLeft(longHash(Double.doubleToRawLongBits(t)),17))); } private static final double LONG_SCALE_FACTOR=1.0/(Long.MAX_VALUE+1.0); public static final double dhash(double x) { long h = hash(x); return (h&Long.MAX_VALUE)*LONG_SCALE_FACTOR; } public static final double dhash(double x, double y) { long h = hash(x,y); return (h&Long.MAX_VALUE)*LONG_SCALE_FACTOR; } public static final double dhash(double x, double y, double z) { long h = hash(x,y,z); return (h&Long.MAX_VALUE)*LONG_SCALE_FACTOR; } public static final double dhash(double x, double y , double z, double t) { long h = hash(x,y,z,t); return (h&Long.MAX_VALUE)*LONG_SCALE_FACTOR; } public static Object execute(String script) { return Compiler.load(new StringReader(script)); } private static double componentFromPQT(double p, double q, double h) { h=Maths.mod(h, 1.0); if (h < 1.0/6.0) return p + (q - p) * 6.0 * h; if (h < 0.5) return q; if (h < 2.0/3.0) return p + (q - p) * (2.0/3.0 - h) * 6.0; return p; } public static double redFromHSL(double h, double s, double l) { if (s==0.0) return l; double q = (l < 0.5) ? (l * (1 + s)) : (l + s - l * s); double p = (2 * l) - q; return componentFromPQT(p, q, h + 1.0/3.0); } public static double greenFromHSL(double h, double s, double l) { if (s==0.0) return l; double q = (l < 0.5) ? (l * (1 + s)) : (l + s - l * s); double p = (2 * l) - q; return componentFromPQT(p, q, h); } public static double blueFromHSL(double h, double s, double l) { if (s==0.0) return l; double q = (l < 0.5) ? (l * (1 + s)) : (l + s - l * s); double p = (2 * l) - q; return componentFromPQT(p, q, h - 1.0/3.0); } }
true
true
public static JFrame frame(final BufferedImage image) { final JFrame f=new JFrame("Clisk Image"); f.setAutoRequestFocus(false); // f.setFocusableWindowState(false); JMenuBar menuBar=new JMenuBar(); JMenu menu=new JMenu("File"); menuBar.add(menu); final JMenuItem jmi=new JMenuItem("Save As..."); menu.add(jmi); jmi.addActionListener(new ActionListener () { @Override public void actionPerformed(ActionEvent arg0) { FileDialog fileDialog = new FileDialog(f, "Save Image As...", FileDialog.SAVE); fileDialog.setFile("*.png"); fileDialog.setVisible(true); String fileName = fileDialog.getFile(); if (fileName !=null) { File outputFile=new File(fileDialog.getDirectory(), fileName); try { ImageIO.write(image, "png", outputFile); System.out.println("Saving: "+ outputFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } } }); JComponent c=new JComponent() { public void paint(Graphics g) { g.drawImage(image,0,0,null); } }; c.setMinimumSize(new Dimension(image.getWidth(null),image.getHeight(null))); f.setMinimumSize(new Dimension(image.getWidth(null)+20,image.getHeight(null)+100)); f.add(c); f.setJMenuBar(menuBar); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.pack(); return f; }
public static JFrame frame(final BufferedImage image) { final JFrame f=new JFrame("Clisk Image"); // f.setFocusableWindowState(false); JMenuBar menuBar=new JMenuBar(); JMenu menu=new JMenu("File"); menuBar.add(menu); final JMenuItem jmi=new JMenuItem("Save As..."); menu.add(jmi); jmi.addActionListener(new ActionListener () { @Override public void actionPerformed(ActionEvent arg0) { FileDialog fileDialog = new FileDialog(f, "Save Image As...", FileDialog.SAVE); fileDialog.setFile("*.png"); fileDialog.setVisible(true); String fileName = fileDialog.getFile(); if (fileName !=null) { File outputFile=new File(fileDialog.getDirectory(), fileName); try { ImageIO.write(image, "png", outputFile); System.out.println("Saving: "+ outputFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } } }); JComponent c=new JComponent() { public void paint(Graphics g) { g.drawImage(image,0,0,null); } }; c.setMinimumSize(new Dimension(image.getWidth(null),image.getHeight(null))); f.setMinimumSize(new Dimension(image.getWidth(null)+20,image.getHeight(null)+100)); f.add(c); f.setJMenuBar(menuBar); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); f.pack(); return f; }
diff --git a/ini/trakem2/persistence/TMLHandler.java b/ini/trakem2/persistence/TMLHandler.java index 33610c7b..c1b02149 100644 --- a/ini/trakem2/persistence/TMLHandler.java +++ b/ini/trakem2/persistence/TMLHandler.java @@ -1,1029 +1,1030 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas. 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 (http://www.gnu.org/licenses/gpl.txt ) 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. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.persistence; import ij.IJ; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.LinkedList; import java.util.Set; import java.util.HashSet; import java.io.File; import java.util.regex.Pattern; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import ini.trakem2.tree.*; import ini.trakem2.display.*; import ini.trakem2.utils.*; import ini.trakem2.Project; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.InputSource; import org.xml.sax.Attributes; import mpicbg.models.TransformList; import mpicbg.trakem2.transform.CoordinateTransform; import mpicbg.trakem2.transform.CoordinateTransformList; import mpicbg.trakem2.transform.InvertibleCoordinateTransform; import mpicbg.trakem2.transform.InvertibleCoordinateTransformList; /** Creates the project objects from an XML file (TrakEM2 Markup Language Handler). */ public class TMLHandler extends DefaultHandler { private LayerThing root_lt = null; private ProjectThing root_pt = null; private TemplateThing root_tt = null; private TemplateThing project_tt = null; private TemplateThing template_layer_thing = null; private TemplateThing template_layer_set_thing = null; private Project project = null; private LayerSet layer_set = null; private final FSLoader loader; private boolean skip = false; private String base_dir; private String xml_path; /** Stores the object and its String with coma-separated links, to construct links when all objects exist. */ final private HashMap ht_links = new HashMap(); private Thing current_thing = null; final private ArrayList al_open = new ArrayList(); final private ArrayList<Layer> al_layers = new ArrayList<Layer>(); final private ArrayList<LayerSet> al_layer_sets = new ArrayList<LayerSet>(); final private ArrayList<HashMap> al_displays = new ArrayList<HashMap>(); // contains HashMap instances with display data. /** To accumulate Displayable types for relinking and assigning their proper layer. */ final private HashMap ht_displayables = new HashMap(); final private HashMap ht_zdispl = new HashMap(); final private HashMap ht_oid_pt = new HashMap(); final private HashMap<ProjectThing,Boolean> ht_pt_expanded = new HashMap<ProjectThing,Boolean>(); private Ball last_ball = null; private AreaList last_area_list = null; private long last_area_list_layer_id = -1; private Dissector last_dissector = null; private Stack last_stack = null; private Patch last_patch = null; private Treeline last_treeline = null; private AreaTree last_areatree = null; private Connector last_connector = null; private Tree last_tree = null; final private LinkedList<Taggable> taggables = new LinkedList<Taggable>(); private ReconstructArea reca = null; private Node last_root_node = null; final private LinkedList<Node> nodes = new LinkedList<Node>(); final private Map<Long,List<Node>> node_layer_table = new HashMap<Long,List<Node>>(); final private Map<Tree,Node> tree_root_nodes = new HashMap<Tree,Node>(); private StringBuilder last_treeline_data = null; private Displayable last_displayable = null; private StringBuilder last_annotation = null; final private ArrayList< TransformList< Object > > ct_list_stack = new ArrayList< TransformList< Object > >(); private boolean open_displays = true; final private LinkedList<Runnable> legacy = new LinkedList<Runnable>(); /** @param path The XML file that contains the project data in XML format. * @param loader The FSLoader for the project. * Expects the path with '/' as folder separator char. */ public TMLHandler(final String path, FSLoader loader) { this.loader = loader; this.base_dir = path.substring(0, path.lastIndexOf('/') + 1); // not File.separatorChar: TrakEM2 uses '/' always this.xml_path = path; final TemplateThing[] tt; try { tt = DTDParser.extractTemplate(path); if (null == tt) { Utils.log("TMLHandler: can't read DTD in file " + path); loader = null; return; } } catch (Exception e) { loader = null; IJError.print(e); return; } /* // debug: Utils.log2("ROOTS #####################"); for (int k=0; k < tt.length; k++) { Utils.log2("tt root " + k + ": " + tt[k]); } */ this.root_tt = tt[0]; // There should only be one root. There may be more than one // when objects in the DTD are declared but do not exist in a // TemplateThing hierarchy, such as ict_* and iict_*. // Find the first proper root: if (tt.length > 1) { final Pattern icts = Pattern.compile("^i{1,2}ct_transform.*$"); this.root_tt = null; for (int k=0; k<tt.length; k++) { if (icts.matcher(tt[k].getType()).matches()) { continue; } this.root_tt = tt[k]; break; } } // TODO the above should be a better filtering rule in the DTDParser. // create LayerThing templates this.template_layer_thing = new TemplateThing("layer"); this.template_layer_set_thing = new TemplateThing("layer set"); this.template_layer_set_thing.addChild(this.template_layer_thing); this.template_layer_thing.addChild(this.template_layer_set_thing); // create Project template this.project_tt = new TemplateThing("project"); project_tt.addChild(this.root_tt); project_tt.addAttribute("title", "Project"); } public boolean isUnreadable() { return null == loader; } /** returns 4 objects packed in an array: <pre> [0] = root TemplateThing [1] = root ProjectThing (contains Project instance) [2] = root LayerThing (contains the top-level LayerSet) [3] = expanded states of all ProjectThing objects </pre> * <br /> * Also, triggers the reconstruction of links and assignment of Displayable objects to their layer. */ public Object[] getProjectData(final boolean open_displays) { if (null == project) return null; this.open_displays = open_displays; // 1 - Reconstruct links using ht_links // Links exist between Displayable objects. for (Iterator it = ht_displayables.values().iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); Object olinks = ht_links.get(d); if (null == olinks) continue; // not linked String[] links = ((String)olinks).split(","); Long lid = null; for (int i=0; i<links.length; i++) { try { lid = new Long(links[i]); } catch (NumberFormatException nfe) { Utils.log2("Ignoring incorrectly formated link '" + links[i] + "' for ob " + d); continue; } Displayable partner = (Displayable)ht_displayables.get(lid); if (null != partner) d.link(partner, false); else Utils.log("TMLHandler: can't find partner with id=" + links[i] + " for Displayable with id=" + d.getId()); } } // 1.2 - Reconstruct linked properties for (final Map.Entry<Displayable,Map<Long,Map<String,String>>> lpe : all_linked_props.entrySet()) { final Displayable origin = lpe.getKey(); for (final Map.Entry<Long,Map<String,String>> e : lpe.getValue().entrySet()) { final Displayable target = (Displayable)ht_displayables.get(e.getKey()); if (null == target) { Utils.log("Setting linked properties for origin " + origin.getId() + ":\n\t* Could not find target displayable #" + e.getKey()); continue; } origin.setLinkedProperties(target, e.getValue()); } } // 2 - Add Displayable objects to ProjectThing that can contain them for (Iterator it = ht_oid_pt.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); Long lid = (Long)entry.getKey(); ProjectThing pt = (ProjectThing)entry.getValue(); Object od = ht_displayables.remove(lid); //Utils.log("==== processing: Displayable [" + od + "] vs. ProjectThing [" + pt + "]"); if (null != od) { pt.setObject(od); } else { Utils.log("#### Failed to find a Displayable for ProjectThing " + pt + " #####"); } } // debug: /* for (Iterator it = al_layer_sets.iterator(); it.hasNext(); ) { LayerSet ls = (LayerSet)it.next(); Utils.log2("ls #id " + ls.getId() + " size: " +ls.getLayers().size()); } */ // 3 - Assign a layer pointer to ZDisplayable objects for (Iterator it = ht_zdispl.values().iterator(); it.hasNext(); ) { ZDisplayable zd = (ZDisplayable)it.next(); //zd.setLayer((Layer)zd.getLayerSet().getLayers().get(0)); zd.setLayer(zd.getLayerSet().getLayer(0)); } // 4 - Assign layers to Treeline nodes for (final Layer la : al_layers) { final List<Node> list = node_layer_table.remove(la.getId()); if (null == list) continue; for (final Node nd : list) nd.setLayer(la); } if (!node_layer_table.isEmpty()) { Utils.log("ERROR: node_layer_table is not empty!"); } // 5 - Assign root nodes to Treelines, now that all nodes have a layer for (final Map.Entry<Tree,Node> e : tree_root_nodes.entrySet()) { if (null == e.getValue()) { //Utils.log2("Ignoring, applies to new Treeline format only."); continue; } e.getKey().setRoot(e.getValue()); // will generate node caches of each Treeline } tree_root_nodes.clear(); // 6 - Run legacy operations for (final Runnable r : legacy) { r.run(); } try { // Create a table with all layer ids vs layer instances: final HashMap<Long,Layer> ht_lids = new HashMap<Long,Layer>(); for (final Layer layer : al_layers) { ht_lids.put(new Long(layer.getId()), layer); } // Spawn threads to recreate buckets, starting from the subset of displays to open int n = Runtime.getRuntime().availableProcessors(); if (n > 1) n /= 2; final ExecutorService exec = Utils.newFixedThreadPool(n, "TMLHandler-recreateBuckets"); final Set<Long> dlids = new HashSet(); final LayerSet layer_set = (LayerSet) root_lt.getObject(); final List<Future> fus = new ArrayList<Future>(); final List<Future> fus2 = new ArrayList<Future>(); for (final HashMap ht_attributes : al_displays) { Object ob = ht_attributes.get("layer_id"); if (null == ob) continue; final Long lid = new Long((String)ob); dlids.add(lid); final Layer la = ht_lids.get(lid); if (null == la) { ht_lids.remove(lid); continue; } // to open later: new Display(project, Long.parseLong((String)ht_attributes.get("id")), la, ht_attributes); fus.add(exec.submit(new Runnable() { public void run() { la.recreateBuckets(); }})); } fus.add(exec.submit(new Runnable() { public void run() { layer_set.recreateBuckets(false); // only for ZDisplayable }})); // Ensure launching: if (dlids.isEmpty() && layer_set.size() > 0) { dlids.add(layer_set.getLayer(0).getId()); } final List<Layer> layers = layer_set.getLayers(); for (final Long lid : new HashSet<Long>(dlids)) { fus.add(exec.submit(new Runnable() { public void run() { int start = layers.indexOf(layer_set.getLayer(lid.longValue())); int next = start + 1; int prev = start -1; while (next < layer_set.size() || prev > -1) { if (prev > -1) { final Layer lprev = layers.get(prev); synchronized (dlids) { if (dlids.add(lprev.getId())) { // returns true if not there already fus2.add(exec.submit(new Runnable() { public void run() { lprev.recreateBuckets(); }})); } } prev--; } if (next < layers.size()) { final Layer lnext = layers.get(next); synchronized (dlids) { if (dlids.add(lnext.getId())) { // returns true if not there already fus2.add(exec.submit(new Runnable() { public void run() { lnext.recreateBuckets(); }})); } } next++; } } Utils.log2("done recreateBuckets chunk"); }})); } Utils.wait(fus); exec.submit(new Runnable() { public void run() { Utils.log2("waiting for TMLHandler fus..."); Utils.wait(fus2); Utils.log2("done waiting TMLHandler fus."); exec.shutdown(); }}); } catch (Throwable t) { IJError.print(t); } // debug: //root_tt.debug(""); //root_pt.debug(""); //root_lt.debug(""); return new Object[]{root_tt, root_pt, root_lt, ht_pt_expanded}; } private int counter = 0; public void startElement(String namespace_URI, String local_name, String qualified_name, Attributes attributes) throws SAXException { if (null == loader) return; //Utils.log2("startElement: " + qualified_name); this.counter++; if (0 == counter % 100) { // davi-experimenting: don't talk so much when you have > 600,000 patches to load! Utils.showStatus("Loading " + counter, false); } try { // failsafe: qualified_name = qualified_name.toLowerCase(); HashMap ht_attributes = new HashMap(); for (int i=attributes.getLength() -1; i>-1; i--) { ht_attributes.put(attributes.getQName(i).toLowerCase(), attributes.getValue(i)); } // get the id, which whenever possible it's the id of the encapsulating Thing object. The encapsulated object id is the oid // The type is specified by the qualified_name Thing thing = null; if (0 == qualified_name.indexOf("t2_")) { if (qualified_name.equals("t2_display")) { if (open_displays) al_displays.add(ht_attributes); // store for later, until the layers exist } else { // a Layer, LayerSet or Displayable object thing = makeLayerThing(qualified_name, ht_attributes); if (null != thing) { if (null == root_lt && thing.getObject() instanceof LayerSet) { root_lt = (LayerThing)thing; } } } } else if (qualified_name.equals("project")) { if (null != this.root_pt) { Utils.log("WARNING: more than one project definitions."); return; } // Create the project this.project = new Project(Long.parseLong((String)ht_attributes.remove("id")), (String)ht_attributes.remove("title")); this.project.setTempLoader(this.loader); // temp, but will be the same anyway this.project.parseXMLOptions(ht_attributes); this.project.addToDatabase(); // register id // Add all unique TemplateThing types to the project for (Iterator it = root_tt.getUniqueTypes(new HashMap()).values().iterator(); it.hasNext(); ) { this.project.addUniqueType((TemplateThing)it.next()); } this.project.addUniqueType(this.project_tt); this.root_pt = new ProjectThing(this.project_tt, this.project, this.project); this.root_pt.addAttribute("title", ht_attributes.get("title")); // Add a project pointer to all template things this.root_tt.addToDatabase(this.project); thing = root_pt; } else if (qualified_name.startsWith("ict_transform")||qualified_name.startsWith("iict_transform")) { makeCoordinateTransform(qualified_name, ht_attributes); } else if (!qualified_name.equals("trakem2")) { // Any abstract object thing = makeProjectThing(qualified_name, ht_attributes); } if (null != thing) { // get the previously open thing and add this new_thing to it as a child int size = al_open.size(); if (size > 0) { Thing parent = (Thing)al_open.get(size -1); parent.addChild(thing); //Utils.log2("Adding child " + thing + " to parent " + parent); } // add the new thing as open al_open.add(thing); } } catch (Exception e) { IJError.print(e); skip = true; } } public void endElement(String namespace_URI, String local_name, String qualified_name) { if (null == loader) return; if (skip) { skip = false; // reset return; } String orig_qualified_name = qualified_name; //Utils.log2("endElement: " + qualified_name); // iterate over all open things and find the one that matches the qualified_name, and set it closed (pop it out of the list): qualified_name = qualified_name.toLowerCase().trim(); if (0 == qualified_name.indexOf("t2_")) { qualified_name = qualified_name.substring(3); } for (int i=al_open.size() -1; i>-1; i--) { Thing thing = (Thing)al_open.get(i); if (thing.getType().toLowerCase().equals(qualified_name)) { al_open.remove(thing); break; } } if (null != last_annotation && null != last_displayable) { last_displayable.setAnnotation(last_annotation.toString().trim().replaceAll("&lt;", "<")); last_annotation = null; } // terminate non-single clause objects if (orig_qualified_name.equals("t2_node")) { // Remove one node from the stack nodes.removeLast(); taggables.removeLast(); } else if (orig_qualified_name.equals("t2_connector")) { if (null != last_connector) { tree_root_nodes.put(last_connector, last_root_node); last_root_node = null; last_connector = null; last_tree = null; nodes.clear(); } last_displayable = null; } else if (orig_qualified_name.equals("t2_area_list")) { last_area_list = null; last_displayable = null; } else if (orig_qualified_name.equals("t2_area")) { if (null != reca) { if (null != last_area_list) { last_area_list.addArea(last_area_list_layer_id, reca.getArea()); // it's local } else { ((AreaTree.AreaNode)nodes.getLast()).setData(reca.getArea()); } reca = null; } } else if (orig_qualified_name.equals("ict_transform_list")) { ct_list_stack.remove( ct_list_stack.size() - 1 ); } else if (orig_qualified_name.equals("t2_patch")) { last_patch = null; last_displayable = null; } else if (orig_qualified_name.equals("t2_ball")) { last_ball = null; last_displayable = null; } else if (orig_qualified_name.equals("t2_dissector")) { last_dissector = null; last_displayable = null; } else if (orig_qualified_name.equals("t2_treeline")) { if (null != last_treeline) { // old format: if (null == last_root_node && null != last_treeline_data && last_treeline_data.length() > 0) { last_root_node = parseBranch(Utils.trim(last_treeline_data)); last_treeline_data = null; } // new tree_root_nodes.put(last_treeline, last_root_node); last_root_node = null; // always: last_treeline = null; last_tree = null; nodes.clear(); } last_displayable = null; } else if (orig_qualified_name.equals("t2_areatree")) { if (null != last_areatree) { tree_root_nodes.put(last_areatree, last_root_node); last_root_node = null; last_areatree = null; last_tree = null; nodes.clear(); // the absence of this line would have made the nodes list grow with all nodes of all areatrees, which is ok but consumes memory } last_displayable = null; } else if (orig_qualified_name.equals( "t2_stack" )) { last_stack = null; last_displayable = null; } else if (in(orig_qualified_name, all_displayables)) { last_displayable = null; } } static private final String[] all_displayables = new String[]{"t2_area_list", "t2_patch", "t2_pipe", "t2_polyline", "t2_ball", "t2_label", "t2_dissector", "t2_profile", "t2_stack", "t2_treeline", "t2_areatree", "t2_connector"}; private final boolean in(final String s, final String[] all) { for (int i=all.length-1; i>-1; i--) { if (s.equals(all[i])) return true; } return false; } public void characters(char[] c, int start, int length) { if (null != last_treeline) { // for old format: last_treeline_data.append(c, start, length); } if (null != last_annotation) { last_annotation.append(c, start, length); } } public void fatalError(SAXParseException e) { Utils.log("Fatal error: column=" + e.getColumnNumber() + " line=" + e.getLineNumber()); } public void skippedEntity(String name) { Utils.log("SAX Parser has skipped: " + name); } public void notationDeclaration(String name, String publicId, String systemId) { Utils.log("Notation declaration: " + name + ", " + publicId + ", " + systemId); } public void warning(SAXParseException e) { Utils.log("SAXParseException : " + e); } private ProjectThing makeProjectThing(String type, HashMap ht_attributes) { try { type = type.toLowerCase(); // debug: //Utils.log2("TMLHander.makeProjectThing for type=" + type); long id = -1; Object sid = ht_attributes.remove("id"); if (null != sid) { id = Long.parseLong((String)sid); } long oid = -1; Object soid = ht_attributes.remove("oid"); if (null != soid) { oid = Long.parseLong((String)soid); } Boolean expanded = new Boolean(false); // default: collapsed Object eob = ht_attributes.remove("expanded"); if (null != eob) { expanded = new Boolean((String)eob); } // abstract object, including profile_list HashMap ht_attr = new HashMap(); for (Iterator it = ht_attributes.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); String key = (String)entry.getKey(); String data = (String)entry.getValue(); ht_attr.put(key, new ProjectAttribute(this.project, -1, key, data)); //Utils.log2("putting key=[" + key + "]=" + data); } TemplateThing tt = this.project.getTemplateThing(type); if (null == tt) { Utils.log("No template for type " + type); return null; } ProjectThing pt = new ProjectThing(tt, this.project, id, type, null, ht_attr); pt.addToDatabase(); ht_pt_expanded.put(pt, expanded); // store the oid vs. pt relationship to fill in the object later. if (-1 != oid) { ht_oid_pt.put(new Long(oid), pt); } return pt; } catch (Exception e) { IJError.print(e); } // default: return null; } private void addToLastOpenLayer(Displayable d) { // find last open layer for (int i = al_layers.size() -1; i>-1; i--) { ((Layer)al_layers.get(i)).addSilently(d); break; } } private void addToLastOpenLayerSet(ZDisplayable zd) { // find last open layer set for (int i = al_layer_sets.size() -1; i>-1; i--) { al_layer_sets.get(i).addSilently(zd); break; } } final private Map<Displayable,Map<Long,Map<String,String>>> all_linked_props = new HashMap<Displayable,Map<Long,Map<String,String>>>(); private void putLinkedProperty(final Displayable origin, final HashMap ht_attributes) { final String stid = (String)ht_attributes.get("target_id"); if (null == stid) { Utils.log2("Can't setLinkedProperty to null target id for origin Displayable " + origin.getId()); return; } Long target_id; try { target_id = Long.parseLong(stid); } catch (NumberFormatException e) { Utils.log2("Unparseable target_id: " + stid + ", for origin " + origin.getId()); return; } String key = (String)ht_attributes.get("key"); String value = (String)ht_attributes.get("value"); if (null == key || null == value) { Utils.log("Skipping linked property for Displayable " + origin.getId() + ": null key or value"); return; } key = key.trim(); value = value.trim(); if (0 == key.length() || 0 == value.length()) { Utils.log("Skipping linked property for Displayable " + origin.getId() + ": empty key or value"); return; } Map<Long,Map<String,String>> linked_props = all_linked_props.get(origin); if (null == linked_props) { linked_props = new HashMap<Long,Map<String,String>>(); all_linked_props.put(origin, linked_props); } Map<String,String> p = linked_props.get(target_id); if (null == p) { p = new HashMap<String,String>(); linked_props.put(target_id, p); } p.put(key, value); } private LayerThing makeLayerThing(String type, final HashMap ht_attributes) { try { type = type.toLowerCase(); if (0 == type.indexOf("t2_")) { type = type.substring(3); } long id = -1; Object sid = ht_attributes.get("id"); if (null != sid) id = Long.parseLong((String)sid); long oid = -1; Object soid = ht_attributes.get("oid"); if (null != soid) oid = Long.parseLong((String)soid); if (type.equals("node")) { if (null == last_tree) { throw new NullPointerException("Can't create a node for null last_tree!"); } final Node node = last_tree.newNode(ht_attributes); taggables.add(node); // Put node into the list of nodes with that layer id, to update to proper Layer pointer later final long ndlid = Long.parseLong((String)ht_attributes.get("lid")); List<Node> list = node_layer_table.get(ndlid); if (null == list) { list = new ArrayList<Node>(); node_layer_table.put(ndlid, list); } list.add(node); // Set node as root node or add as child to last node in the stack if (null == last_root_node) { last_root_node = node; } else { nodes.getLast().add(node, Byte.parseByte((String)ht_attributes.get("c"))); } // Put node into stack of nodes (to be removed on closing the tag) nodes.add(node); } else if (type.equals("profile")) { Profile profile = new Profile(this.project, oid, ht_attributes, ht_links); profile.addToDatabase(); ht_displayables.put(new Long(oid), profile); addToLastOpenLayer(profile); last_displayable = profile; return null; } else if (type.equals("pipe")) { Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links); pipe.addToDatabase(); ht_displayables.put(new Long(oid), pipe); ht_zdispl.put(new Long(oid), pipe); last_displayable = pipe; addToLastOpenLayerSet(pipe); return null; } else if (type.equals("polyline")) { Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links); pline.addToDatabase(); last_displayable = pline; ht_displayables.put(new Long(oid), pline); ht_zdispl.put(new Long(oid), pline); addToLastOpenLayerSet(pline); return null; } else if (type.equals("connector")) { final Connector con = new Connector(this.project, oid, ht_attributes, ht_links); if (ht_attributes.containsKey("origin")) { legacy.add(new Runnable() { public void run() { con.readLegacyXML(al_layer_sets.get(al_layer_sets.size()-1), ht_attributes, ht_links); } }); } con.addToDatabase(); last_connector = con; + last_tree = con; last_displayable = con; ht_displayables.put(new Long(oid), con); ht_zdispl.put(new Long(oid), con); addToLastOpenLayerSet(con); return null; } else if (type.equals("path")) { if (null != reca) { reca.add((String)ht_attributes.get("d")); return null; } return null; } else if (type.equals("area")) { reca = new ReconstructArea(); if (null != last_area_list) { last_area_list_layer_id = Long.parseLong((String)ht_attributes.get("layer_id")); } return null; } else if (type.equals("area_list")) { AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links); area.addToDatabase(); // why? This looks like an onion last_area_list = area; last_displayable = area; ht_displayables.put(new Long(oid), area); ht_zdispl.put(new Long(oid), area); addToLastOpenLayerSet(area); return null; } else if (type.equals("tag")) { Taggable t = taggables.getLast(); if (null != t) { Object ob = ht_attributes.get("key"); int keyCode = KeyEvent.VK_T; // defaults to 't' if (null != ob) keyCode = (int)((String)ob).toUpperCase().charAt(0); // KeyEvent.VK_U is char U, not u Tag tag = new Tag(ht_attributes.get("name"), keyCode); al_layer_sets.get(al_layer_sets.size()-1).putTag(tag, keyCode); t.addTag(tag); } } else if (type.equals("ball_ob")) { // add a ball to the last open Ball if (null != last_ball) { last_ball.addBall(Double.parseDouble((String)ht_attributes.get("x")), Double.parseDouble((String)ht_attributes.get("y")), Double.parseDouble((String)ht_attributes.get("r")), Long.parseLong((String)ht_attributes.get("layer_id"))); } return null; } else if (type.equals("ball")) { Ball ball = new Ball(this.project, oid, ht_attributes, ht_links); ball.addToDatabase(); last_ball = ball; last_displayable = ball; ht_displayables.put(new Long(oid), ball); ht_zdispl.put(new Long(oid), ball); addToLastOpenLayerSet(ball); return null; } else if (type.equals("stack")) { Stack stack = new Stack(this.project, oid, ht_attributes, ht_links); stack.addToDatabase(); last_stack = stack; last_displayable = stack; ht_displayables.put(new Long(oid), stack); ht_zdispl.put( new Long(oid), stack ); addToLastOpenLayerSet( stack ); } else if (type.equals("treeline")) { Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links); tline.addToDatabase(); last_treeline = tline; last_tree = tline; last_treeline_data = new StringBuilder(); last_displayable = tline; ht_displayables.put(oid, tline); ht_zdispl.put(oid, tline); addToLastOpenLayerSet(tline); } else if (type.equals("areatree")) { AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links); art.addToDatabase(); last_areatree = art; last_tree = art; last_displayable = art; ht_displayables.put(oid, art); ht_zdispl.put(oid, art); addToLastOpenLayerSet(art); } else if (type.equals("dd_item")) { if (null != last_dissector) { last_dissector.addItem(Integer.parseInt((String)ht_attributes.get("tag")), Integer.parseInt((String)ht_attributes.get("radius")), (String)ht_attributes.get("points")); } } else if (type.equals("label")) { DLabel label = new DLabel(project, oid, ht_attributes, ht_links); label.addToDatabase(); ht_displayables.put(new Long(oid), label); addToLastOpenLayer(label); last_displayable = label; return null; } else if (type.equals("annot")) { last_annotation = new StringBuilder(); return null; } else if (type.equals("patch")) { Patch patch = new Patch(project, oid, ht_attributes, ht_links); patch.addToDatabase(); ht_displayables.put(new Long(oid), patch); addToLastOpenLayer(patch); last_patch = patch; last_displayable = patch; return null; } else if (type.equals("dissector")) { Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links); dissector.addToDatabase(); last_dissector = dissector; last_displayable = dissector; ht_displayables.put(new Long(oid), dissector); ht_zdispl.put(new Long(oid), dissector); addToLastOpenLayerSet(dissector); } else if (type.equals("layer")) { // find last open LayerSet, if any for (int i = al_layer_sets.size() -1; i>-1; i--) { LayerSet set = (LayerSet)al_layer_sets.get(i); Layer layer = new Layer(project, oid, ht_attributes); layer.addToDatabase(); set.addSilently(layer); al_layers.add(layer); Object ot = ht_attributes.get("title"); return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String)ot), layer, null, null); } } else if (type.equals("layer_set")) { LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links); last_displayable = set; set.addToDatabase(); ht_displayables.put(new Long(oid), set); al_layer_sets.add(set); addToLastOpenLayer(set); Object ot = ht_attributes.get("title"); return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String)ot), set, null, null); } else if (type.equals("calibration")) { // find last open LayerSet if any for (int i = al_layer_sets.size() -1; i>-1; i--) { LayerSet set = (LayerSet)al_layer_sets.get(i); set.restoreCalibration(ht_attributes); return null; } } else if (type.equals("prop")) { // Add property to last created Displayable if (null != last_displayable) { last_displayable.setProperty((String)ht_attributes.get("key"), (String)ht_attributes.get("value")); } } else if (type.equals("linked_prop")) { // Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances. if (null != last_displayable) { putLinkedProperty(last_displayable, ht_attributes); } } else { Utils.log2("TMLHandler Unknown type: " + type); } } catch (Exception e) { IJError.print(e); } // default: return null; } final private void makeCoordinateTransform( String type, final HashMap ht_attributes ) { try { type = type.toLowerCase(); if ( type.equals( "ict_transform" ) ) { final CoordinateTransform ct = ( CoordinateTransform )Class.forName( ( String )ht_attributes.get( "class" ) ).newInstance(); ct.init( ( String )ht_attributes.get( "data" ) ); if ( ct_list_stack.isEmpty() ) { if ( last_patch != null ) last_patch.setCoordinateTransformSilently( ct ); } else { ct_list_stack.get( ct_list_stack.size() - 1 ).add( ct ); } } else if ( type.equals( "iict_transform" ) ) { final InvertibleCoordinateTransform ict = ( InvertibleCoordinateTransform )Class.forName( ( String )ht_attributes.get( "class" ) ).newInstance(); ict.init( ( String )ht_attributes.get( "data" ) ); if ( ct_list_stack.isEmpty() ) { if ( last_patch != null ) last_patch.setCoordinateTransformSilently( ict ); else if ( last_stack != null ) last_stack.setInvertibleCoordinateTransformSilently( ict ); } else { ct_list_stack.get( ct_list_stack.size() - 1 ).add( ict ); } } else if ( type.equals( "ict_transform_list" ) ) { final CoordinateTransformList< CoordinateTransform > ctl = new CoordinateTransformList< CoordinateTransform >(); if ( ct_list_stack.isEmpty() ) { if ( last_patch != null ) last_patch.setCoordinateTransformSilently( ctl ); } else ct_list_stack.get( ct_list_stack.size() - 1 ).add( ctl ); ct_list_stack.add( ( TransformList )ctl ); } else if ( type.equals( "iict_transform_list" ) ) { final InvertibleCoordinateTransformList< InvertibleCoordinateTransform > ictl = new InvertibleCoordinateTransformList< InvertibleCoordinateTransform >(); if ( ct_list_stack.isEmpty() ) { if ( last_patch != null ) last_patch.setCoordinateTransformSilently( ictl ); else if ( last_stack != null ) last_stack.setInvertibleCoordinateTransformSilently( ictl ); } else ct_list_stack.get( ct_list_stack.size() - 1 ).add( ictl ); ct_list_stack.add( ( TransformList )ictl ); } } catch ( Exception e ) { IJError.print(e); } } private final Node parseBranch(String s) { // 1 - Parse the slab final int first = s.indexOf('('); final int last = s.indexOf(')', first+1); final String[] coords = s.substring(first+1, last).split(" "); Node prev = null; final List<Node> nodes = new ArrayList<Node>(); for (int i=0; i<coords.length; i+=3) { long lid = Long.parseLong(coords[i+2]); Node nd = new Treeline.RadiusNode(Float.parseFloat(coords[i]), Float.parseFloat(coords[i+1]), null); nd.setData(0f); nodes.add(nd); // Add to node_layer_table for later assignment of a Layer object to the node List<Node> list = node_layer_table.get(lid); if (null == list) { list = new ArrayList<Node>(); node_layer_table.put(lid, list); } list.add(nd); // if (null == prev) prev = nd; else { prev.add(nd, Node.MAX_EDGE_CONFIDENCE); prev = nd; // new parent } } // 2 - Parse the branches final int ibranches = s.indexOf(":branches", last+1); if (-1 != ibranches) { final int len = s.length(); int open = s.indexOf('{', ibranches + 9); while (-1 != open) { int end = open + 1; // don't read the first curly bracket int level = 1; for(; end < len; end++) { switch (s.charAt(end)) { case '{': level++; break; case '}': level--; break; } if (0 == level) break; } // Add the root node of the new branch to the node at branch index int openbranch = s.indexOf('{', open+1); int branchindex = Integer.parseInt(s.substring(open+1, openbranch-1)); nodes.get(branchindex).add(parseBranch(s.substring(open, end)), Node.MAX_EDGE_CONFIDENCE); open = s.indexOf('{', end+1); } } return nodes.get(0); } }
true
true
private LayerThing makeLayerThing(String type, final HashMap ht_attributes) { try { type = type.toLowerCase(); if (0 == type.indexOf("t2_")) { type = type.substring(3); } long id = -1; Object sid = ht_attributes.get("id"); if (null != sid) id = Long.parseLong((String)sid); long oid = -1; Object soid = ht_attributes.get("oid"); if (null != soid) oid = Long.parseLong((String)soid); if (type.equals("node")) { if (null == last_tree) { throw new NullPointerException("Can't create a node for null last_tree!"); } final Node node = last_tree.newNode(ht_attributes); taggables.add(node); // Put node into the list of nodes with that layer id, to update to proper Layer pointer later final long ndlid = Long.parseLong((String)ht_attributes.get("lid")); List<Node> list = node_layer_table.get(ndlid); if (null == list) { list = new ArrayList<Node>(); node_layer_table.put(ndlid, list); } list.add(node); // Set node as root node or add as child to last node in the stack if (null == last_root_node) { last_root_node = node; } else { nodes.getLast().add(node, Byte.parseByte((String)ht_attributes.get("c"))); } // Put node into stack of nodes (to be removed on closing the tag) nodes.add(node); } else if (type.equals("profile")) { Profile profile = new Profile(this.project, oid, ht_attributes, ht_links); profile.addToDatabase(); ht_displayables.put(new Long(oid), profile); addToLastOpenLayer(profile); last_displayable = profile; return null; } else if (type.equals("pipe")) { Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links); pipe.addToDatabase(); ht_displayables.put(new Long(oid), pipe); ht_zdispl.put(new Long(oid), pipe); last_displayable = pipe; addToLastOpenLayerSet(pipe); return null; } else if (type.equals("polyline")) { Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links); pline.addToDatabase(); last_displayable = pline; ht_displayables.put(new Long(oid), pline); ht_zdispl.put(new Long(oid), pline); addToLastOpenLayerSet(pline); return null; } else if (type.equals("connector")) { final Connector con = new Connector(this.project, oid, ht_attributes, ht_links); if (ht_attributes.containsKey("origin")) { legacy.add(new Runnable() { public void run() { con.readLegacyXML(al_layer_sets.get(al_layer_sets.size()-1), ht_attributes, ht_links); } }); } con.addToDatabase(); last_connector = con; last_displayable = con; ht_displayables.put(new Long(oid), con); ht_zdispl.put(new Long(oid), con); addToLastOpenLayerSet(con); return null; } else if (type.equals("path")) { if (null != reca) { reca.add((String)ht_attributes.get("d")); return null; } return null; } else if (type.equals("area")) { reca = new ReconstructArea(); if (null != last_area_list) { last_area_list_layer_id = Long.parseLong((String)ht_attributes.get("layer_id")); } return null; } else if (type.equals("area_list")) { AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links); area.addToDatabase(); // why? This looks like an onion last_area_list = area; last_displayable = area; ht_displayables.put(new Long(oid), area); ht_zdispl.put(new Long(oid), area); addToLastOpenLayerSet(area); return null; } else if (type.equals("tag")) { Taggable t = taggables.getLast(); if (null != t) { Object ob = ht_attributes.get("key"); int keyCode = KeyEvent.VK_T; // defaults to 't' if (null != ob) keyCode = (int)((String)ob).toUpperCase().charAt(0); // KeyEvent.VK_U is char U, not u Tag tag = new Tag(ht_attributes.get("name"), keyCode); al_layer_sets.get(al_layer_sets.size()-1).putTag(tag, keyCode); t.addTag(tag); } } else if (type.equals("ball_ob")) { // add a ball to the last open Ball if (null != last_ball) { last_ball.addBall(Double.parseDouble((String)ht_attributes.get("x")), Double.parseDouble((String)ht_attributes.get("y")), Double.parseDouble((String)ht_attributes.get("r")), Long.parseLong((String)ht_attributes.get("layer_id"))); } return null; } else if (type.equals("ball")) { Ball ball = new Ball(this.project, oid, ht_attributes, ht_links); ball.addToDatabase(); last_ball = ball; last_displayable = ball; ht_displayables.put(new Long(oid), ball); ht_zdispl.put(new Long(oid), ball); addToLastOpenLayerSet(ball); return null; } else if (type.equals("stack")) { Stack stack = new Stack(this.project, oid, ht_attributes, ht_links); stack.addToDatabase(); last_stack = stack; last_displayable = stack; ht_displayables.put(new Long(oid), stack); ht_zdispl.put( new Long(oid), stack ); addToLastOpenLayerSet( stack ); } else if (type.equals("treeline")) { Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links); tline.addToDatabase(); last_treeline = tline; last_tree = tline; last_treeline_data = new StringBuilder(); last_displayable = tline; ht_displayables.put(oid, tline); ht_zdispl.put(oid, tline); addToLastOpenLayerSet(tline); } else if (type.equals("areatree")) { AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links); art.addToDatabase(); last_areatree = art; last_tree = art; last_displayable = art; ht_displayables.put(oid, art); ht_zdispl.put(oid, art); addToLastOpenLayerSet(art); } else if (type.equals("dd_item")) { if (null != last_dissector) { last_dissector.addItem(Integer.parseInt((String)ht_attributes.get("tag")), Integer.parseInt((String)ht_attributes.get("radius")), (String)ht_attributes.get("points")); } } else if (type.equals("label")) { DLabel label = new DLabel(project, oid, ht_attributes, ht_links); label.addToDatabase(); ht_displayables.put(new Long(oid), label); addToLastOpenLayer(label); last_displayable = label; return null; } else if (type.equals("annot")) { last_annotation = new StringBuilder(); return null; } else if (type.equals("patch")) { Patch patch = new Patch(project, oid, ht_attributes, ht_links); patch.addToDatabase(); ht_displayables.put(new Long(oid), patch); addToLastOpenLayer(patch); last_patch = patch; last_displayable = patch; return null; } else if (type.equals("dissector")) { Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links); dissector.addToDatabase(); last_dissector = dissector; last_displayable = dissector; ht_displayables.put(new Long(oid), dissector); ht_zdispl.put(new Long(oid), dissector); addToLastOpenLayerSet(dissector); } else if (type.equals("layer")) { // find last open LayerSet, if any for (int i = al_layer_sets.size() -1; i>-1; i--) { LayerSet set = (LayerSet)al_layer_sets.get(i); Layer layer = new Layer(project, oid, ht_attributes); layer.addToDatabase(); set.addSilently(layer); al_layers.add(layer); Object ot = ht_attributes.get("title"); return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String)ot), layer, null, null); } } else if (type.equals("layer_set")) { LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links); last_displayable = set; set.addToDatabase(); ht_displayables.put(new Long(oid), set); al_layer_sets.add(set); addToLastOpenLayer(set); Object ot = ht_attributes.get("title"); return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String)ot), set, null, null); } else if (type.equals("calibration")) { // find last open LayerSet if any for (int i = al_layer_sets.size() -1; i>-1; i--) { LayerSet set = (LayerSet)al_layer_sets.get(i); set.restoreCalibration(ht_attributes); return null; } } else if (type.equals("prop")) { // Add property to last created Displayable if (null != last_displayable) { last_displayable.setProperty((String)ht_attributes.get("key"), (String)ht_attributes.get("value")); } } else if (type.equals("linked_prop")) { // Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances. if (null != last_displayable) { putLinkedProperty(last_displayable, ht_attributes); } } else { Utils.log2("TMLHandler Unknown type: " + type); } } catch (Exception e) { IJError.print(e); } // default: return null; }
private LayerThing makeLayerThing(String type, final HashMap ht_attributes) { try { type = type.toLowerCase(); if (0 == type.indexOf("t2_")) { type = type.substring(3); } long id = -1; Object sid = ht_attributes.get("id"); if (null != sid) id = Long.parseLong((String)sid); long oid = -1; Object soid = ht_attributes.get("oid"); if (null != soid) oid = Long.parseLong((String)soid); if (type.equals("node")) { if (null == last_tree) { throw new NullPointerException("Can't create a node for null last_tree!"); } final Node node = last_tree.newNode(ht_attributes); taggables.add(node); // Put node into the list of nodes with that layer id, to update to proper Layer pointer later final long ndlid = Long.parseLong((String)ht_attributes.get("lid")); List<Node> list = node_layer_table.get(ndlid); if (null == list) { list = new ArrayList<Node>(); node_layer_table.put(ndlid, list); } list.add(node); // Set node as root node or add as child to last node in the stack if (null == last_root_node) { last_root_node = node; } else { nodes.getLast().add(node, Byte.parseByte((String)ht_attributes.get("c"))); } // Put node into stack of nodes (to be removed on closing the tag) nodes.add(node); } else if (type.equals("profile")) { Profile profile = new Profile(this.project, oid, ht_attributes, ht_links); profile.addToDatabase(); ht_displayables.put(new Long(oid), profile); addToLastOpenLayer(profile); last_displayable = profile; return null; } else if (type.equals("pipe")) { Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links); pipe.addToDatabase(); ht_displayables.put(new Long(oid), pipe); ht_zdispl.put(new Long(oid), pipe); last_displayable = pipe; addToLastOpenLayerSet(pipe); return null; } else if (type.equals("polyline")) { Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links); pline.addToDatabase(); last_displayable = pline; ht_displayables.put(new Long(oid), pline); ht_zdispl.put(new Long(oid), pline); addToLastOpenLayerSet(pline); return null; } else if (type.equals("connector")) { final Connector con = new Connector(this.project, oid, ht_attributes, ht_links); if (ht_attributes.containsKey("origin")) { legacy.add(new Runnable() { public void run() { con.readLegacyXML(al_layer_sets.get(al_layer_sets.size()-1), ht_attributes, ht_links); } }); } con.addToDatabase(); last_connector = con; last_tree = con; last_displayable = con; ht_displayables.put(new Long(oid), con); ht_zdispl.put(new Long(oid), con); addToLastOpenLayerSet(con); return null; } else if (type.equals("path")) { if (null != reca) { reca.add((String)ht_attributes.get("d")); return null; } return null; } else if (type.equals("area")) { reca = new ReconstructArea(); if (null != last_area_list) { last_area_list_layer_id = Long.parseLong((String)ht_attributes.get("layer_id")); } return null; } else if (type.equals("area_list")) { AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links); area.addToDatabase(); // why? This looks like an onion last_area_list = area; last_displayable = area; ht_displayables.put(new Long(oid), area); ht_zdispl.put(new Long(oid), area); addToLastOpenLayerSet(area); return null; } else if (type.equals("tag")) { Taggable t = taggables.getLast(); if (null != t) { Object ob = ht_attributes.get("key"); int keyCode = KeyEvent.VK_T; // defaults to 't' if (null != ob) keyCode = (int)((String)ob).toUpperCase().charAt(0); // KeyEvent.VK_U is char U, not u Tag tag = new Tag(ht_attributes.get("name"), keyCode); al_layer_sets.get(al_layer_sets.size()-1).putTag(tag, keyCode); t.addTag(tag); } } else if (type.equals("ball_ob")) { // add a ball to the last open Ball if (null != last_ball) { last_ball.addBall(Double.parseDouble((String)ht_attributes.get("x")), Double.parseDouble((String)ht_attributes.get("y")), Double.parseDouble((String)ht_attributes.get("r")), Long.parseLong((String)ht_attributes.get("layer_id"))); } return null; } else if (type.equals("ball")) { Ball ball = new Ball(this.project, oid, ht_attributes, ht_links); ball.addToDatabase(); last_ball = ball; last_displayable = ball; ht_displayables.put(new Long(oid), ball); ht_zdispl.put(new Long(oid), ball); addToLastOpenLayerSet(ball); return null; } else if (type.equals("stack")) { Stack stack = new Stack(this.project, oid, ht_attributes, ht_links); stack.addToDatabase(); last_stack = stack; last_displayable = stack; ht_displayables.put(new Long(oid), stack); ht_zdispl.put( new Long(oid), stack ); addToLastOpenLayerSet( stack ); } else if (type.equals("treeline")) { Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links); tline.addToDatabase(); last_treeline = tline; last_tree = tline; last_treeline_data = new StringBuilder(); last_displayable = tline; ht_displayables.put(oid, tline); ht_zdispl.put(oid, tline); addToLastOpenLayerSet(tline); } else if (type.equals("areatree")) { AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links); art.addToDatabase(); last_areatree = art; last_tree = art; last_displayable = art; ht_displayables.put(oid, art); ht_zdispl.put(oid, art); addToLastOpenLayerSet(art); } else if (type.equals("dd_item")) { if (null != last_dissector) { last_dissector.addItem(Integer.parseInt((String)ht_attributes.get("tag")), Integer.parseInt((String)ht_attributes.get("radius")), (String)ht_attributes.get("points")); } } else if (type.equals("label")) { DLabel label = new DLabel(project, oid, ht_attributes, ht_links); label.addToDatabase(); ht_displayables.put(new Long(oid), label); addToLastOpenLayer(label); last_displayable = label; return null; } else if (type.equals("annot")) { last_annotation = new StringBuilder(); return null; } else if (type.equals("patch")) { Patch patch = new Patch(project, oid, ht_attributes, ht_links); patch.addToDatabase(); ht_displayables.put(new Long(oid), patch); addToLastOpenLayer(patch); last_patch = patch; last_displayable = patch; return null; } else if (type.equals("dissector")) { Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links); dissector.addToDatabase(); last_dissector = dissector; last_displayable = dissector; ht_displayables.put(new Long(oid), dissector); ht_zdispl.put(new Long(oid), dissector); addToLastOpenLayerSet(dissector); } else if (type.equals("layer")) { // find last open LayerSet, if any for (int i = al_layer_sets.size() -1; i>-1; i--) { LayerSet set = (LayerSet)al_layer_sets.get(i); Layer layer = new Layer(project, oid, ht_attributes); layer.addToDatabase(); set.addSilently(layer); al_layers.add(layer); Object ot = ht_attributes.get("title"); return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String)ot), layer, null, null); } } else if (type.equals("layer_set")) { LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links); last_displayable = set; set.addToDatabase(); ht_displayables.put(new Long(oid), set); al_layer_sets.add(set); addToLastOpenLayer(set); Object ot = ht_attributes.get("title"); return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String)ot), set, null, null); } else if (type.equals("calibration")) { // find last open LayerSet if any for (int i = al_layer_sets.size() -1; i>-1; i--) { LayerSet set = (LayerSet)al_layer_sets.get(i); set.restoreCalibration(ht_attributes); return null; } } else if (type.equals("prop")) { // Add property to last created Displayable if (null != last_displayable) { last_displayable.setProperty((String)ht_attributes.get("key"), (String)ht_attributes.get("value")); } } else if (type.equals("linked_prop")) { // Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances. if (null != last_displayable) { putLinkedProperty(last_displayable, ht_attributes); } } else { Utils.log2("TMLHandler Unknown type: " + type); } } catch (Exception e) { IJError.print(e); } // default: return null; }
diff --git a/src/net/sf/freecol/server/ai/ColonyPlan.java b/src/net/sf/freecol/server/ai/ColonyPlan.java index 8865776f1..c840f54fa 100644 --- a/src/net/sf/freecol/server/ai/ColonyPlan.java +++ b/src/net/sf/freecol/server/ai/ColonyPlan.java @@ -1,1119 +1,1120 @@ /** * Copyright (C) 2002-2007 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.server.ai; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Logger; import net.sf.freecol.common.Specification; import net.sf.freecol.common.model.AbstractGoods; import net.sf.freecol.common.model.BuildableType; import net.sf.freecol.common.model.Building; import net.sf.freecol.common.model.BuildingType; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTile; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.Market; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.server.ai.ColonyProfile.ProfileType; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Objects of this class describes the plan the AI has for a <code>Colony</code>. * * <br> * <br> * * A <code>ColonyPlan</code> contains {@link WorkLocationPlan}s which defines * the production of each {@link Building} and {@link ColonyTile}. * * @see Colony */ public class ColonyPlan { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(ColonyPlan.class.getName()); // gets multiplied by the number of fish produced public static final int DOCKS_PRIORITY = 10; public static final int ARTILLERY_PRIORITY = 10; public static final int CHURCH_PRIORITY = 15; public static final int WAGON_TRAIN_PRIORITY = 20; public static final int SCHOOL_PRIORITY = 30; public static final int UPGRADE_PRIORITY = 50; public static final int CUSTOMS_HOUSE_PRIORITY = 60; public static final int TOWN_HALL_PRIORITY = 75; public static final int WAREHOUSE_PRIORITY = 90; public static final int BUILDING_PRIORITY = 120; // What is this supposed to be? Is it the maximum number of units // per building? private static final int MAX_LEVEL = 3; private static final int MIN_RAW_GOODS_THRESHOLD = 20; private static final GoodsType hammersType = Specification.getSpecification().getGoodsType("model.goods.hammers"); private static final GoodsType toolsType = Specification.getSpecification().getGoodsType("model.goods.tools"); private static final GoodsType lumberType = Specification.getSpecification().getGoodsType("model.goods.lumber"); private static final GoodsType oreType = Specification.getSpecification().getGoodsType("model.goods.ore"); /** * The FreeColGameObject this AIObject contains AI-information for. */ private Colony colony; private AIMain aiMain; private ArrayList<WorkLocationPlan> workLocationPlans = new ArrayList<WorkLocationPlan>(); private GoodsType primaryRawMaterial = null; private GoodsType secondaryRawMaterial = null; /** * Describe profile here. */ private ColonyProfile profile = new ColonyProfile(); /** * Creates a new <code>ColonyPlan</code>. * * @param aiMain The main AI-object. * @param colony The colony to make a <code>ColonyPlan</code> for. */ public ColonyPlan(AIMain aiMain, Colony colony) { if (colony == null) { throw new IllegalArgumentException("Parameter 'colony' must not be 'null'."); } this.aiMain = aiMain; this.colony = colony; selectProfile(); } /** * Creates a new <code>ColonyPlan</code>. * * @param aiMain The main AI-object. * @param element An <code>Element</code> containing an XML-representation * of this object. */ public ColonyPlan(AIMain aiMain, Element element) { this.aiMain = aiMain; readFromXMLElement(element); } /** * Returns the <code>WorkLocationPlan</code>s associated with this * <code>ColonyPlan</code>. * * @return The list of <code>WorkLocationPlan</code>s . */ public List<WorkLocationPlan> getWorkLocationPlans() { return new ArrayList<WorkLocationPlan>(workLocationPlans); } /** * Returns the <code>WorkLocationPlan</code>s associated with this * <code>ColonyPlan</code> sorted by production in a decreasing order. * * @return The list of <code>WorkLocationPlan</code>s . */ public List<WorkLocationPlan> getSortedWorkLocationPlans() { List<WorkLocationPlan> workLocationPlans = getWorkLocationPlans(); Collections.sort(workLocationPlans); return workLocationPlans; } /** * Get the <code>Profile</code> value. * * @return a <code>ColonyProfile</code> value */ public final ColonyProfile getProfile() { return profile; } /** * Set the <code>Profile</code> value. * * @param newProfile The new Profile value. */ public final void setProfile(final ColonyProfile newProfile) { this.profile = newProfile; } public class Buildable implements Comparable<Buildable> { BuildableType type; int priority; public Buildable(BuildableType type, int priority) { this.type = type; this.priority = priority; } public int compareTo(Buildable other) { return other.priority - priority; } } /** * Gets an <code>Iterator</code> for everything to be built in the * <code>Colony</code>. * * @return An iterator containing all the <code>Buildable</code> sorted by * priority (highest priority first). */ public Iterator<BuildableType> getBuildable() { // don't build anything in colonies likely to be abandoned if (profile.getType() == ProfileType.OUTPOST) { List<BuildableType> result = Collections.emptyList(); return result.iterator(); } List<Buildable> buildables = new ArrayList<Buildable>(); List<BuildingType> docks = new ArrayList<BuildingType>(); List<BuildingType> customs = new ArrayList<BuildingType>(); List<BuildingType> builders = new ArrayList<BuildingType>(); List<BuildingType> defence = new ArrayList<BuildingType>(); List<BuildingType> military = new ArrayList<BuildingType>(); List<BuildingType> schools = new ArrayList<BuildingType>(); List<BuildingType> churches = new ArrayList<BuildingType>(); List<BuildingType> townHalls = new ArrayList<BuildingType>(); for (BuildingType type : Specification.getSpecification().getBuildingTypeList()) { if (type.hasAbility("model.ability.produceInWater")) { docks.add(type); } if (type.hasAbility("model.ability.export")) { customs.add(type); } if (type.hasAbility("model.ability.teach")) { schools.add(type); } if (!type.getModifierSet("model.modifier.defence").isEmpty()) { defence.add(type); } if (type.getProducedGoodsType() != null) { GoodsType output = type.getProducedGoodsType(); if (output.isBuildingMaterial()) { builders.add(type); } if (output.isMilitaryGoods()) { military.add(type); } if (output.isLibertyType()) { townHalls.add(type); } if (output.isImmigrationType()) { churches.add(type); } } } List<UnitType> buildableDefenders = new ArrayList<UnitType>(); UnitType bestWagon = null; for (UnitType unitType : Specification.getSpecification().getUnitTypeList()) { if (unitType.getDefence() > UnitType.DEFAULT_DEFENCE && !unitType.hasAbility("model.ability.navalUnit") && !unitType.getGoodsRequired().isEmpty()) { buildableDefenders.add(unitType); } if (unitType.hasAbility("model.ability.carryGoods") && !unitType.hasAbility("model.ability.navalUnit") && colony.canBuild(unitType) && (bestWagon == null || unitType.getSpace() > bestWagon.getSpace())) { bestWagon = unitType; } } int wagonTrains = 0; for (Unit unit: colony.getOwner().getUnits()) { if (unit.hasAbility("model.ability.carryGoods") && !unit.isNaval()) { wagonTrains++; } } if (colony.isLandLocked()) { // landlocked colonies need transportation int landLockedColonies = 0; for (Colony otherColony : colony.getOwner().getColonies()) { if (otherColony.isLandLocked()) { landLockedColonies++; } } if (bestWagon != null && landLockedColonies > wagonTrains) { buildables.add(new Buildable(bestWagon, WAGON_TRAIN_PRIORITY * (landLockedColonies - wagonTrains))); } } else if (!colony.hasAbility("model.ability.produceInWater")) { // coastal colonies need docks int potential = 0; for (ColonyTile colonyTile : colony.getColonyTiles()) { Tile tile = colonyTile.getWorkTile(); if (!tile.isLand()) { for (AbstractGoods goods : tile.getSortedPotential()) { if (goods.getType().isFoodType()) { potential += goods.getAmount(); break; } } } } for (BuildingType buildingType : docks) { if (colony.canBuild(buildingType)) { buildables.add(new Buildable(buildingType, potential * DOCKS_PRIORITY)); break; } } } // if we are using a building, we should upgrade it, if possible Iterator<WorkLocationPlan> wlpIt = getSortedWorkLocationPlans().iterator(); while (wlpIt.hasNext()) { WorkLocationPlan wlp = wlpIt.next(); if (wlp.getWorkLocation() instanceof Building) { Building b = (Building) wlp.getWorkLocation(); if (b.canBuildNext()) { buildables.add(new Buildable(b.getType().getUpgradesTo(), UPGRADE_PRIORITY)); } // this handles buildings that increase the production // of other buildings (printing press, newspaper) GoodsType outputType = b.getGoodsOutputType(); if (outputType != null) { for (BuildingType otherType : Specification.getSpecification() .getBuildingTypeList()) { if (!otherType.getModifierSet(outputType.getId()).isEmpty() && colony.canBuild(otherType)) { int priority = (colony.getBuilding(otherType) == null) ? 2 * UPGRADE_PRIORITY : UPGRADE_PRIORITY; buildables.add(new Buildable(otherType, priority)); } } } } } // build custom house as soon as possible, in order to free // transports for other duties (and avoid pirates, and // possibly boycotts) if (!colony.hasAbility("model.ability.export")) { for (BuildingType buildingType : customs) { if (colony.canBuild(buildingType)) { buildables.add(new Buildable(buildingType, CUSTOMS_HOUSE_PRIORITY)); break; } } } // improve production of building materials for (BuildingType buildingType : builders) { if (colony.canBuild(buildingType)) { int priority = BUILDING_PRIORITY; // reduce priority for armory and stables if (buildingType.getProducedGoodsType() != null && buildingType.getProducedGoodsType().isMilitaryGoods()) { priority /= 2; } buildables.add(new Buildable(buildingType, priority)); } } // Check if we should improve the warehouse: Building building = colony.getWarehouse(); if (building.canBuildNext()) { int priority = colony.getGoodsContainer() .hasReachedCapacity(colony.getWarehouseCapacity()) ? 2 * WAREHOUSE_PRIORITY : WAREHOUSE_PRIORITY; buildables.add(new Buildable(building.getType().getUpgradesTo(), priority)); } else if (bestWagon != null && wagonTrains < 4 * colony.getOwner().getColonies().size()) { buildables.add(new Buildable(bestWagon, WAGON_TRAIN_PRIORITY)); } // improve defences for (BuildingType buildingType : defence) { if (colony.canBuild(buildingType)) { int priority = (colony.getBuilding(buildingType) == null || profile.getType() == ProfileType.LARGE || profile.getType() == ProfileType.CAPITAL) ? 2 * UPGRADE_PRIORITY : UPGRADE_PRIORITY; buildables.add(new Buildable(buildingType, priority)); } } // improve military production for (BuildingType buildingType : military) { if (colony.canBuild(buildingType)) { if (colony.getBuilding(buildingType) == null && (buildingType.getConsumedGoodsType() == null || buildingType.getConsumedGoodsType().isFarmed())) { buildables.add(new Buildable(buildingType, UPGRADE_PRIORITY)); } else { buildables.add(new Buildable(buildingType, UPGRADE_PRIORITY / 2)); } } } // add artillery if necessary // TODO: at some point, we will have to add ships if (((AIColony) aiMain.getAIObject(colony)).isBadlyDefended()) { for (UnitType unitType : buildableDefenders) { if (colony.canBuild(unitType)) { int priority = (profile.getType() == ProfileType.LARGE || profile.getType() == ProfileType.CAPITAL) ? 2 * ARTILLERY_PRIORITY : ARTILLERY_PRIORITY; buildables.add(new Buildable(unitType, priority)); break; } } } // improve education if (profile.getType() != ProfileType.SMALL) { for (BuildingType buildingType : schools) { if (colony.canBuild(buildingType)) { int priority = SCHOOL_PRIORITY; if (colony.getBuilding(buildingType) != null) { if (profile.getType() == ProfileType.MEDIUM) { priority /= 2; } if (buildingType.getUpgradesTo() == null) { if (profile.getType() != ProfileType.CAPITAL) { continue; } } } buildables.add(new Buildable(buildingType, priority)); } } } // improve town hall (not required for standard rule set, // since town hall can not be upgraded) for (BuildingType buildingType : townHalls) { if (colony.canBuild(buildingType)) { int priority = (colony.getBuilding(buildingType) == null) ? 2 * TOWN_HALL_PRIORITY : TOWN_HALL_PRIORITY; buildables.add(new Buildable(buildingType, priority)); } } // improve churches for (BuildingType buildingType : churches) { if (colony.canBuild(buildingType)) { int priority = (colony.getBuilding(buildingType) == null) ? 2 * CHURCH_PRIORITY : CHURCH_PRIORITY; buildables.add(new Buildable(buildingType, priority)); } } Collections.sort(buildables); List<BuildableType> result = new ArrayList<BuildableType>(); Set<BuildableType> found = new HashSet<BuildableType>(); for (Buildable buildable : buildables) { if (!found.contains(buildable.type)) { result.add(buildable.type); found.add(buildable.type); } } return result.iterator(); } /** * Gets the main AI-object. * * @return The main AI-object. */ public AIMain getAIMain() { return aiMain; } /** * Get the <code>Game</code> this object is associated to. * * @return The <code>Game</code>. */ public Game getGame() { return aiMain.getGame(); } /** * Creates a plan for this colony. That is; determines what type of goods * each tile should produce and what type of goods that should be * manufactured. */ public void create() { workLocationPlans.clear(); if (profile.getType() == ProfileType.OUTPOST) { GoodsType goodsType = profile.getPreferredProduction().get(0); workLocationPlans.add(new WorkLocationPlan(getAIMain(), getBestTileToProduce(goodsType), goodsType)); return; } Building townHall = colony.getBuildingForProducing(Goods.BELLS); // Choose the best production for each tile: for (ColonyTile ct : colony.getColonyTiles()) { if (ct.getWorkTile().getOwningSettlement() != null && ct.getWorkTile().getOwningSettlement() != colony || ct.isColonyCenterTile()) { continue; } GoodsType goodsType = getBestGoodsToProduce(ct.getWorkTile()); WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), ct, goodsType); workLocationPlans.add(wlp); } // We need to find what, if any, is still required for what we are building GoodsType buildingReq = null; GoodsType buildingRawMat = null; Building buildingReqProducer = null; buildingReq = getBuildingReqGoods(); if(buildingReq != null){ if(buildingReq == hammersType){ buildingRawMat = lumberType; } else{ buildingRawMat = oreType; } buildingReqProducer = colony.getBuildingForProducing(buildingReq); } // Try to ensure that we produce the raw material necessary for //what we are building boolean buildingRawMatReq = buildingRawMat != null && colony.getGoodsCount(buildingRawMat) < MIN_RAW_GOODS_THRESHOLD && getProductionOf(buildingRawMat) <= 0; if(buildingRawMatReq) { WorkLocationPlan bestChoice = null; int highestPotential = 0; Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); // TODO: find out about unit working here, if any (?) if (wlp.getWorkLocation() instanceof ColonyTile && ((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(buildingRawMat, null) > highestPotential) { highestPotential = ((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(buildingRawMat, null); bestChoice = wlp; } } if (highestPotential > 0) { // this must be true because it is the only way to // increase highestPotential assert bestChoice != null; bestChoice.setGoodsType(buildingRawMat); } } // Determine the primary and secondary types of goods: primaryRawMaterial = null; secondaryRawMaterial = null; int primaryRawMaterialProduction = 0; int secondaryRawMaterialProduction = 0; List<GoodsType> goodsTypeList = Specification.getSpecification().getGoodsTypeList(); for (GoodsType goodsType : goodsTypeList) { // only consider goods that can be transformed // do not consider hammers as a valid transformation if (goodsType.getProducedMaterial() == null || goodsType.getProducedMaterial() == hammersType) { continue; } if (getProductionOf(goodsType) > primaryRawMaterialProduction) { secondaryRawMaterial = primaryRawMaterial; secondaryRawMaterialProduction = primaryRawMaterialProduction; primaryRawMaterial = goodsType; primaryRawMaterialProduction = getProductionOf(goodsType); } else if (getProductionOf(goodsType) > secondaryRawMaterialProduction) { secondaryRawMaterial = goodsType; secondaryRawMaterialProduction = getProductionOf(goodsType); } } // Produce food instead of goods not being primary, secondary, lumber, // ore or silver: // Stop producing if the amount of goods being produced is too low: Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); if (!(wlp.getWorkLocation() instanceof ColonyTile)) { continue; } if (wlp.getGoodsType() == primaryRawMaterial || wlp.getGoodsType() == secondaryRawMaterial || wlp.getGoodsType() == Goods.LUMBER || wlp.getGoodsType() == Goods.ORE || wlp.getGoodsType() == Goods.SILVER) { continue; } // TODO: find out about unit working here, if any (?) if (((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(Goods.FOOD, null) <= 2) { if (wlp.getGoodsType() == null) { // on arctic tiles nothing can be produced wlpIterator.remove(); } else if (wlp.getProductionOf(wlp.getGoodsType()) <= 2) { // just a poor location wlpIterator.remove(); } continue; } wlp.setGoodsType(Goods.FOOD); } // Produce the goods required for what is being built, if: // - anything is being built, and // - there is either production or stock of the raw material if(buildingReq != null && (getProductionOf(buildingRawMat) > 0 || colony.getGoodsCount(buildingRawMat) > 0)){ WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), colony.getBuildingForProducing(buildingReq), buildingReq); workLocationPlans.add(wlp); } // Place a statesman: WorkLocationPlan townHallWlp = new WorkLocationPlan(getAIMain(), townHall, Goods.BELLS); workLocationPlans.add(townHallWlp); // Place a colonist to manufacture the primary goods: if (primaryRawMaterial != null) { GoodsType producedGoods = primaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); } } // Remove the secondary goods if we need food: - if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION && - secondaryRawMaterial.isNewWorldGoodsType()) { + if (secondaryRawMaterial != null + && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION + && secondaryRawMaterial.isNewWorldGoodsType()) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext()) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == secondaryRawMaterial) { Tile t = ((ColonyTile) wlp.getWorkLocation()).getWorkTile(); // TODO: find out about unit working here, if any (?) if (t.getMaximumPotential(Goods.FOOD, null) > 2) { wlp.setGoodsType(Goods.FOOD); } else { wlpIterator2.remove(); } } } } // Remove the workers on the primary goods one-by-one if we need food: if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == primaryRawMaterial) { Tile t = ((ColonyTile) wlp.getWorkLocation()).getWorkTile(); // TODO: find out about unit working here, if any (?) if (t.getMaximumPotential(Goods.FOOD, null) > 2) { wlp.setGoodsType(Goods.FOOD); } else { wlpIterator2.remove(); } } } } // Remove the manufacturer if we still lack food: if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof Building) { Building b = (Building) wlp.getWorkLocation(); if ( b != buildingReqProducer && b != townHall) { wlpIterator2.remove(); } } } } // Still lacking food // Remove the producers of the raw and/or non-raw materials required for the build // The decision of which to start depends on existence or not of stock of //raw materials GoodsType buildMatToGo = buildingReq; if(colony.getGoodsCount(buildingRawMat) > 0){ buildMatToGo = buildingRawMat; } if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == buildMatToGo) { wlpIterator2.remove(); } } // still lacking food, removing the rest if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { buildMatToGo = (buildMatToGo == buildingRawMat)? buildingReq : buildingRawMat; wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == buildMatToGo) { wlpIterator2.remove(); } } } } // Primary allocations done // Beginning secondary allocations // Not enough food for more allocations, save work and stop here if(getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2){ return; } int primaryWorkers = 1; int secondaryWorkers = 0; int builders = 1; int gunsmiths = 0; boolean colonistAdded = true; //XXX: This loop does not work, only goes through once, not as intended while (colonistAdded) { boolean blacksmithAdded = false; // Add a manufacturer for the secondary type of goods: if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && secondaryRawMaterial != null && 12 * secondaryWorkers + 6 <= getProductionOf(secondaryRawMaterial) && secondaryWorkers <= MAX_LEVEL) { GoodsType producedGoods = secondaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); colonistAdded = true; secondaryWorkers++; if (secondaryRawMaterial == Goods.ORE) { blacksmithAdded = true; } } } // Add a manufacturer for the primary type of goods: if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && primaryRawMaterial != null && 12 * primaryWorkers + 6 <= getProductionOf(primaryRawMaterial) && primaryWorkers <= MAX_LEVEL) { GoodsType producedGoods = primaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); colonistAdded = true; primaryWorkers++; if (primaryRawMaterial == Goods.ORE) { blacksmithAdded = true; } } } // Add a gunsmith: if (blacksmithAdded && getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && gunsmiths < MAX_LEVEL) { Building b = colony.getBuildingForProducing(Goods.MUSKETS); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, Goods.MUSKETS); workLocationPlans.add(wlp); colonistAdded = true; gunsmiths++; } } // Add builders if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && buildingReqProducer != null && buildingReqProducer.getProduction() * builders <= getProductionOf(buildingRawMat) && buildingReqProducer.getMaxUnits() < builders) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), buildingReqProducer, buildingReq); workLocationPlans.add(wlp); colonistAdded = true; builders++; } // TODO: Add worker to armory. colonistAdded = false; } // TODO: Add statesman // TODO: Add teacher // TODO: Add preacher } /** * Returns the production of the given type of goods according to this plan. * * @param goodsType The type of goods to check the production for. * @return The maximum possible production of the given type of goods * according to this <code>ColonyPlan</code>. */ public int getProductionOf(GoodsType goodsType) { int amount = 0; Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); amount += wlp.getProductionOf(goodsType); } // Add values for the center tile: if (goodsType == colony.getTile().primaryGoods() || goodsType == colony.getTile().secondaryGoods()) { amount += colony.getTile().getMaximumPotential(goodsType, null); } return amount; } /** * Returns the production of food according to this plan. * * @return The maximum possible food production * according to this <code>ColonyPlan</code>. */ public int getFoodProduction() { int amount = 0; for (GoodsType foodType : Specification.getSpecification().getGoodsFood()) { amount += getProductionOf(foodType); } return amount; } /** * Determines the best goods to produce on a given <code>Tile</code> * within this colony. * * @param t The <code>Tile</code>. * @return The type of goods. */ private GoodsType getBestGoodsToProduce(Tile t) { if (t.hasResource()) { return t.getTileItemContainer().getResource().getBestGoodsType(); } else { List<AbstractGoods> sortedPotentials = t.getSortedPotential(); if (sortedPotentials.isEmpty()) { return null; } else { return sortedPotentials.get(0).getType(); } } } private ColonyTile getBestTileToProduce(GoodsType goodsType) { int bestProduction = -1; ColonyTile bestTile = null; for (ColonyTile ct : colony.getColonyTiles()) { Tile tile = ct.getWorkTile(); if ((tile.getOwningSettlement() == null || tile.getOwningSettlement() == colony) && !ct.isColonyCenterTile()) { int production = tile.potential(goodsType, null); if (bestTile == null || bestProduction < production) { bestTile = ct; bestProduction = production; } } } if (bestProduction > 0) { return bestTile; } else { return null; } } public class Production { ColonyTile colonyTile; GoodsType goodsType; public Production(ColonyTile ct, GoodsType gt) { colonyTile = ct; goodsType = gt; } } public Production getBestProduction(UnitType unitType) { Market market = colony.getOwner().getMarket(); Production bestProduction = null; int value = -1; for (ColonyTile ct : colony.getColonyTiles()) { Tile tile = ct.getWorkTile(); if ((tile.getOwningSettlement() == null || tile.getOwningSettlement() == colony) && !ct.isColonyCenterTile()) { for (GoodsType goodsType : Specification.getSpecification().getFarmedGoodsTypeList()) { int production = market.getSalePrice(goodsType, tile.potential(goodsType, unitType)); if (bestProduction == null || value < production) { value = production; bestProduction = new Production(ct, goodsType); } } } } return bestProduction; } public void adjustProductionAndManufacture(){ List<GoodsType> rawMatList = new ArrayList<GoodsType>(); if(getBuildingReqGoods() == hammersType){ rawMatList.add(lumberType); } rawMatList.add(oreType); if (primaryRawMaterial != null && primaryRawMaterial != lumberType && primaryRawMaterial != oreType && !primaryRawMaterial.isFoodType()) { rawMatList.add(primaryRawMaterial); } if (secondaryRawMaterial != null && secondaryRawMaterial != lumberType && secondaryRawMaterial != oreType && !secondaryRawMaterial.isFoodType()) { rawMatList.add(secondaryRawMaterial); } for(GoodsType rawMat : rawMatList){ GoodsType producedGoods = rawMat.getProducedMaterial(); if(producedGoods == null){ continue; } adjustProductionAndManufactureFor(rawMat,producedGoods); } } public void adjustProductionAndManufactureFor(GoodsType rawMat, GoodsType producedGoods){ Building factory = colony.getBuildingForProducing(producedGoods); if(factory == null){ return; } List<Unit> producers = new ArrayList<Unit>(); int stockRawMat = colony.getGoodsCount(rawMat); for(ColonyTile t : colony.getColonyTiles()){ if(t.isColonyCenterTile()){ continue; } Unit u = t.getUnit(); if(u == null){ continue; } if(u.getWorkType() != rawMat){ continue; } producers.add(u); } if(producers.size() == 0){ return; } // Creates comparator to order the list of producers by their production (ascending) Comparator<Unit> comp = new Comparator<Unit>(){ public int compare(Unit u1, Unit u2){ GoodsType goodsType = u1.getWorkType(); int prodU1 = ((ColonyTile) u1.getLocation()).getProductionOf(u1, goodsType); int prodU2 = ((ColonyTile) u2.getLocation()).getProductionOf(u2, goodsType); if(prodU1 > prodU2){ return 1; } if(prodU1 < prodU2){ return -1; } return 0; } }; Collections.sort(producers, comp); // shift units gathering raw materials to production of manufactured goods Iterator<Unit> iter = new ArrayList<Unit>(producers).iterator(); while(iter.hasNext()){ // not enough stock of raw material and workers if(stockRawMat < 50 && producers.size() < 2){ return; } if(factory.getUnitCount() == factory.getMaxUnits()){ return; } Unit u = iter.next(); // this particular unit cannot be added to this building if(!factory.canAdd(u.getType())){ continue; } // get the production values if the unit is shifted int rawProd = colony.getProductionNextTurn(rawMat) - ((ColonyTile)u.getWorkTile()).getProductionOf(u, rawMat); int mfnProd = colony.getProductionNextTurn(producedGoods) + factory.getAdditionalProductionNextTurn(u); if(stockRawMat < 50 && rawProd < mfnProd){ return; } u.work(factory); u.setWorkType(producedGoods); producers.remove(u); } } public GoodsType getBuildingReqGoods(){ BuildableType currBuild = colony.getCurrentlyBuilding(); if(currBuild == null){ return null; } if(colony.getGoodsCount(hammersType) < currBuild.getAmountRequiredOf(hammersType)){ return hammersType; } else{ return toolsType; } } public GoodsType getPrimaryRawMaterial(){ return primaryRawMaterial; } public GoodsType getSecondaryRawMaterial(){ return secondaryRawMaterial; } /** * Gets the <code>Colony</code> this <code>ColonyPlan</code> controls. * * @return The <code>Colony</code>. */ public Colony getColony() { return colony; } private void selectProfile() { int size = colony.getUnitCount(); if (size < 4) { profile.setType(ProfileType.SMALL); } else if (size > 8) { profile.setType(ProfileType.LARGE); } else if (size > 12) { profile.setType(ProfileType.CAPITAL); } } /** * Creates an XML-representation of this object. * * @param document The <code>Document</code> in which the * XML-representation should be created. * @return The XML-representation. */ public Element toXMLElement(Document document) { Element element = document.createElement(getXMLElementTagName()); element.setAttribute("ID", colony.getId()); return element; } /** * Updates this object from an XML-representation of a * <code>ColonyPlan</code>. * * @param element The XML-representation. */ public void readFromXMLElement(Element element) { colony = (Colony) getAIMain().getFreeColGameObject(element.getAttribute("ID")); // TODO: serialize profile selectProfile(); } /** * Returns the tag name of the root element representing this object. * * @return "colonyPlan" */ public static String getXMLElementTagName() { return "colonyPlan"; } /** * Creates a <code>String</code> representation of this plan. */ public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ColonyPlan for " + colony.getName() + " " + colony.getTile().getPosition()); sb.append("\n\nPROFILE:\n"); sb.append(profile.getType().toString()); sb.append("\n"); for (GoodsType goodsType : profile.getPreferredProduction()) { sb.append(goodsType.getName()); sb.append("\n"); } sb.append("\n\nWORK LOCATIONS:\n"); for (WorkLocationPlan p : getSortedWorkLocationPlans()) { sb.append(p.getGoodsType().getName() + " (" + p.getWorkLocation() + ")\n"); } sb.append("\n\nBUILD QUEUE:\n"); final Iterator<BuildableType> it = getBuildable(); while (it.hasNext()) { final BuildableType b = it.next(); sb.append(b.getName()); sb.append('\n'); } return sb.toString(); } }
true
true
public void create() { workLocationPlans.clear(); if (profile.getType() == ProfileType.OUTPOST) { GoodsType goodsType = profile.getPreferredProduction().get(0); workLocationPlans.add(new WorkLocationPlan(getAIMain(), getBestTileToProduce(goodsType), goodsType)); return; } Building townHall = colony.getBuildingForProducing(Goods.BELLS); // Choose the best production for each tile: for (ColonyTile ct : colony.getColonyTiles()) { if (ct.getWorkTile().getOwningSettlement() != null && ct.getWorkTile().getOwningSettlement() != colony || ct.isColonyCenterTile()) { continue; } GoodsType goodsType = getBestGoodsToProduce(ct.getWorkTile()); WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), ct, goodsType); workLocationPlans.add(wlp); } // We need to find what, if any, is still required for what we are building GoodsType buildingReq = null; GoodsType buildingRawMat = null; Building buildingReqProducer = null; buildingReq = getBuildingReqGoods(); if(buildingReq != null){ if(buildingReq == hammersType){ buildingRawMat = lumberType; } else{ buildingRawMat = oreType; } buildingReqProducer = colony.getBuildingForProducing(buildingReq); } // Try to ensure that we produce the raw material necessary for //what we are building boolean buildingRawMatReq = buildingRawMat != null && colony.getGoodsCount(buildingRawMat) < MIN_RAW_GOODS_THRESHOLD && getProductionOf(buildingRawMat) <= 0; if(buildingRawMatReq) { WorkLocationPlan bestChoice = null; int highestPotential = 0; Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); // TODO: find out about unit working here, if any (?) if (wlp.getWorkLocation() instanceof ColonyTile && ((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(buildingRawMat, null) > highestPotential) { highestPotential = ((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(buildingRawMat, null); bestChoice = wlp; } } if (highestPotential > 0) { // this must be true because it is the only way to // increase highestPotential assert bestChoice != null; bestChoice.setGoodsType(buildingRawMat); } } // Determine the primary and secondary types of goods: primaryRawMaterial = null; secondaryRawMaterial = null; int primaryRawMaterialProduction = 0; int secondaryRawMaterialProduction = 0; List<GoodsType> goodsTypeList = Specification.getSpecification().getGoodsTypeList(); for (GoodsType goodsType : goodsTypeList) { // only consider goods that can be transformed // do not consider hammers as a valid transformation if (goodsType.getProducedMaterial() == null || goodsType.getProducedMaterial() == hammersType) { continue; } if (getProductionOf(goodsType) > primaryRawMaterialProduction) { secondaryRawMaterial = primaryRawMaterial; secondaryRawMaterialProduction = primaryRawMaterialProduction; primaryRawMaterial = goodsType; primaryRawMaterialProduction = getProductionOf(goodsType); } else if (getProductionOf(goodsType) > secondaryRawMaterialProduction) { secondaryRawMaterial = goodsType; secondaryRawMaterialProduction = getProductionOf(goodsType); } } // Produce food instead of goods not being primary, secondary, lumber, // ore or silver: // Stop producing if the amount of goods being produced is too low: Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); if (!(wlp.getWorkLocation() instanceof ColonyTile)) { continue; } if (wlp.getGoodsType() == primaryRawMaterial || wlp.getGoodsType() == secondaryRawMaterial || wlp.getGoodsType() == Goods.LUMBER || wlp.getGoodsType() == Goods.ORE || wlp.getGoodsType() == Goods.SILVER) { continue; } // TODO: find out about unit working here, if any (?) if (((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(Goods.FOOD, null) <= 2) { if (wlp.getGoodsType() == null) { // on arctic tiles nothing can be produced wlpIterator.remove(); } else if (wlp.getProductionOf(wlp.getGoodsType()) <= 2) { // just a poor location wlpIterator.remove(); } continue; } wlp.setGoodsType(Goods.FOOD); } // Produce the goods required for what is being built, if: // - anything is being built, and // - there is either production or stock of the raw material if(buildingReq != null && (getProductionOf(buildingRawMat) > 0 || colony.getGoodsCount(buildingRawMat) > 0)){ WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), colony.getBuildingForProducing(buildingReq), buildingReq); workLocationPlans.add(wlp); } // Place a statesman: WorkLocationPlan townHallWlp = new WorkLocationPlan(getAIMain(), townHall, Goods.BELLS); workLocationPlans.add(townHallWlp); // Place a colonist to manufacture the primary goods: if (primaryRawMaterial != null) { GoodsType producedGoods = primaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); } } // Remove the secondary goods if we need food: if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION && secondaryRawMaterial.isNewWorldGoodsType()) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext()) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == secondaryRawMaterial) { Tile t = ((ColonyTile) wlp.getWorkLocation()).getWorkTile(); // TODO: find out about unit working here, if any (?) if (t.getMaximumPotential(Goods.FOOD, null) > 2) { wlp.setGoodsType(Goods.FOOD); } else { wlpIterator2.remove(); } } } } // Remove the workers on the primary goods one-by-one if we need food: if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == primaryRawMaterial) { Tile t = ((ColonyTile) wlp.getWorkLocation()).getWorkTile(); // TODO: find out about unit working here, if any (?) if (t.getMaximumPotential(Goods.FOOD, null) > 2) { wlp.setGoodsType(Goods.FOOD); } else { wlpIterator2.remove(); } } } } // Remove the manufacturer if we still lack food: if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof Building) { Building b = (Building) wlp.getWorkLocation(); if ( b != buildingReqProducer && b != townHall) { wlpIterator2.remove(); } } } } // Still lacking food // Remove the producers of the raw and/or non-raw materials required for the build // The decision of which to start depends on existence or not of stock of //raw materials GoodsType buildMatToGo = buildingReq; if(colony.getGoodsCount(buildingRawMat) > 0){ buildMatToGo = buildingRawMat; } if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == buildMatToGo) { wlpIterator2.remove(); } } // still lacking food, removing the rest if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { buildMatToGo = (buildMatToGo == buildingRawMat)? buildingReq : buildingRawMat; wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == buildMatToGo) { wlpIterator2.remove(); } } } } // Primary allocations done // Beginning secondary allocations // Not enough food for more allocations, save work and stop here if(getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2){ return; } int primaryWorkers = 1; int secondaryWorkers = 0; int builders = 1; int gunsmiths = 0; boolean colonistAdded = true; //XXX: This loop does not work, only goes through once, not as intended while (colonistAdded) { boolean blacksmithAdded = false; // Add a manufacturer for the secondary type of goods: if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && secondaryRawMaterial != null && 12 * secondaryWorkers + 6 <= getProductionOf(secondaryRawMaterial) && secondaryWorkers <= MAX_LEVEL) { GoodsType producedGoods = secondaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); colonistAdded = true; secondaryWorkers++; if (secondaryRawMaterial == Goods.ORE) { blacksmithAdded = true; } } } // Add a manufacturer for the primary type of goods: if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && primaryRawMaterial != null && 12 * primaryWorkers + 6 <= getProductionOf(primaryRawMaterial) && primaryWorkers <= MAX_LEVEL) { GoodsType producedGoods = primaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); colonistAdded = true; primaryWorkers++; if (primaryRawMaterial == Goods.ORE) { blacksmithAdded = true; } } } // Add a gunsmith: if (blacksmithAdded && getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && gunsmiths < MAX_LEVEL) { Building b = colony.getBuildingForProducing(Goods.MUSKETS); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, Goods.MUSKETS); workLocationPlans.add(wlp); colonistAdded = true; gunsmiths++; } } // Add builders if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && buildingReqProducer != null && buildingReqProducer.getProduction() * builders <= getProductionOf(buildingRawMat) && buildingReqProducer.getMaxUnits() < builders) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), buildingReqProducer, buildingReq); workLocationPlans.add(wlp); colonistAdded = true; builders++; } // TODO: Add worker to armory. colonistAdded = false; } // TODO: Add statesman // TODO: Add teacher // TODO: Add preacher }
public void create() { workLocationPlans.clear(); if (profile.getType() == ProfileType.OUTPOST) { GoodsType goodsType = profile.getPreferredProduction().get(0); workLocationPlans.add(new WorkLocationPlan(getAIMain(), getBestTileToProduce(goodsType), goodsType)); return; } Building townHall = colony.getBuildingForProducing(Goods.BELLS); // Choose the best production for each tile: for (ColonyTile ct : colony.getColonyTiles()) { if (ct.getWorkTile().getOwningSettlement() != null && ct.getWorkTile().getOwningSettlement() != colony || ct.isColonyCenterTile()) { continue; } GoodsType goodsType = getBestGoodsToProduce(ct.getWorkTile()); WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), ct, goodsType); workLocationPlans.add(wlp); } // We need to find what, if any, is still required for what we are building GoodsType buildingReq = null; GoodsType buildingRawMat = null; Building buildingReqProducer = null; buildingReq = getBuildingReqGoods(); if(buildingReq != null){ if(buildingReq == hammersType){ buildingRawMat = lumberType; } else{ buildingRawMat = oreType; } buildingReqProducer = colony.getBuildingForProducing(buildingReq); } // Try to ensure that we produce the raw material necessary for //what we are building boolean buildingRawMatReq = buildingRawMat != null && colony.getGoodsCount(buildingRawMat) < MIN_RAW_GOODS_THRESHOLD && getProductionOf(buildingRawMat) <= 0; if(buildingRawMatReq) { WorkLocationPlan bestChoice = null; int highestPotential = 0; Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); // TODO: find out about unit working here, if any (?) if (wlp.getWorkLocation() instanceof ColonyTile && ((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(buildingRawMat, null) > highestPotential) { highestPotential = ((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(buildingRawMat, null); bestChoice = wlp; } } if (highestPotential > 0) { // this must be true because it is the only way to // increase highestPotential assert bestChoice != null; bestChoice.setGoodsType(buildingRawMat); } } // Determine the primary and secondary types of goods: primaryRawMaterial = null; secondaryRawMaterial = null; int primaryRawMaterialProduction = 0; int secondaryRawMaterialProduction = 0; List<GoodsType> goodsTypeList = Specification.getSpecification().getGoodsTypeList(); for (GoodsType goodsType : goodsTypeList) { // only consider goods that can be transformed // do not consider hammers as a valid transformation if (goodsType.getProducedMaterial() == null || goodsType.getProducedMaterial() == hammersType) { continue; } if (getProductionOf(goodsType) > primaryRawMaterialProduction) { secondaryRawMaterial = primaryRawMaterial; secondaryRawMaterialProduction = primaryRawMaterialProduction; primaryRawMaterial = goodsType; primaryRawMaterialProduction = getProductionOf(goodsType); } else if (getProductionOf(goodsType) > secondaryRawMaterialProduction) { secondaryRawMaterial = goodsType; secondaryRawMaterialProduction = getProductionOf(goodsType); } } // Produce food instead of goods not being primary, secondary, lumber, // ore or silver: // Stop producing if the amount of goods being produced is too low: Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); if (!(wlp.getWorkLocation() instanceof ColonyTile)) { continue; } if (wlp.getGoodsType() == primaryRawMaterial || wlp.getGoodsType() == secondaryRawMaterial || wlp.getGoodsType() == Goods.LUMBER || wlp.getGoodsType() == Goods.ORE || wlp.getGoodsType() == Goods.SILVER) { continue; } // TODO: find out about unit working here, if any (?) if (((ColonyTile) wlp.getWorkLocation()).getWorkTile().potential(Goods.FOOD, null) <= 2) { if (wlp.getGoodsType() == null) { // on arctic tiles nothing can be produced wlpIterator.remove(); } else if (wlp.getProductionOf(wlp.getGoodsType()) <= 2) { // just a poor location wlpIterator.remove(); } continue; } wlp.setGoodsType(Goods.FOOD); } // Produce the goods required for what is being built, if: // - anything is being built, and // - there is either production or stock of the raw material if(buildingReq != null && (getProductionOf(buildingRawMat) > 0 || colony.getGoodsCount(buildingRawMat) > 0)){ WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), colony.getBuildingForProducing(buildingReq), buildingReq); workLocationPlans.add(wlp); } // Place a statesman: WorkLocationPlan townHallWlp = new WorkLocationPlan(getAIMain(), townHall, Goods.BELLS); workLocationPlans.add(townHallWlp); // Place a colonist to manufacture the primary goods: if (primaryRawMaterial != null) { GoodsType producedGoods = primaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); } } // Remove the secondary goods if we need food: if (secondaryRawMaterial != null && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION && secondaryRawMaterial.isNewWorldGoodsType()) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext()) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == secondaryRawMaterial) { Tile t = ((ColonyTile) wlp.getWorkLocation()).getWorkTile(); // TODO: find out about unit working here, if any (?) if (t.getMaximumPotential(Goods.FOOD, null) > 2) { wlp.setGoodsType(Goods.FOOD); } else { wlpIterator2.remove(); } } } } // Remove the workers on the primary goods one-by-one if we need food: if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == primaryRawMaterial) { Tile t = ((ColonyTile) wlp.getWorkLocation()).getWorkTile(); // TODO: find out about unit working here, if any (?) if (t.getMaximumPotential(Goods.FOOD, null) > 2) { wlp.setGoodsType(Goods.FOOD); } else { wlpIterator2.remove(); } } } } // Remove the manufacturer if we still lack food: if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof Building) { Building b = (Building) wlp.getWorkLocation(); if ( b != buildingReqProducer && b != townHall) { wlpIterator2.remove(); } } } } // Still lacking food // Remove the producers of the raw and/or non-raw materials required for the build // The decision of which to start depends on existence or not of stock of //raw materials GoodsType buildMatToGo = buildingReq; if(colony.getGoodsCount(buildingRawMat) > 0){ buildMatToGo = buildingRawMat; } if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { Iterator<WorkLocationPlan> wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == buildMatToGo) { wlpIterator2.remove(); } } // still lacking food, removing the rest if (getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { buildMatToGo = (buildMatToGo == buildingRawMat)? buildingReq : buildingRawMat; wlpIterator2 = workLocationPlans.iterator(); while (wlpIterator2.hasNext() && getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION) { WorkLocationPlan wlp = wlpIterator2.next(); if (wlp.getWorkLocation() instanceof ColonyTile && wlp.getGoodsType() == buildMatToGo) { wlpIterator2.remove(); } } } } // Primary allocations done // Beginning secondary allocations // Not enough food for more allocations, save work and stop here if(getFoodProduction() < workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2){ return; } int primaryWorkers = 1; int secondaryWorkers = 0; int builders = 1; int gunsmiths = 0; boolean colonistAdded = true; //XXX: This loop does not work, only goes through once, not as intended while (colonistAdded) { boolean blacksmithAdded = false; // Add a manufacturer for the secondary type of goods: if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && secondaryRawMaterial != null && 12 * secondaryWorkers + 6 <= getProductionOf(secondaryRawMaterial) && secondaryWorkers <= MAX_LEVEL) { GoodsType producedGoods = secondaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); colonistAdded = true; secondaryWorkers++; if (secondaryRawMaterial == Goods.ORE) { blacksmithAdded = true; } } } // Add a manufacturer for the primary type of goods: if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && primaryRawMaterial != null && 12 * primaryWorkers + 6 <= getProductionOf(primaryRawMaterial) && primaryWorkers <= MAX_LEVEL) { GoodsType producedGoods = primaryRawMaterial.getProducedMaterial(); Building b = colony.getBuildingForProducing(producedGoods); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, producedGoods); workLocationPlans.add(wlp); colonistAdded = true; primaryWorkers++; if (primaryRawMaterial == Goods.ORE) { blacksmithAdded = true; } } } // Add a gunsmith: if (blacksmithAdded && getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && gunsmiths < MAX_LEVEL) { Building b = colony.getBuildingForProducing(Goods.MUSKETS); if (b != null) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), b, Goods.MUSKETS); workLocationPlans.add(wlp); colonistAdded = true; gunsmiths++; } } // Add builders if (getFoodProduction() >= workLocationPlans.size() * Colony.FOOD_CONSUMPTION + 2 && buildingReqProducer != null && buildingReqProducer.getProduction() * builders <= getProductionOf(buildingRawMat) && buildingReqProducer.getMaxUnits() < builders) { WorkLocationPlan wlp = new WorkLocationPlan(getAIMain(), buildingReqProducer, buildingReq); workLocationPlans.add(wlp); colonistAdded = true; builders++; } // TODO: Add worker to armory. colonistAdded = false; } // TODO: Add statesman // TODO: Add teacher // TODO: Add preacher }
diff --git a/src/org/opensolaris/opengrok/web/DirectoryListing.java b/src/org/opensolaris/opengrok/web/DirectoryListing.java index 26e5038a..b5fabbd1 100644 --- a/src/org/opensolaris/opengrok/web/DirectoryListing.java +++ b/src/org/opensolaris/opengrok/web/DirectoryListing.java @@ -1,150 +1,150 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ package org.opensolaris.opengrok.web; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.Format; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.logging.Level; import org.opensolaris.opengrok.OpenGrokLogger; import org.opensolaris.opengrok.configuration.RuntimeEnvironment; import org.opensolaris.opengrok.index.IgnoredNames; /** * Generates HTML listing of a Directory */ public class DirectoryListing { private final EftarFileReader desc; private final long now; public DirectoryListing() { desc = null; now = System.currentTimeMillis(); } public DirectoryListing(EftarFileReader desc) { this.desc = desc; now = System.currentTimeMillis(); } public void listTo(File dir, Writer out) throws IOException { String[] files = dir.list(); if (files != null) { listTo(dir, out, dir.getPath(), files); } } /** * Write a listing of "dir" to "out" * * @param dir to be Listed * @param out writer to write * @param path Virtual Path of the directory * @param files childred of dir * @return a list of READMEs * @throws java.io.IOException * */ - public List listTo(File dir, Writer out, String path, String[] files) throws IOException { + public List<String> listTo(File dir, Writer out, String path, String[] files) throws IOException { Arrays.sort(files, String.CASE_INSENSITIVE_ORDER); boolean alt = true; Format dateFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()); out.write("<table cellspacing=\"0\" border=\"0\" id=\"dirlist\">"); EftarFileReader.FNode parentFNode = null; if (!"".equals(path)) { out.write("<tr><td colspan=\"4\"><a href=\"..\"><i>Up to higher level directory</i></a></td></tr>"); } if (desc != null) { parentFNode = desc.getNode(path); } out.write("<tr class=\"thead\"><th><tt>Name</tt></th><th><tt>Date</tt></th><th><tt>Size</tt></th>"); if (parentFNode != null && parentFNode.childOffset > 0) { out.write("<th><tt>Description</tt></th>"); } out.write("</tr>"); ArrayList<String> readMes = new ArrayList<String>(); IgnoredNames ignoredNames = RuntimeEnvironment.getInstance().getIgnoredNames(); for (String file : files) { if (!ignoredNames.ignore(file)) { File child = new File(dir, file); if (file.startsWith("README") || file.endsWith("README") || file.startsWith("readme")) { readMes.add(file); } alt = !alt; out.write("<tr align=\"right\""); out.write(alt ? " class=\"alt\"" : ""); boolean isDir = child.isDirectory(); out.write("><td align=\"left\"><tt><a href=\"" + Util.URIEncodePath(file) + (isDir ? "/\" class=\"r\"" : "\" class=\"p\"") + ">"); if (isDir) { out.write("<b>" + file + "</b></a>/"); } else { out.write(file + "</a>"); } Date lastm = new Date(child.lastModified()); out.write("</tt></td><td>" + ((now - lastm.getTime()) < 86400000 ? "Today" : dateFormatter.format(lastm)) + "</td>"); out.write("<td><tt>" + (isDir ? "" : Util.redableSize(child.length())) + "</tt></td>"); if (parentFNode != null && parentFNode.childOffset > 0) { String briefDesc = desc.getChildTag(parentFNode, file); if (briefDesc == null) { out.write("<td></td>"); } else { out.write("<td align=\"left\">"); out.write(briefDesc); out.write("</td>"); } } out.write("</tr>"); } } out.write("</table>"); return readMes; } public static void main(String[] args) { try { DirectoryListing dl = new DirectoryListing(); File tolist = new File(args[0]); File outFile = new File(args[1]); BufferedWriter out = new BufferedWriter(new FileWriter(outFile)); dl.listTo(tolist, out); out.close(); } catch (Exception e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Usage DirListing <dir> <output.html>", e); } } }
true
true
public List listTo(File dir, Writer out, String path, String[] files) throws IOException { Arrays.sort(files, String.CASE_INSENSITIVE_ORDER); boolean alt = true; Format dateFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()); out.write("<table cellspacing=\"0\" border=\"0\" id=\"dirlist\">"); EftarFileReader.FNode parentFNode = null; if (!"".equals(path)) { out.write("<tr><td colspan=\"4\"><a href=\"..\"><i>Up to higher level directory</i></a></td></tr>"); } if (desc != null) { parentFNode = desc.getNode(path); } out.write("<tr class=\"thead\"><th><tt>Name</tt></th><th><tt>Date</tt></th><th><tt>Size</tt></th>"); if (parentFNode != null && parentFNode.childOffset > 0) { out.write("<th><tt>Description</tt></th>"); } out.write("</tr>"); ArrayList<String> readMes = new ArrayList<String>(); IgnoredNames ignoredNames = RuntimeEnvironment.getInstance().getIgnoredNames(); for (String file : files) { if (!ignoredNames.ignore(file)) { File child = new File(dir, file); if (file.startsWith("README") || file.endsWith("README") || file.startsWith("readme")) { readMes.add(file); } alt = !alt; out.write("<tr align=\"right\""); out.write(alt ? " class=\"alt\"" : ""); boolean isDir = child.isDirectory(); out.write("><td align=\"left\"><tt><a href=\"" + Util.URIEncodePath(file) + (isDir ? "/\" class=\"r\"" : "\" class=\"p\"") + ">"); if (isDir) { out.write("<b>" + file + "</b></a>/"); } else { out.write(file + "</a>"); } Date lastm = new Date(child.lastModified()); out.write("</tt></td><td>" + ((now - lastm.getTime()) < 86400000 ? "Today" : dateFormatter.format(lastm)) + "</td>"); out.write("<td><tt>" + (isDir ? "" : Util.redableSize(child.length())) + "</tt></td>"); if (parentFNode != null && parentFNode.childOffset > 0) { String briefDesc = desc.getChildTag(parentFNode, file); if (briefDesc == null) { out.write("<td></td>"); } else { out.write("<td align=\"left\">"); out.write(briefDesc); out.write("</td>"); } } out.write("</tr>"); } } out.write("</table>"); return readMes; }
public List<String> listTo(File dir, Writer out, String path, String[] files) throws IOException { Arrays.sort(files, String.CASE_INSENSITIVE_ORDER); boolean alt = true; Format dateFormatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()); out.write("<table cellspacing=\"0\" border=\"0\" id=\"dirlist\">"); EftarFileReader.FNode parentFNode = null; if (!"".equals(path)) { out.write("<tr><td colspan=\"4\"><a href=\"..\"><i>Up to higher level directory</i></a></td></tr>"); } if (desc != null) { parentFNode = desc.getNode(path); } out.write("<tr class=\"thead\"><th><tt>Name</tt></th><th><tt>Date</tt></th><th><tt>Size</tt></th>"); if (parentFNode != null && parentFNode.childOffset > 0) { out.write("<th><tt>Description</tt></th>"); } out.write("</tr>"); ArrayList<String> readMes = new ArrayList<String>(); IgnoredNames ignoredNames = RuntimeEnvironment.getInstance().getIgnoredNames(); for (String file : files) { if (!ignoredNames.ignore(file)) { File child = new File(dir, file); if (file.startsWith("README") || file.endsWith("README") || file.startsWith("readme")) { readMes.add(file); } alt = !alt; out.write("<tr align=\"right\""); out.write(alt ? " class=\"alt\"" : ""); boolean isDir = child.isDirectory(); out.write("><td align=\"left\"><tt><a href=\"" + Util.URIEncodePath(file) + (isDir ? "/\" class=\"r\"" : "\" class=\"p\"") + ">"); if (isDir) { out.write("<b>" + file + "</b></a>/"); } else { out.write(file + "</a>"); } Date lastm = new Date(child.lastModified()); out.write("</tt></td><td>" + ((now - lastm.getTime()) < 86400000 ? "Today" : dateFormatter.format(lastm)) + "</td>"); out.write("<td><tt>" + (isDir ? "" : Util.redableSize(child.length())) + "</tt></td>"); if (parentFNode != null && parentFNode.childOffset > 0) { String briefDesc = desc.getChildTag(parentFNode, file); if (briefDesc == null) { out.write("<td></td>"); } else { out.write("<td align=\"left\">"); out.write(briefDesc); out.write("</td>"); } } out.write("</tr>"); } } out.write("</table>"); return readMes; }
diff --git a/gui/src/main/java/org/jboss/mbui/gui/reification/pipeline/IntegrityStep.java b/gui/src/main/java/org/jboss/mbui/gui/reification/pipeline/IntegrityStep.java index e3e006a0..cf9191f7 100644 --- a/gui/src/main/java/org/jboss/mbui/gui/reification/pipeline/IntegrityStep.java +++ b/gui/src/main/java/org/jboss/mbui/gui/reification/pipeline/IntegrityStep.java @@ -1,45 +1,45 @@ package org.jboss.mbui.gui.reification.pipeline; import com.allen_sauer.gwt.log.client.Log; import org.jboss.mbui.gui.behaviour.Integrity; import org.jboss.mbui.gui.behaviour.IntegrityErrors; import org.jboss.mbui.gui.behaviour.InteractionCoordinator; import org.jboss.mbui.gui.reification.Context; import org.jboss.mbui.gui.reification.ContextKey; import org.jboss.mbui.gui.reification.ReificationException; import org.jboss.mbui.model.Dialog; /** * @author Harald Pehl * @date 02/22/2013 */ public class IntegrityStep extends ReificationStep { public IntegrityStep() { super("integrity check"); } @Override public void execute(final Dialog dialog, final Context context) throws ReificationException { InteractionCoordinator coordinator = context.get(ContextKey.COORDINATOR); try { // Step 3: Verify integrity Integrity.check( dialog.getInterfaceModel(), coordinator.listProcedures() ); } catch (IntegrityErrors integrityErrors) { if (integrityErrors.needsToBeRaised()) { - Log.error("Integrity errors: " + integrityErrors.getMessage()); + Log.error(integrityErrors.getMessage()); // throw new RuntimeException("Integrity check failed", integrityErrors); } } } }
true
true
public void execute(final Dialog dialog, final Context context) throws ReificationException { InteractionCoordinator coordinator = context.get(ContextKey.COORDINATOR); try { // Step 3: Verify integrity Integrity.check( dialog.getInterfaceModel(), coordinator.listProcedures() ); } catch (IntegrityErrors integrityErrors) { if (integrityErrors.needsToBeRaised()) { Log.error("Integrity errors: " + integrityErrors.getMessage()); // throw new RuntimeException("Integrity check failed", integrityErrors); } } }
public void execute(final Dialog dialog, final Context context) throws ReificationException { InteractionCoordinator coordinator = context.get(ContextKey.COORDINATOR); try { // Step 3: Verify integrity Integrity.check( dialog.getInterfaceModel(), coordinator.listProcedures() ); } catch (IntegrityErrors integrityErrors) { if (integrityErrors.needsToBeRaised()) { Log.error(integrityErrors.getMessage()); // throw new RuntimeException("Integrity check failed", integrityErrors); } } }
diff --git a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/jsptag/ItemListTag.java b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/jsptag/ItemListTag.java index 89f61d6fa..e1fd1711d 100644 --- a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/jsptag/ItemListTag.java +++ b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/jsptag/ItemListTag.java @@ -1,864 +1,865 @@ /* * ItemListTag.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts * Institute of Technology. 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 Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * 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 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.webui.jsptag; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeManager; import org.dspace.browse.BrowseException; import org.dspace.browse.BrowseIndex; import org.dspace.browse.CrossLinks; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.DCDate; import org.dspace.content.DCValue; import org.dspace.content.Item; import org.dspace.content.Thumbnail; import org.dspace.content.service.ItemService; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.Utils; import org.dspace.sort.SortOption; import org.dspace.storage.bitstore.BitstreamStorageManager; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import java.util.StringTokenizer; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.jstl.fmt.LocaleSupport; import javax.servlet.jsp.tagext.TagSupport; /** * Tag for display a list of items * * @author Robert Tansley * @version $Revision$ */ public class ItemListTag extends TagSupport { private static Logger log = Logger.getLogger(ItemListTag.class); /** Items to display */ private Item[] items; /** Row to highlight, -1 for no row */ private int highlightRow = -1; /** Column to emphasise - null, "title" or "date" */ private String emphColumn; /** Config value of thumbnail view toggle */ private boolean showThumbs; /** Config browse/search width and height */ private int thumbItemListMaxWidth; private int thumbItemListMaxHeight; /** Config browse/search thumbnail link behaviour */ private boolean linkToBitstream = false; /** Config to include an edit link */ private boolean linkToEdit = false; /** Config to disable cross links */ private boolean disableCrossLinks = false; /** The default fields to be displayed when listing items */ private static String listFields; /** The default widths for the columns */ private static String listWidths; /** The default field which is bound to the browse by date */ private static String dateField = "dc.date.issued"; /** The default field which is bound to the browse by title */ private static String titleField = "dc.title"; private static String authorField = "dc.contributor.*"; private static int authorLimit = -1; private SortOption sortOption = null; public ItemListTag() { super(); getThumbSettings(); if (showThumbs) { listFields = "thumbnail, dc.date.issued(date), dc.title, dc.contributor.*"; listWidths = "*, 130, 60%, 40%"; } else { listFields = "dc.date.issued(date), dc.title, dc.contributor.*"; listWidths = "130, 60%, 40%"; } } public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest(); boolean emphasiseDate = false; boolean emphasiseTitle = false; if (emphColumn != null) { emphasiseDate = emphColumn.equalsIgnoreCase("date"); emphasiseTitle = emphColumn.equalsIgnoreCase("title"); } // get the elements to display String configLine = null; String widthLine = null; if (sortOption != null) { if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".widths"); } if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".widths"); } } if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist.columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist.widths"); } // Have we read a field configration from dspace.cfg? if (configLine != null) { // If thumbnails are disabled, strip out any thumbnail column from the configuration if (!showThumbs && configLine.contains("thumbnail")) { // Ensure we haven't got any nulls configLine = configLine == null ? "" : configLine; widthLine = widthLine == null ? "" : widthLine; // Tokenize the field and width lines StringTokenizer llt = new StringTokenizer(configLine, ","); StringTokenizer wlt = new StringTokenizer(widthLine, ","); StringBuilder newLLine = new StringBuilder(); StringBuilder newWLine = new StringBuilder(); while (llt.hasMoreTokens() || wlt.hasMoreTokens()) { String listTok = llt.hasMoreTokens() ? llt.nextToken() : null; String widthTok = wlt.hasMoreTokens() ? wlt.nextToken() : null; // Only use the Field and Width tokens, if the field isn't 'thumbnail' if (listTok == null || !listTok.trim().equals("thumbnail")) { if (listTok != null) { if (newLLine.length() > 0) newLLine.append(","); newLLine.append(listTok); } if (widthTok != null) { if (newWLine.length() > 0) newWLine.append(","); newWLine.append(widthTok); } } } // Use the newly built configuration file configLine = newLLine.toString(); widthLine = newWLine.toString(); } listFields = configLine; listWidths = widthLine; } // get the date and title fields String dateLine = ConfigurationManager.getProperty("webui.browse.index.date"); if (dateLine != null) { dateField = dateLine; } String titleLine = ConfigurationManager.getProperty("webui.browse.index.title"); if (titleLine != null) { titleField = titleLine; } String authorLine = ConfigurationManager.getProperty("webui.browse.author-field"); if (authorLine != null) { authorField = authorLine; } // Arrays used to hold the information we will require when outputting each row String[] fieldArr = listFields.split("\\s*,\\s*"); String[] widthArr = listWidths == null ? new String[0] : listWidths.split("\\s*,\\s*"); boolean isDate[] = new boolean[fieldArr.length]; boolean emph[] = new boolean[fieldArr.length]; boolean isAuthor[] = new boolean[fieldArr.length]; boolean viewFull[] = new boolean[fieldArr.length]; String[] browseType = new String[fieldArr.length]; String[] cOddOrEven = new String[fieldArr.length]; try { // Get the interlinking configuration too CrossLinks cl = new CrossLinks(); // Get a width for the table String tablewidth = ConfigurationManager.getProperty("webui.itemlist.tablewidth"); // If we have column widths, output a fixed layout table - faster for browsers to render // but not if we have to add an 'edit item' button - we can't know how big it will be if (widthArr.length > 0 && widthArr.length == fieldArr.length && !linkToEdit) { // If the table width has been specified, we can make this a fixed layout if (!StringUtils.isEmpty(tablewidth)) { out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } else { // Otherwise, don't constrain the width out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } // Output the known column widths out.print("<colgroup>"); for (int w = 0; w < widthArr.length; w++) { out.print("<col width=\""); // For a thumbnail column of width '*', use the configured max width for thumbnails if (fieldArr[w].equals("thumbnail") && widthArr[w].equals("*")) { out.print(thumbItemListMaxWidth); } else { out.print(StringUtils.isEmpty(widthArr[w]) ? "*" : widthArr[w]); } out.print("\" />"); } out.println("</colgroup>"); } else if (!StringUtils.isEmpty(tablewidth)) { out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } else { out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } // Output the table headers out.println("<tr>"); for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) { String field = fieldArr[colIdx].toLowerCase().trim(); cOddOrEven[colIdx] = (((colIdx + 1) % 2) == 0 ? "Odd" : "Even"); // find out if the field is a date if (field.indexOf("(date)") > 0) { field = field.replaceAll("\\(date\\)", ""); isDate[colIdx] = true; } // Cache any modifications to field fieldArr[colIdx] = field; // find out if this is the author column if (field.equals(authorField)) { isAuthor[colIdx] = true; } // find out if this field needs to link out to other browse views if (cl.hasLink(field)) { browseType[colIdx] = cl.getLinkType(field); viewFull[colIdx] = BrowseIndex.getBrowseIndex(browseType[colIdx]).isItemIndex(); } // find out if we are emphasising this field if (field.equals(emphColumn)) { emph[colIdx] = true; } else if ((field.equals(dateField) && emphasiseDate) || (field.equals(titleField) && emphasiseTitle)) { emph[colIdx] = true; } // prepare the strings for the header String id = "t" + Integer.toString(colIdx + 1); String css = "oddRow" + cOddOrEven[colIdx] + "Col"; String message = "itemlist." + field; // output the header out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[colIdx] ? "<strong>" : "") + LocaleSupport.getLocalizedMessage(pageContext, message) + (emph[colIdx] ? "</strong>" : "") + "</th>"); } if (linkToEdit) { String id = "t" + Integer.toString(cOddOrEven.length + 1); String css = "oddRow" + cOddOrEven[cOddOrEven.length - 2] + "Col"; // output the header out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[emph.length - 2] ? "<strong>" : "") + "&nbsp;" //LocaleSupport.getLocalizedMessage(pageContext, message) + (emph[emph.length - 2] ? "</strong>" : "") + "</th>"); } out.print("</tr>"); // now output each item row for (int i = 0; i < items.length; i++) { // now prepare the XHTML frag for this division + out.print("<tr>"); String rOddOrEven; if (i == highlightRow) { rOddOrEven = "highlight"; } else { rOddOrEven = ((i % 2) == 1 ? "odd" : "even"); } for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) { String field = fieldArr[colIdx]; // get the schema and the element qualifier pair // (Note, the schema is not used for anything yet) // (second note, I hate this bit of code. There must be // a much more elegant way of doing this. Tomcat has // some weird problems with variations on this code that // I tried, which is why it has ended up the way it is) StringTokenizer eq = new StringTokenizer(field, "."); String[] tokens = { "", "", "" }; int k = 0; while(eq.hasMoreTokens()) { tokens[k] = eq.nextToken().toLowerCase().trim(); k++; } String schema = tokens[0]; String element = tokens[1]; String qualifier = tokens[2]; // first get hold of the relevant metadata for this column DCValue[] metadataArray; if (qualifier.equals("*")) { metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY); } else if (qualifier.equals("")) { metadataArray = items[i].getMetadata(schema, element, null, Item.ANY); } else { metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY); } // save on a null check which would make the code untidy if (metadataArray == null) { metadataArray = new DCValue[0]; } // now prepare the content of the table division String metadata = "-"; if (field.equals("thumbnail")) { metadata = getThumbMarkup(hrq, items[i]); } if (metadataArray.length > 0) { // format the date field correctly if (isDate[colIdx]) { DCDate dd = new DCDate(metadataArray[0].value); metadata = UIUtil.displayDate(dd, false, false, hrq); } // format the title field correctly for withdrawn items (ie. don't link) else if (field.equals(titleField) && items[i].isWithdrawn()) { metadata = Utils.addEntities(metadataArray[0].value); } // format the title field correctly else if (field.equals(titleField)) { metadata = "<a href=\"" + hrq.getContextPath() + "/handle/" + items[i].getHandle() + "\">" + Utils.addEntities(metadataArray[0].value) + "</a>"; } // format all other fields else { // limit the number of records if this is the author field (if // -1, then the limit is the full list) boolean truncated = false; int loopLimit = metadataArray.length; if (isAuthor[colIdx]) { int fieldMax = (authorLimit > 0 ? authorLimit : metadataArray.length); loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax); truncated = (fieldMax < metadataArray.length); log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit) + " from an original " + Integer.toString(metadataArray.length)); } StringBuffer sb = new StringBuffer(); for (int j = 0; j < loopLimit; j++) { String startLink = ""; String endLink = ""; if (!StringUtils.isEmpty(browseType[colIdx]) && !disableCrossLinks) { String argument = "value"; if (viewFull[colIdx]) { argument = "vfocus"; } startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type=" + browseType[colIdx] + "&amp;" + argument + "=" + Utils.addEntities(metadataArray[j].value); if (metadataArray[j].language != null) { startLink = startLink + "&amp;" + argument + "_lang=" + Utils.addEntities(metadataArray[j].language) + "\">"; } else { startLink = startLink + "\">"; } endLink = "</a>"; } sb.append(startLink); sb.append(Utils.addEntities(metadataArray[j].value)); sb.append(endLink); if (j < (loopLimit - 1)) { sb.append("; "); } } if (truncated) { String etal = LocaleSupport.getLocalizedMessage(pageContext, "itemlist.et-al"); sb.append(", " + etal); } metadata = "<em>" + sb.toString() + "</em>"; } } // prepare extra special layout requirements for dates String extras = ""; if (isDate[colIdx]) { extras = "nowrap=\"nowrap\" align=\"right\""; } String id = "t" + Integer.toString(colIdx + 1); out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[colIdx] + "Col\" " + extras + ">" + (emph[colIdx] ? "<strong>" : "") + metadata + (emph[colIdx] ? "</strong>" : "") + "</td>"); } // Add column for 'edit item' links if (linkToEdit) { String id = "t" + Integer.toString(cOddOrEven.length + 1); out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[cOddOrEven.length - 2] + "Col\" nowrap>" - + "<form method=get action=\"" + hrq.getContextPath() + "/tools/edit-item\">" + + "<form method=\"get\" action=\"" + hrq.getContextPath() + "/tools/edit-item\">" + "<input type=\"hidden\" name=\"handle\" value=\"" + items[i].getHandle() + "\" />" + "<input type=\"submit\" value=\"Edit Item\" /></form>" + "</td>"); } out.println("</tr>"); } // close the table out.println("</table>"); } catch (IOException ie) { throw new JspException(ie); } catch (BrowseException e) { throw new JspException(e); } return SKIP_BODY; } public int getAuthorLimit() { return authorLimit; } public void setAuthorLimit(int al) { authorLimit = al; } public boolean getLinkToEdit() { return linkToEdit; } public void setLinkToEdit(boolean edit) { this.linkToEdit = edit; } public boolean getDisableCrossLinks() { return disableCrossLinks; } public void setDisableCrossLinks(boolean links) { this.disableCrossLinks = links; } public SortOption getSortOption() { return sortOption; } public void setSortOption(SortOption so) { sortOption = so; } /** * Get the items to list * * @return the items */ public Item[] getItems() { return items; } /** * Set the items to list * * @param itemsIn * the items */ public void setItems(Item[] itemsIn) { items = itemsIn; } /** * Get the row to highlight - null or -1 for no row * * @return the row to highlight */ public String getHighlightrow() { return String.valueOf(highlightRow); } /** * Set the row to highlight * * @param highlightRowIn * the row to highlight or -1 for no highlight */ public void setHighlightrow(String highlightRowIn) { if ((highlightRowIn == null) || highlightRowIn.equals("")) { highlightRow = -1; } else { try { highlightRow = Integer.parseInt(highlightRowIn); } catch (NumberFormatException nfe) { highlightRow = -1; } } } /** * Get the column to emphasise - "title", "date" or null * * @return the column to emphasise */ public String getEmphcolumn() { return emphColumn; } /** * Set the column to emphasise - "title", "date" or null * * @param emphColumnIn * column to emphasise */ public void setEmphcolumn(String emphColumnIn) { emphColumn = emphColumnIn; } public void release() { highlightRow = -1; emphColumn = null; items = null; } /* get the required thumbnail config items */ private void getThumbSettings() { showThumbs = ConfigurationManager .getBooleanProperty("webui.browse.thumbnail.show"); if (showThumbs) { thumbItemListMaxHeight = ConfigurationManager .getIntProperty("webui.browse.thumbnail.maxheight"); if (thumbItemListMaxHeight == 0) { thumbItemListMaxHeight = ConfigurationManager .getIntProperty("thumbnail.maxheight"); } thumbItemListMaxWidth = ConfigurationManager .getIntProperty("webui.browse.thumbnail.maxwidth"); if (thumbItemListMaxWidth == 0) { thumbItemListMaxWidth = ConfigurationManager .getIntProperty("thumbnail.maxwidth"); } } String linkBehaviour = ConfigurationManager .getProperty("webui.browse.thumbnail.linkbehaviour"); if (linkBehaviour != null) { if (linkBehaviour.equals("bitstream")) { linkToBitstream = true; } } } /* * Get the (X)HTML width and height attributes. As the browser is being used * for scaling, we only scale down otherwise we'll get hideously chunky * images. This means the media filter should be run with the maxheight and * maxwidth set greater than or equal to the size of the images required in * the search/browse */ private String getScalingAttr(HttpServletRequest hrq, Bitstream bitstream) throws JspException { BufferedImage buf; try { Context c = UIUtil.obtainContext(hrq); InputStream is = BitstreamStorageManager.retrieve(c, bitstream .getID()); //AuthorizeManager.authorizeAction(bContext, this, Constants.READ); // read in bitstream's image buf = ImageIO.read(is); is.close(); } catch (SQLException sqle) { throw new JspException(sqle.getMessage()); } catch (IOException ioe) { throw new JspException(ioe.getMessage()); } // now get the image dimensions float xsize = (float) buf.getWidth(null); float ysize = (float) buf.getHeight(null); // scale by x first if needed if (xsize > (float) thumbItemListMaxWidth) { // calculate scaling factor so that xsize * scale = new size (max) float scale_factor = (float) thumbItemListMaxWidth / xsize; // now reduce x size and y size xsize = xsize * scale_factor; ysize = ysize * scale_factor; } // scale by y if needed if (ysize > (float) thumbItemListMaxHeight) { float scale_factor = (float) thumbItemListMaxHeight / ysize; // now reduce x size // and y size xsize = xsize * scale_factor; ysize = ysize * scale_factor; } StringBuffer sb = new StringBuffer("width=\"").append(xsize).append( "\" height=\"").append(ysize).append("\""); return sb.toString(); } /* generate the (X)HTML required to show the thumbnail */ private String getThumbMarkup(HttpServletRequest hrq, Item item) throws JspException { try { Context c = UIUtil.obtainContext(hrq); Thumbnail thumbnail = ItemService.getThumbnail(c, item.getID(), linkToBitstream); if (thumbnail == null) { return ""; } StringBuffer thumbFrag = new StringBuffer(); if (linkToBitstream) { Bitstream original = thumbnail.getOriginal(); String link = hrq.getContextPath() + "/bitstream/" + item.getHandle() + "/" + original.getSequenceID() + "/" + UIUtil.encodeBitstreamName(original.getName(), Constants.DEFAULT_ENCODING); thumbFrag.append("<a target=\"_blank\" href=\"" + link + "\" />"); } else { String link = hrq.getContextPath() + "/handle/" + item.getHandle(); thumbFrag.append("<a href=\"" + link + "\" />"); } Bitstream thumb = thumbnail.getThumb(); String img = hrq.getContextPath() + "/retrieve/" + thumb.getID() + "/" + UIUtil.encodeBitstreamName(thumb.getName(), Constants.DEFAULT_ENCODING); String alt = thumb.getName(); String scAttr = getScalingAttr(hrq, thumb); thumbFrag.append("<img src=\"") .append(img) .append("\" alt=\"") .append(alt + "\" ") .append(scAttr) .append("/ border=\"0\"></a>"); return thumbFrag.toString(); } catch (SQLException sqle) { throw new JspException(sqle.getMessage()); } catch (UnsupportedEncodingException e) { throw new JspException("Server does not support DSpace's default encoding. ", e); } } }
false
true
public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest(); boolean emphasiseDate = false; boolean emphasiseTitle = false; if (emphColumn != null) { emphasiseDate = emphColumn.equalsIgnoreCase("date"); emphasiseTitle = emphColumn.equalsIgnoreCase("title"); } // get the elements to display String configLine = null; String widthLine = null; if (sortOption != null) { if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".widths"); } if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".widths"); } } if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist.columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist.widths"); } // Have we read a field configration from dspace.cfg? if (configLine != null) { // If thumbnails are disabled, strip out any thumbnail column from the configuration if (!showThumbs && configLine.contains("thumbnail")) { // Ensure we haven't got any nulls configLine = configLine == null ? "" : configLine; widthLine = widthLine == null ? "" : widthLine; // Tokenize the field and width lines StringTokenizer llt = new StringTokenizer(configLine, ","); StringTokenizer wlt = new StringTokenizer(widthLine, ","); StringBuilder newLLine = new StringBuilder(); StringBuilder newWLine = new StringBuilder(); while (llt.hasMoreTokens() || wlt.hasMoreTokens()) { String listTok = llt.hasMoreTokens() ? llt.nextToken() : null; String widthTok = wlt.hasMoreTokens() ? wlt.nextToken() : null; // Only use the Field and Width tokens, if the field isn't 'thumbnail' if (listTok == null || !listTok.trim().equals("thumbnail")) { if (listTok != null) { if (newLLine.length() > 0) newLLine.append(","); newLLine.append(listTok); } if (widthTok != null) { if (newWLine.length() > 0) newWLine.append(","); newWLine.append(widthTok); } } } // Use the newly built configuration file configLine = newLLine.toString(); widthLine = newWLine.toString(); } listFields = configLine; listWidths = widthLine; } // get the date and title fields String dateLine = ConfigurationManager.getProperty("webui.browse.index.date"); if (dateLine != null) { dateField = dateLine; } String titleLine = ConfigurationManager.getProperty("webui.browse.index.title"); if (titleLine != null) { titleField = titleLine; } String authorLine = ConfigurationManager.getProperty("webui.browse.author-field"); if (authorLine != null) { authorField = authorLine; } // Arrays used to hold the information we will require when outputting each row String[] fieldArr = listFields.split("\\s*,\\s*"); String[] widthArr = listWidths == null ? new String[0] : listWidths.split("\\s*,\\s*"); boolean isDate[] = new boolean[fieldArr.length]; boolean emph[] = new boolean[fieldArr.length]; boolean isAuthor[] = new boolean[fieldArr.length]; boolean viewFull[] = new boolean[fieldArr.length]; String[] browseType = new String[fieldArr.length]; String[] cOddOrEven = new String[fieldArr.length]; try { // Get the interlinking configuration too CrossLinks cl = new CrossLinks(); // Get a width for the table String tablewidth = ConfigurationManager.getProperty("webui.itemlist.tablewidth"); // If we have column widths, output a fixed layout table - faster for browsers to render // but not if we have to add an 'edit item' button - we can't know how big it will be if (widthArr.length > 0 && widthArr.length == fieldArr.length && !linkToEdit) { // If the table width has been specified, we can make this a fixed layout if (!StringUtils.isEmpty(tablewidth)) { out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } else { // Otherwise, don't constrain the width out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } // Output the known column widths out.print("<colgroup>"); for (int w = 0; w < widthArr.length; w++) { out.print("<col width=\""); // For a thumbnail column of width '*', use the configured max width for thumbnails if (fieldArr[w].equals("thumbnail") && widthArr[w].equals("*")) { out.print(thumbItemListMaxWidth); } else { out.print(StringUtils.isEmpty(widthArr[w]) ? "*" : widthArr[w]); } out.print("\" />"); } out.println("</colgroup>"); } else if (!StringUtils.isEmpty(tablewidth)) { out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } else { out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } // Output the table headers out.println("<tr>"); for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) { String field = fieldArr[colIdx].toLowerCase().trim(); cOddOrEven[colIdx] = (((colIdx + 1) % 2) == 0 ? "Odd" : "Even"); // find out if the field is a date if (field.indexOf("(date)") > 0) { field = field.replaceAll("\\(date\\)", ""); isDate[colIdx] = true; } // Cache any modifications to field fieldArr[colIdx] = field; // find out if this is the author column if (field.equals(authorField)) { isAuthor[colIdx] = true; } // find out if this field needs to link out to other browse views if (cl.hasLink(field)) { browseType[colIdx] = cl.getLinkType(field); viewFull[colIdx] = BrowseIndex.getBrowseIndex(browseType[colIdx]).isItemIndex(); } // find out if we are emphasising this field if (field.equals(emphColumn)) { emph[colIdx] = true; } else if ((field.equals(dateField) && emphasiseDate) || (field.equals(titleField) && emphasiseTitle)) { emph[colIdx] = true; } // prepare the strings for the header String id = "t" + Integer.toString(colIdx + 1); String css = "oddRow" + cOddOrEven[colIdx] + "Col"; String message = "itemlist." + field; // output the header out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[colIdx] ? "<strong>" : "") + LocaleSupport.getLocalizedMessage(pageContext, message) + (emph[colIdx] ? "</strong>" : "") + "</th>"); } if (linkToEdit) { String id = "t" + Integer.toString(cOddOrEven.length + 1); String css = "oddRow" + cOddOrEven[cOddOrEven.length - 2] + "Col"; // output the header out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[emph.length - 2] ? "<strong>" : "") + "&nbsp;" //LocaleSupport.getLocalizedMessage(pageContext, message) + (emph[emph.length - 2] ? "</strong>" : "") + "</th>"); } out.print("</tr>"); // now output each item row for (int i = 0; i < items.length; i++) { // now prepare the XHTML frag for this division String rOddOrEven; if (i == highlightRow) { rOddOrEven = "highlight"; } else { rOddOrEven = ((i % 2) == 1 ? "odd" : "even"); } for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) { String field = fieldArr[colIdx]; // get the schema and the element qualifier pair // (Note, the schema is not used for anything yet) // (second note, I hate this bit of code. There must be // a much more elegant way of doing this. Tomcat has // some weird problems with variations on this code that // I tried, which is why it has ended up the way it is) StringTokenizer eq = new StringTokenizer(field, "."); String[] tokens = { "", "", "" }; int k = 0; while(eq.hasMoreTokens()) { tokens[k] = eq.nextToken().toLowerCase().trim(); k++; } String schema = tokens[0]; String element = tokens[1]; String qualifier = tokens[2]; // first get hold of the relevant metadata for this column DCValue[] metadataArray; if (qualifier.equals("*")) { metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY); } else if (qualifier.equals("")) { metadataArray = items[i].getMetadata(schema, element, null, Item.ANY); } else { metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY); } // save on a null check which would make the code untidy if (metadataArray == null) { metadataArray = new DCValue[0]; } // now prepare the content of the table division String metadata = "-"; if (field.equals("thumbnail")) { metadata = getThumbMarkup(hrq, items[i]); } if (metadataArray.length > 0) { // format the date field correctly if (isDate[colIdx]) { DCDate dd = new DCDate(metadataArray[0].value); metadata = UIUtil.displayDate(dd, false, false, hrq); } // format the title field correctly for withdrawn items (ie. don't link) else if (field.equals(titleField) && items[i].isWithdrawn()) { metadata = Utils.addEntities(metadataArray[0].value); } // format the title field correctly else if (field.equals(titleField)) { metadata = "<a href=\"" + hrq.getContextPath() + "/handle/" + items[i].getHandle() + "\">" + Utils.addEntities(metadataArray[0].value) + "</a>"; } // format all other fields else { // limit the number of records if this is the author field (if // -1, then the limit is the full list) boolean truncated = false; int loopLimit = metadataArray.length; if (isAuthor[colIdx]) { int fieldMax = (authorLimit > 0 ? authorLimit : metadataArray.length); loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax); truncated = (fieldMax < metadataArray.length); log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit) + " from an original " + Integer.toString(metadataArray.length)); } StringBuffer sb = new StringBuffer(); for (int j = 0; j < loopLimit; j++) { String startLink = ""; String endLink = ""; if (!StringUtils.isEmpty(browseType[colIdx]) && !disableCrossLinks) { String argument = "value"; if (viewFull[colIdx]) { argument = "vfocus"; } startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type=" + browseType[colIdx] + "&amp;" + argument + "=" + Utils.addEntities(metadataArray[j].value); if (metadataArray[j].language != null) { startLink = startLink + "&amp;" + argument + "_lang=" + Utils.addEntities(metadataArray[j].language) + "\">"; } else { startLink = startLink + "\">"; } endLink = "</a>"; } sb.append(startLink); sb.append(Utils.addEntities(metadataArray[j].value)); sb.append(endLink); if (j < (loopLimit - 1)) { sb.append("; "); } } if (truncated) { String etal = LocaleSupport.getLocalizedMessage(pageContext, "itemlist.et-al"); sb.append(", " + etal); } metadata = "<em>" + sb.toString() + "</em>"; } } // prepare extra special layout requirements for dates String extras = ""; if (isDate[colIdx]) { extras = "nowrap=\"nowrap\" align=\"right\""; } String id = "t" + Integer.toString(colIdx + 1); out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[colIdx] + "Col\" " + extras + ">" + (emph[colIdx] ? "<strong>" : "") + metadata + (emph[colIdx] ? "</strong>" : "") + "</td>"); } // Add column for 'edit item' links if (linkToEdit) { String id = "t" + Integer.toString(cOddOrEven.length + 1); out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[cOddOrEven.length - 2] + "Col\" nowrap>" + "<form method=get action=\"" + hrq.getContextPath() + "/tools/edit-item\">" + "<input type=\"hidden\" name=\"handle\" value=\"" + items[i].getHandle() + "\" />" + "<input type=\"submit\" value=\"Edit Item\" /></form>" + "</td>"); } out.println("</tr>"); } // close the table out.println("</table>"); } catch (IOException ie) { throw new JspException(ie); } catch (BrowseException e) { throw new JspException(e); } return SKIP_BODY; }
public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); HttpServletRequest hrq = (HttpServletRequest) pageContext.getRequest(); boolean emphasiseDate = false; boolean emphasiseTitle = false; if (emphColumn != null) { emphasiseDate = emphColumn.equalsIgnoreCase("date"); emphasiseTitle = emphColumn.equalsIgnoreCase("title"); } // get the elements to display String configLine = null; String widthLine = null; if (sortOption != null) { if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist.sort." + sortOption.getName() + ".widths"); } if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist." + sortOption.getName() + ".widths"); } } if (configLine == null) { configLine = ConfigurationManager.getProperty("webui.itemlist.columns"); widthLine = ConfigurationManager.getProperty("webui.itemlist.widths"); } // Have we read a field configration from dspace.cfg? if (configLine != null) { // If thumbnails are disabled, strip out any thumbnail column from the configuration if (!showThumbs && configLine.contains("thumbnail")) { // Ensure we haven't got any nulls configLine = configLine == null ? "" : configLine; widthLine = widthLine == null ? "" : widthLine; // Tokenize the field and width lines StringTokenizer llt = new StringTokenizer(configLine, ","); StringTokenizer wlt = new StringTokenizer(widthLine, ","); StringBuilder newLLine = new StringBuilder(); StringBuilder newWLine = new StringBuilder(); while (llt.hasMoreTokens() || wlt.hasMoreTokens()) { String listTok = llt.hasMoreTokens() ? llt.nextToken() : null; String widthTok = wlt.hasMoreTokens() ? wlt.nextToken() : null; // Only use the Field and Width tokens, if the field isn't 'thumbnail' if (listTok == null || !listTok.trim().equals("thumbnail")) { if (listTok != null) { if (newLLine.length() > 0) newLLine.append(","); newLLine.append(listTok); } if (widthTok != null) { if (newWLine.length() > 0) newWLine.append(","); newWLine.append(widthTok); } } } // Use the newly built configuration file configLine = newLLine.toString(); widthLine = newWLine.toString(); } listFields = configLine; listWidths = widthLine; } // get the date and title fields String dateLine = ConfigurationManager.getProperty("webui.browse.index.date"); if (dateLine != null) { dateField = dateLine; } String titleLine = ConfigurationManager.getProperty("webui.browse.index.title"); if (titleLine != null) { titleField = titleLine; } String authorLine = ConfigurationManager.getProperty("webui.browse.author-field"); if (authorLine != null) { authorField = authorLine; } // Arrays used to hold the information we will require when outputting each row String[] fieldArr = listFields.split("\\s*,\\s*"); String[] widthArr = listWidths == null ? new String[0] : listWidths.split("\\s*,\\s*"); boolean isDate[] = new boolean[fieldArr.length]; boolean emph[] = new boolean[fieldArr.length]; boolean isAuthor[] = new boolean[fieldArr.length]; boolean viewFull[] = new boolean[fieldArr.length]; String[] browseType = new String[fieldArr.length]; String[] cOddOrEven = new String[fieldArr.length]; try { // Get the interlinking configuration too CrossLinks cl = new CrossLinks(); // Get a width for the table String tablewidth = ConfigurationManager.getProperty("webui.itemlist.tablewidth"); // If we have column widths, output a fixed layout table - faster for browsers to render // but not if we have to add an 'edit item' button - we can't know how big it will be if (widthArr.length > 0 && widthArr.length == fieldArr.length && !linkToEdit) { // If the table width has been specified, we can make this a fixed layout if (!StringUtils.isEmpty(tablewidth)) { out.println("<table style=\"width: " + tablewidth + "; table-layout: fixed;\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } else { // Otherwise, don't constrain the width out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } // Output the known column widths out.print("<colgroup>"); for (int w = 0; w < widthArr.length; w++) { out.print("<col width=\""); // For a thumbnail column of width '*', use the configured max width for thumbnails if (fieldArr[w].equals("thumbnail") && widthArr[w].equals("*")) { out.print(thumbItemListMaxWidth); } else { out.print(StringUtils.isEmpty(widthArr[w]) ? "*" : widthArr[w]); } out.print("\" />"); } out.println("</colgroup>"); } else if (!StringUtils.isEmpty(tablewidth)) { out.println("<table width=\"" + tablewidth + "\" align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } else { out.println("<table align=\"center\" class=\"miscTable\" summary=\"This table browses all dspace content\">"); } // Output the table headers out.println("<tr>"); for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) { String field = fieldArr[colIdx].toLowerCase().trim(); cOddOrEven[colIdx] = (((colIdx + 1) % 2) == 0 ? "Odd" : "Even"); // find out if the field is a date if (field.indexOf("(date)") > 0) { field = field.replaceAll("\\(date\\)", ""); isDate[colIdx] = true; } // Cache any modifications to field fieldArr[colIdx] = field; // find out if this is the author column if (field.equals(authorField)) { isAuthor[colIdx] = true; } // find out if this field needs to link out to other browse views if (cl.hasLink(field)) { browseType[colIdx] = cl.getLinkType(field); viewFull[colIdx] = BrowseIndex.getBrowseIndex(browseType[colIdx]).isItemIndex(); } // find out if we are emphasising this field if (field.equals(emphColumn)) { emph[colIdx] = true; } else if ((field.equals(dateField) && emphasiseDate) || (field.equals(titleField) && emphasiseTitle)) { emph[colIdx] = true; } // prepare the strings for the header String id = "t" + Integer.toString(colIdx + 1); String css = "oddRow" + cOddOrEven[colIdx] + "Col"; String message = "itemlist." + field; // output the header out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[colIdx] ? "<strong>" : "") + LocaleSupport.getLocalizedMessage(pageContext, message) + (emph[colIdx] ? "</strong>" : "") + "</th>"); } if (linkToEdit) { String id = "t" + Integer.toString(cOddOrEven.length + 1); String css = "oddRow" + cOddOrEven[cOddOrEven.length - 2] + "Col"; // output the header out.print("<th id=\"" + id + "\" class=\"" + css + "\">" + (emph[emph.length - 2] ? "<strong>" : "") + "&nbsp;" //LocaleSupport.getLocalizedMessage(pageContext, message) + (emph[emph.length - 2] ? "</strong>" : "") + "</th>"); } out.print("</tr>"); // now output each item row for (int i = 0; i < items.length; i++) { // now prepare the XHTML frag for this division out.print("<tr>"); String rOddOrEven; if (i == highlightRow) { rOddOrEven = "highlight"; } else { rOddOrEven = ((i % 2) == 1 ? "odd" : "even"); } for (int colIdx = 0; colIdx < fieldArr.length; colIdx++) { String field = fieldArr[colIdx]; // get the schema and the element qualifier pair // (Note, the schema is not used for anything yet) // (second note, I hate this bit of code. There must be // a much more elegant way of doing this. Tomcat has // some weird problems with variations on this code that // I tried, which is why it has ended up the way it is) StringTokenizer eq = new StringTokenizer(field, "."); String[] tokens = { "", "", "" }; int k = 0; while(eq.hasMoreTokens()) { tokens[k] = eq.nextToken().toLowerCase().trim(); k++; } String schema = tokens[0]; String element = tokens[1]; String qualifier = tokens[2]; // first get hold of the relevant metadata for this column DCValue[] metadataArray; if (qualifier.equals("*")) { metadataArray = items[i].getMetadata(schema, element, Item.ANY, Item.ANY); } else if (qualifier.equals("")) { metadataArray = items[i].getMetadata(schema, element, null, Item.ANY); } else { metadataArray = items[i].getMetadata(schema, element, qualifier, Item.ANY); } // save on a null check which would make the code untidy if (metadataArray == null) { metadataArray = new DCValue[0]; } // now prepare the content of the table division String metadata = "-"; if (field.equals("thumbnail")) { metadata = getThumbMarkup(hrq, items[i]); } if (metadataArray.length > 0) { // format the date field correctly if (isDate[colIdx]) { DCDate dd = new DCDate(metadataArray[0].value); metadata = UIUtil.displayDate(dd, false, false, hrq); } // format the title field correctly for withdrawn items (ie. don't link) else if (field.equals(titleField) && items[i].isWithdrawn()) { metadata = Utils.addEntities(metadataArray[0].value); } // format the title field correctly else if (field.equals(titleField)) { metadata = "<a href=\"" + hrq.getContextPath() + "/handle/" + items[i].getHandle() + "\">" + Utils.addEntities(metadataArray[0].value) + "</a>"; } // format all other fields else { // limit the number of records if this is the author field (if // -1, then the limit is the full list) boolean truncated = false; int loopLimit = metadataArray.length; if (isAuthor[colIdx]) { int fieldMax = (authorLimit > 0 ? authorLimit : metadataArray.length); loopLimit = (fieldMax > metadataArray.length ? metadataArray.length : fieldMax); truncated = (fieldMax < metadataArray.length); log.debug("Limiting output of field " + field + " to " + Integer.toString(loopLimit) + " from an original " + Integer.toString(metadataArray.length)); } StringBuffer sb = new StringBuffer(); for (int j = 0; j < loopLimit; j++) { String startLink = ""; String endLink = ""; if (!StringUtils.isEmpty(browseType[colIdx]) && !disableCrossLinks) { String argument = "value"; if (viewFull[colIdx]) { argument = "vfocus"; } startLink = "<a href=\"" + hrq.getContextPath() + "/browse?type=" + browseType[colIdx] + "&amp;" + argument + "=" + Utils.addEntities(metadataArray[j].value); if (metadataArray[j].language != null) { startLink = startLink + "&amp;" + argument + "_lang=" + Utils.addEntities(metadataArray[j].language) + "\">"; } else { startLink = startLink + "\">"; } endLink = "</a>"; } sb.append(startLink); sb.append(Utils.addEntities(metadataArray[j].value)); sb.append(endLink); if (j < (loopLimit - 1)) { sb.append("; "); } } if (truncated) { String etal = LocaleSupport.getLocalizedMessage(pageContext, "itemlist.et-al"); sb.append(", " + etal); } metadata = "<em>" + sb.toString() + "</em>"; } } // prepare extra special layout requirements for dates String extras = ""; if (isDate[colIdx]) { extras = "nowrap=\"nowrap\" align=\"right\""; } String id = "t" + Integer.toString(colIdx + 1); out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[colIdx] + "Col\" " + extras + ">" + (emph[colIdx] ? "<strong>" : "") + metadata + (emph[colIdx] ? "</strong>" : "") + "</td>"); } // Add column for 'edit item' links if (linkToEdit) { String id = "t" + Integer.toString(cOddOrEven.length + 1); out.print("<td headers=\"" + id + "\" class=\"" + rOddOrEven + "Row" + cOddOrEven[cOddOrEven.length - 2] + "Col\" nowrap>" + "<form method=\"get\" action=\"" + hrq.getContextPath() + "/tools/edit-item\">" + "<input type=\"hidden\" name=\"handle\" value=\"" + items[i].getHandle() + "\" />" + "<input type=\"submit\" value=\"Edit Item\" /></form>" + "</td>"); } out.println("</tr>"); } // close the table out.println("</table>"); } catch (IOException ie) { throw new JspException(ie); } catch (BrowseException e) { throw new JspException(e); } return SKIP_BODY; }
diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index 020cd47f0..1e32bd560 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -1,1882 +1,1883 @@ package cgeo.geocaching.maps; import cgeo.geocaching.R; import cgeo.geocaching.Settings; import cgeo.geocaching.Settings.mapSourceEnum; import cgeo.geocaching.cgBase; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgCoord; import cgeo.geocaching.cgDirection; import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgUpdateDir; import cgeo.geocaching.cgUpdateLoc; import cgeo.geocaching.cgUser; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.cgeocaches; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl; import cgeo.geocaching.maps.interfaces.GeoPointImpl; import cgeo.geocaching.maps.interfaces.MapActivityImpl; import cgeo.geocaching.maps.interfaces.MapControllerImpl; import cgeo.geocaching.maps.interfaces.MapFactory; import cgeo.geocaching.maps.interfaces.MapViewImpl; import cgeo.geocaching.maps.interfaces.OnDragListener; import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.TextView; import android.widget.ViewSwitcher.ViewFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; /** * Class representing the Map in c:geo */ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory { private static final String EXTRAS_GEOCODE = "geocode"; private static final String EXTRAS_LONGITUDE = "longitude"; private static final String EXTRAS_LATITUDE = "latitude"; private static final String EXTRAS_WPTTYPE = "wpttype"; private static final String EXTRAS_MAPSTATE = "mapstate"; private static final String EXTRAS_SEARCHID = "searchid"; private static final String EXTRAS_DETAIL = "detail"; private static final int MENU_SELECT_MAPVIEW = 1; private static final int MENU_MAP_LIVE = 2; private static final int MENU_STORE_CACHES = 3; private static final int MENU_TRAIL_MODE = 4; private static final int MENU_CIRCLE_MODE = 5; private static final int MENU_AS_LIST = 6; private static final int SUBMENU_VIEW_GOOGLE_MAP = 10; private static final int SUBMENU_VIEW_GOOGLE_SAT = 11; private static final int SUBMENU_VIEW_MF_MAPNIK = 13; private static final int SUBMENU_VIEW_MF_OSMARENDER = 14; private static final int SUBMENU_VIEW_MF_CYCLEMAP = 15; private static final int SUBMENU_VIEW_MF_OFFLINE = 16; private static final String EXTRAS_MAP_TITLE = "mapTitle"; private Resources res = null; private Activity activity = null; private MapViewImpl mapView = null; private MapControllerImpl mapController = null; private cgBase base = null; private cgeoapplication app = null; private cgGeo geo = null; private cgDirection dir = null; private cgUpdateLoc geoUpdate = new UpdateLoc(); private cgUpdateDir dirUpdate = new UpdateDir(); // from intent private boolean fromDetailIntent = false; private String searchIdIntent = null; private String geocodeIntent = null; private Geopoint coordsIntent = null; private WaypointType waypointTypeIntent = null; private int[] mapStateIntent = null; // status data private UUID searchId = null; private String token = null; private boolean noMapTokenShowed = false; // map status data private boolean followMyLocation = false; private Integer centerLatitude = null; private Integer centerLongitude = null; private Integer spanLatitude = null; private Integer spanLongitude = null; private Integer centerLatitudeUsers = null; private Integer centerLongitudeUsers = null; private Integer spanLatitudeUsers = null; private Integer spanLongitudeUsers = null; // threads private LoadTimer loadTimer = null; private UsersTimer usersTimer = null; //FIXME should be members of LoadTimer since started by it. private LoadThread loadThread = null; private DownloadThread downloadThread = null; private DisplayThread displayThread = null; //FIXME should be members of UsersTimer since started by it. private UsersThread usersThread = null; private DisplayUsersThread displayUsersThread = null; //FIXME move to OnOptionsItemSelected private LoadDetails loadDetailsThread = null; /** Time of last {@link LoadThread} run */ private volatile long loadThreadRun = 0L; /** Time of last {@link UsersThread} run */ private volatile long usersThreadRun = 0L; //Interthread communication flag private volatile boolean downloaded = false; // overlays private CachesOverlay overlayCaches = null; private OtherCachersOverlay overlayOtherCachers = null; private ScaleOverlay overlayScale = null; private PositionOverlay overlayPosition = null; // data for overlays private int cachesCnt = 0; private Map<Integer, Drawable> iconsCache = new HashMap<Integer, Drawable>(); /** List of caches in the viewport */ private List<cgCache> caches = new ArrayList<cgCache>(); /** List of users in the viewport */ private List<cgUser> users = new ArrayList<cgUser>(); private List<cgCoord> coordinates = new ArrayList<cgCoord>(); // storing for offline private ProgressDialog waitDialog = null; private int detailTotal = 0; private int detailProgress = 0; private Long detailProgressTime = 0L; // views private ImageSwitcher myLocSwitch = null; // other things private boolean live = true; // live map (live, dead) or rest (displaying caches on map) private boolean liveChanged = false; // previous state for loadTimer private boolean centered = false; // if map is already centered private boolean alreadyCentered = false; // -""- for setting my location // handlers /** Updates the titles */ final private Handler displayHandler = new Handler() { @Override public void handleMessage(Message msg) { final int what = msg.what; if (what == 0) { // set title final StringBuilder title = new StringBuilder(); if (live) { title.append(res.getString(R.string.map_live)); } else { title.append(mapTitle); } if (caches != null && cachesCnt > 0 && !mapTitle.contains("[")) { title.append(" ["); title.append(caches.size()); title.append(']'); } ActivityMixin.setTitle(activity, title.toString()); } else if (what == 1 && mapView != null) { mapView.invalidate(); } } }; /** Updates the progress. */ final private Handler showProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { final int what = msg.what; if (what == 0) { ActivityMixin.showProgress(activity, false); } else if (what == 1) { ActivityMixin.showProgress(activity, true); } } }; final private Handler loadDetailsHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0) { if (waitDialog != null) { int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); int secondsRemaining; if (detailProgress > 0) //DP can be zero and cause devisionByZero secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; else secondsRemaining = (detailTotal - detailProgress) * secondsElapsed; waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (secondsRemaining < 90) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%d", (secondsRemaining / 60)) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%d", (secondsRemaining / 60)) + " " + res.getString(R.string.caches_eta_mins)); } } } else { if (waitDialog != null) { waitDialog.dismiss(); waitDialog.setOnCancelListener(null); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } } }; final private Handler noMapTokenHandler = new Handler() { @Override public void handleMessage(Message msg) { if (!noMapTokenShowed) { ActivityMixin.showToast(activity, res.getString(R.string.map_token_err)); noMapTokenShowed = true; } } }; /** * calling activities can set the map title via extras */ private String mapTitle; public CGeoMap(MapActivityImpl activity) { super(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // class init res = this.getResources(); activity = this.getActivity(); app = (cgeoapplication) activity.getApplication(); app.setAction(null); base = new cgBase(app); MapFactory mapFactory = Settings.getMapFactory(); // reset status noMapTokenShowed = false; // set layout activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // set layout ActivityMixin.setTheme(activity); activity.setContentView(Settings.getMapFactory().getMapLayoutId()); ActivityMixin.setTitle(activity, res.getString(R.string.map_map)); if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } // initialize map mapView = (MapViewImpl) activity.findViewById(mapFactory.getMapViewId()); mapView.setMapSource(); mapView.setBuiltInZoomControls(true); mapView.displayZoomControls(true); mapView.preLoad(); mapView.setOnDragListener(this); // initialize overlays mapView.clearOverlays(); if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if (Settings.isPublicLoc() && overlayOtherCachers == null) { overlayOtherCachers = mapView.createAddUsersOverlay(activity, getResources().getDrawable(R.drawable.user_location)); } if (overlayCaches == null) { overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker), fromDetailIntent); } if (overlayScale == null) { overlayScale = mapView.createAddScaleOverlay(activity); } mapView.invalidate(); mapController = mapView.getMapController(); mapController.setZoom(Settings.getMapZoom()); // start location and directory services if (geo != null) { geoUpdate.updateLoc(geo); } if (dir != null) { dirUpdate.updateDir(dir); } // get parameters Bundle extras = activity.getIntent().getExtras(); if (extras != null) { fromDetailIntent = extras.getBoolean(EXTRAS_DETAIL); searchIdIntent = extras.getString(EXTRAS_SEARCHID); geocodeIntent = extras.getString(EXTRAS_GEOCODE); final double latitudeIntent = extras.getDouble(EXTRAS_LATITUDE); final double longitudeIntent = extras.getDouble(EXTRAS_LONGITUDE); coordsIntent = new Geopoint(latitudeIntent, longitudeIntent); waypointTypeIntent = WaypointType.FIND_BY_ID.get(extras.getString(EXTRAS_WPTTYPE)); mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE); mapTitle = extras.getString(EXTRAS_MAP_TITLE); if ("".equals(searchIdIntent)) { searchIdIntent = null; } if (coordsIntent.getLatitude() == 0.0 || coordsIntent.getLongitude() == 0.0) { coordsIntent = null; } } if (StringUtils.isBlank(mapTitle)) { mapTitle = res.getString(R.string.map_map); } // live map, if no arguments are given live = (searchIdIntent == null && geocodeIntent == null && coordsIntent == null); if (null == mapStateIntent) { followMyLocation = live; } else { followMyLocation = 1 == mapStateIntent[3] ? true : false; } if (geocodeIntent != null || searchIdIntent != null || coordsIntent != null || mapStateIntent != null) { centerMap(geocodeIntent, searchIdIntent, coordsIntent, mapStateIntent); } // prepare my location button myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position); myLocSwitch.setFactory(this); myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); myLocSwitch.setOnClickListener(new MyLocationListener()); switchMyLocationButton(); startTimer(); // show the filter warning bar if the filter is set if (Settings.getCacheType() != null) { String cacheType = cgBase.cacheTypesInv.get(Settings.getCacheType()); ((TextView) activity.findViewById(R.id.filter_text)).setText(cacheType); activity.findViewById(R.id.filter_bar).setVisibility(View.VISIBLE); } } @Override public void onResume() { super.onResume(); app.setAction(null); if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } if (geo != null) { geoUpdate.updateLoc(geo); } if (dir != null) { dirUpdate.updateDir(dir); } startTimer(); } @Override public void onStop() { if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } savePrefs(); if (mapView != null) { mapView.destroyDrawingCache(); } super.onStop(); } @Override public void onPause() { if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } savePrefs(); if (mapView != null) { mapView.destroyDrawingCache(); } super.onPause(); } @Override public void onDestroy() { if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } savePrefs(); if (mapView != null) { mapView.destroyDrawingCache(); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { SubMenu submenu = menu.addSubMenu(1, MENU_SELECT_MAPVIEW, 0, res.getString(R.string.map_view_map)).setIcon(android.R.drawable.ic_menu_mapmode); addMapViewMenuItems(submenu); menu.add(0, MENU_MAP_LIVE, 0, res.getString(R.string.map_live_disable)).setIcon(R.drawable.ic_menu_notifications); menu.add(0, MENU_STORE_CACHES, 0, res.getString(R.string.caches_store_offline)).setIcon(android.R.drawable.ic_menu_set_as).setEnabled(false); menu.add(0, MENU_TRAIL_MODE, 0, res.getString(R.string.map_trail_hide)).setIcon(android.R.drawable.ic_menu_recent_history); menu.add(0, MENU_CIRCLE_MODE, 0, res.getString(R.string.map_circles_hide)).setIcon(R.drawable.ic_menu_circle); menu.add(0, MENU_AS_LIST, 0, res.getString(R.string.map_as_list)).setIcon(android.R.drawable.ic_menu_agenda); return true; } private void addMapViewMenuItems(final Menu menu) { String[] mapViews = res.getStringArray(R.array.map_sources); mapSourceEnum mapSource = Settings.getMapSource(); menu.add(1, SUBMENU_VIEW_GOOGLE_MAP, 0, mapViews[0]).setCheckable(true).setChecked(mapSource == mapSourceEnum.googleMap); menu.add(1, SUBMENU_VIEW_GOOGLE_SAT, 0, mapViews[1]).setCheckable(true).setChecked(mapSource == mapSourceEnum.googleSat); menu.add(1, SUBMENU_VIEW_MF_MAPNIK, 0, mapViews[2]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeMapnik); menu.add(1, SUBMENU_VIEW_MF_OSMARENDER, 0, mapViews[3]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeOsmarender); menu.add(1, SUBMENU_VIEW_MF_CYCLEMAP, 0, mapViews[4]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeCycle); menu.add(1, SUBMENU_VIEW_MF_OFFLINE, 0, mapViews[5]).setCheckable(true).setChecked(mapSource == mapSourceEnum.mapsforgeOffline); menu.setGroupCheckable(1, true, true); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem item; try { item = menu.findItem(MENU_TRAIL_MODE); // show trail if (Settings.isMapTrail()) { item.setTitle(res.getString(R.string.map_trail_hide)); } else { item.setTitle(res.getString(R.string.map_trail_show)); } item = menu.findItem(MENU_MAP_LIVE); // live map if (live) { if (Settings.isLiveMap()) { item.setTitle(res.getString(R.string.map_live_disable)); } else { item.setTitle(res.getString(R.string.map_live_enable)); } } else { item.setEnabled(false); item.setTitle(res.getString(R.string.map_live_enable)); } menu.findItem(MENU_STORE_CACHES).setEnabled(live && !isLoading() && CollectionUtils.isNotEmpty(caches) && app.hasUnsavedCaches(searchId)); item = menu.findItem(MENU_CIRCLE_MODE); // show circles if (overlayCaches != null && overlayCaches.getCircles()) { item.setTitle(res.getString(R.string.map_circles_hide)); } else { item.setTitle(res.getString(R.string.map_circles_show)); } menu.findItem(SUBMENU_VIEW_MF_OFFLINE).setEnabled(Settings.isValidMapFile()); item = menu.findItem(MENU_AS_LIST); item.setVisible(live); item.setEnabled(CollectionUtils.isNotEmpty(caches)); } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onPrepareOptionsMenu: " + e.toString()); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case MENU_TRAIL_MODE: Settings.setMapTrail(!Settings.isMapTrail()); return true; case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); liveChanged = true; searchId = null; searchIdIntent = null; return true; case MENU_STORE_CACHES: if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { final List<String> geocodes = new ArrayList<String>(); List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); try { if (cachesProtected.size() > 0) { final GeoPointImpl mapCenter = mapView.getMapViewCenter(); final int mapCenterLat = mapCenter.getLatitudeE6(); final int mapCenterLon = mapCenter.getLongitudeE6(); final int mapSpanLat = mapView.getLatitudeSpan(); final int mapSpanLon = mapView.getLongitudeSpan(); for (cgCache oneCache : cachesProtected) { if (oneCache != null && oneCache.coords != null) { if (cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && app.isOffline(oneCache.geocode, null) == false) { geocodes.add(oneCache.geocode); } } } } } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString()); } detailTotal = geocodes.size(); + detailProgress = 0; if (detailTotal == 0) { ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing)); return true; } waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); } } }); Float etaTime = Float.valueOf((detailTotal * (float) 7) / 60); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (etaTime < 1.5) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_mins)); } waitDialog.show(); detailProgressTime = System.currentTimeMillis(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes); loadDetailsThread.start(); } return true; case MENU_CIRCLE_MODE: if (overlayCaches == null) { return false; } overlayCaches.switchCircles(); mapView.invalidate(); return true; case MENU_AS_LIST: final cgSearch search = new cgSearch(); search.totalCnt = caches.size(); for (cgCache cache : caches) { search.addGeocode(cache.geocode); } cgeocaches.startActivityMap(activity, app.addSearch(search, caches, true, 0)); return true; default: if (SUBMENU_VIEW_GOOGLE_MAP <= id && SUBMENU_VIEW_MF_OFFLINE >= id) { item.setChecked(true); mapSourceEnum mapSource = getMapSourceFromMenuId(id); boolean mapRestartRequired = switchMapSource(mapSource); if (mapRestartRequired) { // close old mapview activity.finish(); // prepare information to restart a similar view Intent mapIntent = new Intent(activity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, fromDetailIntent); mapIntent.putExtra(EXTRAS_SEARCHID, searchIdIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coordsIntent.getLongitude()); } mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null); int[] mapState = new int[4]; GeoPointImpl mapCenter = mapView.getMapViewCenter(); mapState[0] = mapCenter.getLatitudeE6(); mapState[1] = mapCenter.getLongitudeE6(); mapState[2] = mapView.getMapZoomLevel(); mapState[3] = followMyLocation ? 1 : 0; mapIntent.putExtra(EXTRAS_MAPSTATE, mapState); // start the new map activity.startActivity(mapIntent); } return true; } break; } return false; } private static mapSourceEnum getMapSourceFromMenuId(int menuItemId) { switch (menuItemId) { case SUBMENU_VIEW_GOOGLE_MAP: return mapSourceEnum.googleMap; case SUBMENU_VIEW_GOOGLE_SAT: return mapSourceEnum.googleSat; case SUBMENU_VIEW_MF_OSMARENDER: return mapSourceEnum.mapsforgeOsmarender; case SUBMENU_VIEW_MF_MAPNIK: return mapSourceEnum.mapsforgeMapnik; case SUBMENU_VIEW_MF_CYCLEMAP: return mapSourceEnum.mapsforgeCycle; case SUBMENU_VIEW_MF_OFFLINE: return mapSourceEnum.mapsforgeOffline; default: return mapSourceEnum.googleMap; } } private boolean switchMapSource(mapSourceEnum mapSource) { boolean oldIsGoogle = Settings.getMapSource().isGoogleMapSource(); Settings.setMapSource(mapSource); boolean mapRestartRequired = mapSource.isGoogleMapSource() != oldIsGoogle; if (!mapRestartRequired) { mapView.setMapSource(); } return mapRestartRequired; } private void savePrefs() { if (mapView == null) { return; } Settings.setMapZoom(mapView.getMapZoomLevel()); } // set center of map to my location private void myLocationInMiddle() { if (geo == null) { return; } if (!followMyLocation) { return; } centerMap(geo.coordsNow); } // class: update location private class UpdateLoc extends cgUpdateLoc { @Override public void updateLoc(cgGeo geo) { if (geo == null) { return; } try { boolean repaintRequired = false; if (overlayPosition == null && mapView != null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if (overlayPosition != null && geo.location != null) { overlayPosition.setCoordinates(geo.location); } if (geo.coordsNow != null) { if (followMyLocation) { myLocationInMiddle(); } else { repaintRequired = true; } } if (!Settings.isUseCompass() || (geo.speedNow != null && geo.speedNow > 5)) { // use GPS when speed is higher than 18 km/h if (geo.bearingNow != null) { overlayPosition.setHeading(geo.bearingNow); } else { overlayPosition.setHeading(0f); } repaintRequired = true; } if (repaintRequired && mapView != null) { mapView.repaintRequired(overlayPosition); } } catch (Exception e) { Log.w(Settings.tag, "Failed to update location."); } } } // class: update direction private class UpdateDir extends cgUpdateDir { @Override public void updateDir(cgDirection dir) { if (dir == null || dir.directionNow == null) { return; } if (overlayPosition != null && mapView != null && (geo == null || geo.speedNow == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h overlayPosition.setHeading(dir.directionNow); mapView.invalidate(); } } } /** * Starts the {@link LoadTimer} and {@link UsersTimer}. */ public synchronized void startTimer() { if (coordsIntent != null) { // display just one point (new DisplayPointThread()).start(); } else { // start timer if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } loadTimer = new LoadTimer(); loadTimer.start(); } if (Settings.isPublicLoc()) { if (usersTimer != null) { usersTimer.stopIt(); usersTimer = null; } usersTimer = new UsersTimer(); usersTimer.start(); } } /** * loading timer Triggers every 250ms and checks for viewport change and starts a {@link LoadThread}. */ private class LoadTimer extends Thread { public LoadTimer() { super("Load Timer"); } private volatile boolean stop = false; public void stopIt() { stop = true; if (loadThread != null) { loadThread.stopIt(); loadThread = null; } if (downloadThread != null) { downloadThread.stopIt(); downloadThread = null; } if (displayThread != null) { displayThread.stopIt(); displayThread = null; } } @Override public void run() { GeoPointImpl mapCenterNow; int centerLatitudeNow; int centerLongitudeNow; int spanLatitudeNow; int spanLongitudeNow; boolean moved = false; boolean force = false; long currentTime = 0; while (!stop) { try { sleep(250); if (mapView != null) { // get current viewport mapCenterNow = mapView.getMapViewCenter(); centerLatitudeNow = mapCenterNow.getLatitudeE6(); centerLongitudeNow = mapCenterNow.getLongitudeE6(); spanLatitudeNow = mapView.getLatitudeSpan(); spanLongitudeNow = mapView.getLongitudeSpan(); // check if map moved or zoomed //TODO Portree Use Rectangle inside with bigger search window. That will stop reloading on every move moved = false; force = false; if (liveChanged) { moved = true; force = true; } else if (live && Settings.isLiveMap() && downloaded == false) { moved = true; } else if (centerLatitude == null || centerLongitude == null) { moved = true; } else if (spanLatitude == null || spanLongitude == null) { moved = true; } else if (((Math.abs(spanLatitudeNow - spanLatitude) > 50) || (Math.abs(spanLongitudeNow - spanLongitude) > 50) || // changed zoom (Math.abs(centerLatitudeNow - centerLatitude) > (spanLatitudeNow / 4)) || (Math.abs(centerLongitudeNow - centerLongitude) > (spanLongitudeNow / 4)) // map moved ) && (cachesCnt <= 0 || CollectionUtils.isEmpty(caches) || !cgBase.isInViewPort(centerLatitude, centerLongitude, centerLatitudeNow, centerLongitudeNow, spanLatitude, spanLongitude, spanLatitudeNow, spanLongitudeNow))) { moved = true; } if (moved && caches != null && centerLatitude != null && centerLongitude != null && ((Math.abs(centerLatitudeNow - centerLatitude) > (spanLatitudeNow * 1.2)) || (Math.abs(centerLongitudeNow - centerLongitude) > (spanLongitudeNow * 1.2)))) { force = true; } //LeeB // save new values if (moved) { liveChanged = false; currentTime = System.currentTimeMillis(); if (1000 < (currentTime - loadThreadRun)) { // from web if (20000 < (currentTime - loadThreadRun)) { force = true; // probably stucked thread } if (force && loadThread != null && loadThread.isWorking()) { loadThread.stopIt(); try { sleep(100); } catch (Exception e) { // nothing } } if (loadThread != null && loadThread.isWorking()) { continue; } centerLatitude = centerLatitudeNow; centerLongitude = centerLongitudeNow; spanLatitude = spanLatitudeNow; spanLongitude = spanLongitudeNow; showProgressHandler.sendEmptyMessage(1); // show progress loadThread = new LoadThread(centerLatitude, centerLongitude, spanLatitude, spanLongitude); loadThread.start(); //loadThread will kick off downloadThread once it's done } } } if (!isLoading()) { showProgressHandler.sendEmptyMessage(0); // hide progress } yield(); } catch (Exception e) { Log.w(Settings.tag, "cgeomap.LoadTimer.run: " + e.toString()); } } } } /** * Timer triggering every 250 ms to start the {@link UsersThread} for displaying user. */ private class UsersTimer extends Thread { public UsersTimer() { super("Users Timer"); } private volatile boolean stop = false; public void stopIt() { stop = true; if (usersThread != null) { usersThread.stopIt(); usersThread = null; } if (displayUsersThread != null) { displayUsersThread.stopIt(); displayUsersThread = null; } } @Override public void run() { GeoPointImpl mapCenterNow; int centerLatitudeNow; int centerLongitudeNow; int spanLatitudeNow; int spanLongitudeNow; boolean moved = false; long currentTime = 0; while (!stop) { try { sleep(250); if (mapView != null) { // get current viewport mapCenterNow = mapView.getMapViewCenter(); centerLatitudeNow = mapCenterNow.getLatitudeE6(); centerLongitudeNow = mapCenterNow.getLongitudeE6(); spanLatitudeNow = mapView.getLatitudeSpan(); spanLongitudeNow = mapView.getLongitudeSpan(); // check if map moved or zoomed moved = false; currentTime = System.currentTimeMillis(); if (60000 < (currentTime - usersThreadRun)) { moved = true; } else if (centerLatitudeUsers == null || centerLongitudeUsers == null) { moved = true; } else if (spanLatitudeUsers == null || spanLongitudeUsers == null) { moved = true; } else if (((Math.abs(spanLatitudeNow - spanLatitudeUsers) > 50) || (Math.abs(spanLongitudeNow - spanLongitudeUsers) > 50) || // changed zoom (Math.abs(centerLatitudeNow - centerLatitudeUsers) > (spanLatitudeNow / 4)) || (Math.abs(centerLongitudeNow - centerLongitudeUsers) > (spanLongitudeNow / 4)) // map moved ) && !cgBase.isInViewPort(centerLatitudeUsers, centerLongitudeUsers, centerLatitudeNow, centerLongitudeNow, spanLatitudeUsers, spanLongitudeUsers, spanLatitudeNow, spanLongitudeNow)) { moved = true; } // save new values if (moved && (1000 < (currentTime - usersThreadRun))) { if (usersThread != null && usersThread.isWorking()) { continue; } centerLatitudeUsers = centerLatitudeNow; centerLongitudeUsers = centerLongitudeNow; spanLatitudeUsers = spanLatitudeNow; spanLongitudeUsers = spanLongitudeNow; usersThread = new UsersThread(centerLatitude, centerLongitude, spanLatitude, spanLongitude); usersThread.start(); } } yield(); } catch (Exception e) { Log.w(Settings.tag, "cgeomap.LoadUsersTimer.run: " + e.toString()); } } } } /** * Worker thread that loads caches and waypoints from the database and then spawns the {@link DownloadThread}. * started by {@link LoadTimer} */ private class LoadThread extends DoThread { public LoadThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("Load Thread"); } @Override public void run() { try { stop = false; working = true; loadThreadRun = System.currentTimeMillis(); if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //LeeB - I think this can be done better: //1. fetch and draw(in another thread) caches from the db (fast? db read will be the slow bit) //2. fetch and draw(in another thread) and then insert into the db caches from geocaching.com - dont draw/insert if exist in memory? // stage 1 - pull and render from the DB only if (fromDetailIntent || StringUtils.isNotEmpty(searchIdIntent)) { searchId = UUID.fromString(searchIdIntent); } else { if (!live || !Settings.isLiveMap()) { searchId = app.getStoredInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); } else { searchId = app.getCachedInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); } } if (searchId != null) { downloaded = true; } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } caches = app.getCaches(searchId); //if in live map and stored caches are found / disables are also shown. if (live && Settings.isLiveMap()) { final boolean excludeMine = Settings.isExcludeMyCaches(); final boolean excludeDisabled = Settings.isExcludeDisabledCaches(); for (int i = caches.size() - 1; i >= 0; i--) { cgCache cache = caches.get(i); if ((cache.found && excludeMine) || (cache.own && excludeMine) || (cache.disabled && excludeDisabled)) { caches.remove(i); } } } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //render if (displayThread != null && displayThread.isWorking()) { displayThread.stopIt(); } displayThread = new DisplayThread(centerLat, centerLon, spanLat, spanLon); displayThread.start(); if (stop) { displayThread.stopIt(); displayHandler.sendEmptyMessage(0); working = false; return; } //*** this needs to be in it's own thread // stage 2 - pull and render from geocaching.com //this should just fetch and insert into the db _and_ be cancel-able if the viewport changes if (live && Settings.isLiveMap()) { if (downloadThread != null && downloadThread.isWorking()) { downloadThread.stopIt(); } downloadThread = new DownloadThread(centerLat, centerLon, spanLat, spanLon); downloadThread.setName("downloadThread"); downloadThread.start(); } } finally { working = false; } } } /** * Worker thread downloading caches from the internet. * Started by {@link LoadThread}. Duplicate Code with {@link UsersThread} */ private class DownloadThread extends DoThread { public DownloadThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); } @Override public void run() { //first time we enter we have crappy long/lat.... try { stop = false; working = true; if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } double lat1 = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4); double lat2 = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4); double lon1 = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4); double lon2 = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4); double latMin = Math.min(lat1, lat2); double latMax = Math.max(lat1, lat2); double lonMin = Math.min(lon1, lon2); double lonMax = Math.max(lon1, lon2); //*** this needs to be in it's own thread // stage 2 - pull and render from geocaching.com //this should just fetch and insert into the db _and_ be cancel-able if the viewport changes if (token == null) { token = cgBase.getMapUserToken(noMapTokenHandler); } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } searchId = base.searchByViewport(token, latMin, latMax, lonMin, lonMax, 0); if (searchId != null) { downloaded = true; } if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //TODO Portree Only overwrite if we got some. Otherwise maybe error icon //TODO Merge not to show locally found caches caches = app.getCaches(searchId, centerLat, centerLon, spanLat, spanLon); if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } //render if (displayThread != null && displayThread.isWorking()) { displayThread.stopIt(); } displayThread = new DisplayThread(centerLat, centerLon, spanLat, spanLon); displayThread.start(); } finally { working = false; } } } /** * Thread to Display (down)loaded caches. Started by {@link LoadThread} and {@link DownloadThread} */ private class DisplayThread extends DoThread { public DisplayThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("Display Thread"); } @Override public void run() { try { stop = false; working = true; if (mapView == null || caches == null) { displayHandler.sendEmptyMessage(0); working = false; return; } // display caches final List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); final List<CachesOverlayItemImpl> items = new ArrayList<CachesOverlayItemImpl>(); if (!cachesProtected.isEmpty()) { for (cgCache cacheOne : cachesProtected) { if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } if (cacheOne.coords == null) { continue; } // display cache waypoints if (cacheOne.waypoints != null // Only show waypoints for single view or setting // when less than showWaypointsthreshold Caches shown && (cachesProtected.size() == 1 || (cachesProtected.size() < Settings.getWayPointsThreshold())) && !cacheOne.waypoints.isEmpty()) { for (cgWaypoint oneWaypoint : cacheOne.waypoints) { if (oneWaypoint.coords == null) { continue; } items.add(getWaypointItem(new cgCoord(oneWaypoint), oneWaypoint.type)); } } items.add(getCacheItem(new cgCoord(cacheOne), cacheOne.type, cacheOne.own, cacheOne.found, cacheOne.disabled)); } overlayCaches.updateItems(items); displayHandler.sendEmptyMessage(1); cachesCnt = cachesProtected.size(); if (stop) { displayHandler.sendEmptyMessage(0); working = false; return; } } else { overlayCaches.updateItems(items); displayHandler.sendEmptyMessage(1); } cachesProtected.clear(); displayHandler.sendEmptyMessage(0); } finally { working = false; } } /** * Returns a OverlayItem representing the cache * * @param cgCoord * The coords * @param type * String name * @param own * true for own caches * @param found * true for found * @param disabled * true for disabled * @return */ private CachesOverlayItemImpl getCacheItem(cgCoord cgCoord, String type, boolean own, boolean found, boolean disabled) { return getItem(cgCoord, cgBase.getCacheMarkerIcon(type, own, found, disabled)); } /** * Returns a OverlayItem representing the waypoint * * @param cgCoord * The coords * @param type * The waypoint's type * @return */ private CachesOverlayItemImpl getWaypointItem(cgCoord cgCoord, WaypointType type) { return getItem(cgCoord, type != null ? type.markerId : WaypointType.WAYPOINT.markerId); } /** * Returns a OverlayItem represented by an icon * * @param cgCoord * The coords * @param icon * The icon * @return */ private CachesOverlayItemImpl getItem(cgCoord cgCoord, int icon) { coordinates.add(cgCoord); CachesOverlayItemImpl item = Settings.getMapFactory().getCachesOverlayItem(cgCoord, null); Drawable pin = null; if (iconsCache.containsKey(icon)) { pin = iconsCache.get(icon); } else { pin = getResources().getDrawable(icon); pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight()); iconsCache.put(icon, pin); } item.setMarker(pin); return item; } } /** * Thread to load users from Go 4 Cache * Duplicate Code with {@link DownloadThread} */ private class UsersThread extends DoThread { public UsersThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("UsersThread"); } @Override public void run() { try { stop = false; working = true; usersThreadRun = System.currentTimeMillis(); if (stop) { return; } double latMin = (centerLat / 1e6) - ((spanLat / 1e6) / 2) - ((spanLat / 1e6) / 4); double latMax = (centerLat / 1e6) + ((spanLat / 1e6) / 2) + ((spanLat / 1e6) / 4); double lonMin = (centerLon / 1e6) - ((spanLon / 1e6) / 2) - ((spanLon / 1e6) / 4); double lonMax = (centerLon / 1e6) + ((spanLon / 1e6) / 2) + ((spanLon / 1e6) / 4); double llCache; if (latMin > latMax) { llCache = latMax; latMax = latMin; latMin = llCache; } if (lonMin > lonMax) { llCache = lonMax; lonMax = lonMin; lonMin = llCache; } users = cgBase.getGeocachersInViewport(Settings.getUsername(), latMin, latMax, lonMin, lonMax); if (stop) { return; } if (displayUsersThread != null && displayUsersThread.isWorking()) { displayUsersThread.stopIt(); } displayUsersThread = new DisplayUsersThread(users, centerLat, centerLon, spanLat, spanLon); displayUsersThread.start(); } finally { working = false; } } } /** * Thread to display users of Go 4 Cache started from {@link UsersThread} */ private class DisplayUsersThread extends DoThread { private List<cgUser> users = null; public DisplayUsersThread(List<cgUser> usersIn, long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { super(centerLatIn, centerLonIn, spanLatIn, spanLonIn); setName("DisplayUsersThread"); users = usersIn; } @Override public void run() { try { stop = false; working = true; if (mapView == null || CollectionUtils.isEmpty(users)) { return; } // display users List<OtherCachersOverlayItemImpl> items = new ArrayList<OtherCachersOverlayItemImpl>(); int counter = 0; OtherCachersOverlayItemImpl item = null; for (cgUser userOne : users) { if (stop) { return; } if (userOne.coords == null) { continue; } item = Settings.getMapFactory().getOtherCachersOverlayItemBase(activity, userOne); items.add(item); counter++; if ((counter % 10) == 0) { overlayOtherCachers.updateItems(items); displayHandler.sendEmptyMessage(1); } } overlayOtherCachers.updateItems(items); } finally { working = false; } } } /** * Thread to display one point. Started on opening if in single mode. */ private class DisplayPointThread extends Thread { @Override public void run() { if (mapView == null || caches == null) { return; } if (coordsIntent != null) { cgCoord coord = new cgCoord(); coord.type = "waypoint"; coord.coords = coordsIntent; coord.name = "some place"; coordinates.add(coord); CachesOverlayItemImpl item = Settings.getMapFactory().getCachesOverlayItem(coord, null); final int icon = waypointTypeIntent != null ? waypointTypeIntent.markerId : null; Drawable pin = null; if (iconsCache.containsKey(icon)) { pin = iconsCache.get(icon); } else { pin = getResources().getDrawable(icon); pin.setBounds(0, 0, pin.getIntrinsicWidth(), pin.getIntrinsicHeight()); iconsCache.put(icon, pin); } item.setMarker(pin); overlayCaches.updateItems(item); displayHandler.sendEmptyMessage(1); cachesCnt = 1; } else { cachesCnt = 0; } displayHandler.sendEmptyMessage(0); } } /** * Abstract Base Class for the worker threads. */ private abstract class DoThread extends Thread { protected boolean working = true; protected boolean stop = false; protected long centerLat = 0L; protected long centerLon = 0L; protected long spanLat = 0L; protected long spanLon = 0L; public DoThread(long centerLatIn, long centerLonIn, long spanLatIn, long spanLonIn) { centerLat = centerLatIn; centerLon = centerLonIn; spanLat = spanLatIn; spanLon = spanLonIn; } public synchronized boolean isWorking() { return working; } public synchronized void stopIt() { stop = true; } } /** * get if map is loading something * * @return */ private synchronized boolean isLoading() { boolean loading = false; if (loadThread != null && loadThread.isWorking()) { loading = true; } else if (downloadThread != null && downloadThread.isWorking()) { loading = true; } else if (displayThread != null && displayThread.isWorking()) { loading = true; } return loading; } /** * Thread to store the caches in the viewport. Started by Activity. */ private class LoadDetails extends Thread { private Handler handler = null; private List<String> geocodes = null; private volatile boolean stop = false; private long last = 0L; public LoadDetails(Handler handlerIn, List<String> geocodesIn) { handler = handlerIn; geocodes = geocodesIn; } public void stopIt() { stop = true; } @Override public void run() { if (CollectionUtils.isEmpty(geocodes)) { return; } if (dir != null) { dir = app.removeDir(); } if (geo != null) { geo = app.removeGeo(); } for (String geocode : geocodes) { try { if (stop) { break; } if (!app.isOffline(geocode, null)) { if ((System.currentTimeMillis() - last) < 1500) { try { int delay = 1000 + ((Double) (Math.random() * 1000)).intValue() - (int) (System.currentTimeMillis() - last); if (delay < 0) { delay = 500; } sleep(delay); } catch (Exception e) { // nothing } } if (stop) { Log.i(Settings.tag, "Stopped storing process."); break; } base.storeCache(app, activity, null, geocode, 1, handler); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.LoadDetails.run: " + e.toString()); } finally { // one more cache over detailProgress++; handler.sendEmptyMessage(0); } yield(); last = System.currentTimeMillis(); } // we're done handler.sendEmptyMessage(1); } } // center map to desired location private void centerMap(final Geopoint coords) { if (coords == null) { return; } if (mapView == null) { return; } if (!alreadyCentered) { alreadyCentered = true; mapController.setCenter(makeGeoPoint(coords)); } else { mapController.animateTo(makeGeoPoint(coords)); } } // move map to view results of searchIdIntent private void centerMap(String geocodeCenter, String searchIdCenter, final Geopoint coordsCenter, int[] mapState) { if (!centered && mapState != null) { try { mapController.setCenter(Settings.getMapFactory().getGeoPointBase(new Geopoint(mapState[0] / 1.0e6, mapState[1] / 1.0e6))); mapController.setZoom(mapState[2]); } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } else if (!centered && (geocodeCenter != null || searchIdIntent != null)) { try { List<Object> viewport = null; if (geocodeCenter != null) { viewport = app.getBounds(geocodeCenter); } else { viewport = app.getBounds(UUID.fromString(searchIdCenter)); } if (viewport == null) return; Integer cnt = (Integer) viewport.get(0); Integer minLat = null; Integer maxLat = null; Integer minLon = null; Integer maxLon = null; if (viewport.get(1) != null) { minLat = (int) ((Double) viewport.get(1) * 1e6); } if (viewport.get(2) != null) { maxLat = (int) ((Double) viewport.get(2) * 1e6); } if (viewport.get(3) != null) { maxLon = (int) ((Double) viewport.get(3) * 1e6); } if (viewport.get(4) != null) { minLon = (int) ((Double) viewport.get(4) * 1e6); } if (cnt == null || cnt <= 0 || minLat == null || maxLat == null || minLon == null || maxLon == null) { return; } int centerLat = 0; int centerLon = 0; if ((Math.abs(maxLat) - Math.abs(minLat)) != 0) { centerLat = minLat + ((maxLat - minLat) / 2); } else { centerLat = maxLat; } if ((Math.abs(maxLon) - Math.abs(minLon)) != 0) { centerLon = minLon + ((maxLon - minLon) / 2); } else { centerLon = maxLon; } if (cnt > 0) { mapController.setCenter(Settings.getMapFactory().getGeoPointBase(new Geopoint(centerLat, centerLon))); if (Math.abs(maxLat - minLat) != 0 && Math.abs(maxLon - minLon) != 0) { mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon)); } } } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } else if (!centered && coordsCenter != null) { try { mapController.setCenter(makeGeoPoint(coordsCenter)); } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } } // switch My Location button image private void switchMyLocationButton() { if (followMyLocation) { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on); myLocationInMiddle(); } else { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off); } } // set my location listener private class MyLocationListener implements View.OnClickListener { public void onClick(View view) { followMyLocation = !followMyLocation; switchMyLocationButton(); } } @Override public void onDrag() { if (followMyLocation) { followMyLocation = false; switchMyLocationButton(); } } // make geopoint private static GeoPointImpl makeGeoPoint(final Geopoint coords) { return Settings.getMapFactory().getGeoPointBase(coords); } // close activity and open homescreen public void goHome(View view) { ActivityMixin.goHome(activity); } // open manual entry public void goManual(View view) { ActivityMixin.goManual(activity, "c:geo-live-map"); } @Override public View makeView() { ImageView imageView = new ImageView(activity); imageView.setScaleType(ScaleType.CENTER); imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); return imageView; } public static void startActivitySearch(final Activity fromActivity, final UUID searchId, final String title, boolean detail) { Intent mapIntent = new Intent(fromActivity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, detail); mapIntent.putExtra(EXTRAS_SEARCHID, searchId.toString()); if (StringUtils.isNotBlank(title)) { mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title); } fromActivity.startActivity(mapIntent); } public static void startActivityLiveMap(final Context context) { context.startActivity(new Intent(context, Settings.getMapFactory().getMapClass())); } public static void startActivityCoords(final Context context, final Geopoint coords, final WaypointType type) { Intent mapIntent = new Intent(context, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, false); mapIntent.putExtra(EXTRAS_LATITUDE, coords.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coords.getLongitude()); if (type != null) { mapIntent.putExtra(EXTRAS_WPTTYPE, type.id); } context.startActivity(mapIntent); } public static void startActivityGeoCode(final Context context, final String geocode) { Intent mapIntent = new Intent(context, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, false); mapIntent.putExtra(EXTRAS_GEOCODE, geocode); mapIntent.putExtra(EXTRAS_MAP_TITLE, geocode); context.startActivity(mapIntent); } }
true
true
public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case MENU_TRAIL_MODE: Settings.setMapTrail(!Settings.isMapTrail()); return true; case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); liveChanged = true; searchId = null; searchIdIntent = null; return true; case MENU_STORE_CACHES: if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { final List<String> geocodes = new ArrayList<String>(); List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); try { if (cachesProtected.size() > 0) { final GeoPointImpl mapCenter = mapView.getMapViewCenter(); final int mapCenterLat = mapCenter.getLatitudeE6(); final int mapCenterLon = mapCenter.getLongitudeE6(); final int mapSpanLat = mapView.getLatitudeSpan(); final int mapSpanLon = mapView.getLongitudeSpan(); for (cgCache oneCache : cachesProtected) { if (oneCache != null && oneCache.coords != null) { if (cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && app.isOffline(oneCache.geocode, null) == false) { geocodes.add(oneCache.geocode); } } } } } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString()); } detailTotal = geocodes.size(); if (detailTotal == 0) { ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing)); return true; } waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); } } }); Float etaTime = Float.valueOf((detailTotal * (float) 7) / 60); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (etaTime < 1.5) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_mins)); } waitDialog.show(); detailProgressTime = System.currentTimeMillis(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes); loadDetailsThread.start(); } return true; case MENU_CIRCLE_MODE: if (overlayCaches == null) { return false; } overlayCaches.switchCircles(); mapView.invalidate(); return true; case MENU_AS_LIST: final cgSearch search = new cgSearch(); search.totalCnt = caches.size(); for (cgCache cache : caches) { search.addGeocode(cache.geocode); } cgeocaches.startActivityMap(activity, app.addSearch(search, caches, true, 0)); return true; default: if (SUBMENU_VIEW_GOOGLE_MAP <= id && SUBMENU_VIEW_MF_OFFLINE >= id) { item.setChecked(true); mapSourceEnum mapSource = getMapSourceFromMenuId(id); boolean mapRestartRequired = switchMapSource(mapSource); if (mapRestartRequired) { // close old mapview activity.finish(); // prepare information to restart a similar view Intent mapIntent = new Intent(activity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, fromDetailIntent); mapIntent.putExtra(EXTRAS_SEARCHID, searchIdIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coordsIntent.getLongitude()); } mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null); int[] mapState = new int[4]; GeoPointImpl mapCenter = mapView.getMapViewCenter(); mapState[0] = mapCenter.getLatitudeE6(); mapState[1] = mapCenter.getLongitudeE6(); mapState[2] = mapView.getMapZoomLevel(); mapState[3] = followMyLocation ? 1 : 0; mapIntent.putExtra(EXTRAS_MAPSTATE, mapState); // start the new map activity.startActivity(mapIntent); } return true; } break; } return false; }
public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case MENU_TRAIL_MODE: Settings.setMapTrail(!Settings.isMapTrail()); return true; case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); liveChanged = true; searchId = null; searchIdIntent = null; return true; case MENU_STORE_CACHES: if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { final List<String> geocodes = new ArrayList<String>(); List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); try { if (cachesProtected.size() > 0) { final GeoPointImpl mapCenter = mapView.getMapViewCenter(); final int mapCenterLat = mapCenter.getLatitudeE6(); final int mapCenterLon = mapCenter.getLongitudeE6(); final int mapSpanLat = mapView.getLatitudeSpan(); final int mapSpanLon = mapView.getLongitudeSpan(); for (cgCache oneCache : cachesProtected) { if (oneCache != null && oneCache.coords != null) { if (cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && app.isOffline(oneCache.geocode, null) == false) { geocodes.add(oneCache.geocode); } } } } } catch (Exception e) { Log.e(Settings.tag, "cgeomap.onOptionsItemSelected.#4: " + e.toString()); } detailTotal = geocodes.size(); detailProgress = 0; if (detailTotal == 0) { ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing)); return true; } waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } if (geo == null) { geo = app.startGeo(activity, geoUpdate, base, 0, 0); } if (Settings.isUseCompass() && dir == null) { dir = app.startDir(activity, dirUpdate); } } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); } } }); Float etaTime = Float.valueOf((detailTotal * (float) 7) / 60); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (etaTime < 1.5) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_min)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + String.format(Locale.getDefault(), "%.0f", etaTime) + " " + res.getString(R.string.caches_eta_mins)); } waitDialog.show(); detailProgressTime = System.currentTimeMillis(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes); loadDetailsThread.start(); } return true; case MENU_CIRCLE_MODE: if (overlayCaches == null) { return false; } overlayCaches.switchCircles(); mapView.invalidate(); return true; case MENU_AS_LIST: final cgSearch search = new cgSearch(); search.totalCnt = caches.size(); for (cgCache cache : caches) { search.addGeocode(cache.geocode); } cgeocaches.startActivityMap(activity, app.addSearch(search, caches, true, 0)); return true; default: if (SUBMENU_VIEW_GOOGLE_MAP <= id && SUBMENU_VIEW_MF_OFFLINE >= id) { item.setChecked(true); mapSourceEnum mapSource = getMapSourceFromMenuId(id); boolean mapRestartRequired = switchMapSource(mapSource); if (mapRestartRequired) { // close old mapview activity.finish(); // prepare information to restart a similar view Intent mapIntent = new Intent(activity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, fromDetailIntent); mapIntent.putExtra(EXTRAS_SEARCHID, searchIdIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude()); mapIntent.putExtra(EXTRAS_LONGITUDE, coordsIntent.getLongitude()); } mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null); int[] mapState = new int[4]; GeoPointImpl mapCenter = mapView.getMapViewCenter(); mapState[0] = mapCenter.getLatitudeE6(); mapState[1] = mapCenter.getLongitudeE6(); mapState[2] = mapView.getMapZoomLevel(); mapState[3] = followMyLocation ? 1 : 0; mapIntent.putExtra(EXTRAS_MAPSTATE, mapState); // start the new map activity.startActivity(mapIntent); } return true; } break; } return false; }
diff --git a/plugins/org.eclipse.jst.j2ee/j2eeplugin/org/eclipse/jst/j2ee/internal/deployables/J2EEFlexProjDeployable.java b/plugins/org.eclipse.jst.j2ee/j2eeplugin/org/eclipse/jst/j2ee/internal/deployables/J2EEFlexProjDeployable.java index d83dce27e..45c9c3ec4 100644 --- a/plugins/org.eclipse.jst.j2ee/j2eeplugin/org/eclipse/jst/j2ee/internal/deployables/J2EEFlexProjDeployable.java +++ b/plugins/org.eclipse.jst.j2ee/j2eeplugin/org/eclipse/jst/j2ee/internal/deployables/J2EEFlexProjDeployable.java @@ -1,985 +1,985 @@ /******************************************************************************* * Copyright (c) 2003, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jst.j2ee.internal.deployables; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jem.workbench.utility.JemProjectUtilities; import org.eclipse.jst.j2ee.application.Application; import org.eclipse.jst.j2ee.classpathdep.ClasspathDependencyUtil; import org.eclipse.jst.j2ee.classpathdep.IClasspathDependencyConstants; import org.eclipse.jst.j2ee.componentcore.J2EEModuleVirtualArchiveComponent; import org.eclipse.jst.j2ee.componentcore.J2EEModuleVirtualComponent; import org.eclipse.jst.j2ee.componentcore.util.EARArtifactEdit; import org.eclipse.jst.j2ee.ejb.EJBJar; import org.eclipse.jst.j2ee.internal.EjbModuleExtensionHelper; import org.eclipse.jst.j2ee.internal.IEJBModelExtenderManager; import org.eclipse.jst.j2ee.internal.J2EEConstants; import org.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyManifestUtil; import org.eclipse.jst.j2ee.internal.plugin.IJ2EEModuleConstants; import org.eclipse.jst.j2ee.internal.plugin.J2EEPlugin; import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities; import org.eclipse.jst.server.core.IApplicationClientModule; import org.eclipse.jst.server.core.IConnectorModule; import org.eclipse.jst.server.core.IEJBModule; import org.eclipse.jst.server.core.IEnterpriseApplication; import org.eclipse.jst.server.core.IJ2EEModule; import org.eclipse.jst.server.core.IWebModule; import org.eclipse.wst.common.componentcore.ArtifactEdit; import org.eclipse.wst.common.componentcore.ComponentCore; import org.eclipse.wst.common.componentcore.internal.ComponentResource; import org.eclipse.wst.common.componentcore.internal.StructureEdit; import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent; import org.eclipse.wst.common.componentcore.internal.resources.VirtualArchiveComponent; import org.eclipse.wst.common.componentcore.internal.util.ComponentUtilities; import org.eclipse.wst.common.componentcore.internal.util.IModuleConstants; import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; import org.eclipse.wst.common.componentcore.resources.IVirtualFolder; import org.eclipse.wst.common.componentcore.resources.IVirtualReference; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.ServerUtil; import org.eclipse.wst.server.core.internal.ModuleFile; import org.eclipse.wst.server.core.internal.ModuleFolder; import org.eclipse.wst.server.core.model.IModuleFile; import org.eclipse.wst.server.core.model.IModuleFolder; import org.eclipse.wst.server.core.model.IModuleResource; import org.eclipse.wst.web.internal.deployables.ComponentDeployable; /** * J2EE module superclass. */ public class J2EEFlexProjDeployable extends ComponentDeployable implements IJ2EEModule, IEnterpriseApplication, IApplicationClientModule, IConnectorModule, IEJBModule, IWebModule { private static final IPath WEB_CLASSES_PATH = new Path(J2EEConstants.WEB_INF_CLASSES); private static final IPath MANIFEST_PATH = new Path(J2EEConstants.MANIFEST_URI); private static IPath WEBLIB = new Path(J2EEConstants.WEB_INF_LIB).makeAbsolute(); private IPackageFragmentRoot[] cachedSourceContainers; private IContainer[] cachedOutputContainers; private HashMap cachedOutputMappings; private HashMap cachedSourceOutputPairs; private List classpathComponentDependencyURIs = new ArrayList(); /** * Constructor for J2EEFlexProjDeployable. * * @param project * @param aComponent */ public J2EEFlexProjDeployable(IProject project, IVirtualComponent aComponent) { super(project, aComponent); } /** * Constructor for J2EEFlexProjDeployable. * * @param project */ public J2EEFlexProjDeployable(IProject project) { super(project); } /** * Returns the root folders for the resources in this module. * * @return a possibly-empty array of resource folders */ public IContainer[] getResourceFolders() { List result = new ArrayList(); IVirtualComponent vc = ComponentCore.createComponent(getProject()); if (vc != null) { IVirtualFolder vFolder = vc.getRootFolder(); if (vFolder != null) { IContainer[] underlyingFolders = vFolder.getUnderlyingFolders(); result.addAll(Arrays.asList(underlyingFolders)); } } return (IContainer[]) result.toArray(new IContainer[result.size()]); } /** * Returns the root folders containing Java output in this module. * * @return a possibly-empty array of Java output folders */ public IContainer[] getJavaOutputFolders() { if (cachedOutputContainers == null) cachedOutputContainers = getJavaOutputFolders(getProject()); return cachedOutputContainers; } public IContainer[] getJavaOutputFolders(IProject project) { if (project == null) return new IContainer[0]; return J2EEProjectUtilities.getOutputContainers(project); } protected boolean shouldIncludeUtilityComponent(IVirtualComponent virtualComp,IVirtualReference[] references, ArtifactEdit edit) { // If the component module is an EAR we know all archives are filtered out of virtual component members // and we will return only those archives which are not binary J2EE modules in the EAR DD. These J2EE modules will // be returned by getChildModules() if (J2EEProjectUtilities.isEARProject(component.getProject())) return virtualComp != null && virtualComp.isBinary() && !isNestedJ2EEModule(virtualComp, references, (EARArtifactEdit)edit); else return super.shouldIncludeUtilityComponent(virtualComp, references, edit); } protected void addUtilMember(IVirtualComponent parent, IVirtualReference reference, IPath runtimePath) { // do not add classpath dependencies whose runtime path (../) maps to the parent component if (!runtimePath.equals(IClasspathDependencyConstants.RUNTIME_MAPPING_INTO_CONTAINER_PATH)) { super.addUtilMember(parent, reference, runtimePath); } } protected IModuleResource[] getBinaryModuleMembers() { IPath archivePath = ((J2EEModuleVirtualArchiveComponent)component).getWorkspaceRelativePath(); ModuleFile mf = null; if (archivePath != null) { //In Workspace IFile utilFile = ResourcesPlugin.getWorkspace().getRoot().getFile(archivePath); mf = new ModuleFile(utilFile, utilFile.getName(), ((J2EEModuleVirtualArchiveComponent)component).getRuntimePath().makeRelative()); } else { File extFile = ((J2EEModuleVirtualArchiveComponent)component).getUnderlyingDiskFile(); mf = new ModuleFile(extFile, extFile.getName(), ((J2EEModuleVirtualArchiveComponent)component).getRuntimePath().makeRelative()); } return new IModuleResource[] {mf}; } public IModuleResource[] members() throws CoreException { members.clear(); classpathComponentDependencyURIs.clear(); // Handle binary components if (component instanceof J2EEModuleVirtualArchiveComponent) return getBinaryModuleMembers(); if (J2EEProjectUtilities.isEARProject(component.getProject())) { // If an EAR, add classpath contributions for all referenced modules addReferencedComponentClasspathDependencies(component, false); } else { if (J2EEProjectUtilities.isDynamicWebProject(component.getProject())) { // If a web, add classpath contributions for all WEB-INF/lib modules addReferencedComponentClasspathDependencies(component, true); } if (canExportClasspathComponentDependencies(component)){ saveClasspathDependencyURIs(component); } } // If j2ee project structure is a single root structure, just return optimized members if (isSingleRootStructure()) { final IModuleResource[] resources = getOptimizedMembers(); if (!classpathComponentDependencyURIs.isEmpty()) { for (int i = 0; i < resources.length; i++) { if (resources[i] instanceof IModuleFolder) { IModuleFolder folder = (IModuleFolder) resources[i]; if (folder.getName().equals(J2EEConstants.META_INF)) { IModuleResource[] files = folder.members(); for (int j = 0; j < files.length; j++) { - files[i] = replaceManifestFile((IModuleFile) files[j]); + files[j] = replaceManifestFile((IModuleFile) files[j]); } } } } } return resources; } cachedSourceContainers = J2EEProjectUtilities.getSourceContainers(getProject()); try { IPath javaPath = Path.EMPTY; if (J2EEProjectUtilities.isDynamicWebProject(component.getProject())) javaPath = WEB_CLASSES_PATH; if (component != null) { IVirtualFolder vFolder = component.getRootFolder(); IModuleResource[] mr = getMembers(vFolder, Path.EMPTY); int size = mr.length; for (int j = 0; j < size; j++) { members.add(mr[j]); } } IContainer[] javaCont = getJavaOutputFolders(); int size = javaCont.length; for (int i = 0; i < size; i++) { //If the java output is in the scope of the virtual component, ignore to avoid duplicates if (ComponentCore.createResources(javaCont[i]).length > 0) continue; IModuleResource[] mr = getMembers(javaCont[i], javaPath, javaPath, javaCont); int size2 = mr.length; for (int j = 0; j < size2; j++) { members.add(mr[j]); } } if (component != null) { addUtilMembers(component); List consumableMembers = getConsumableReferencedMembers(component); if (!consumableMembers.isEmpty()) members.addAll(consumableMembers); } IModuleResource[] mr = new IModuleResource[members.size()]; members.toArray(mr); return mr; } finally { cachedSourceContainers = null; cachedOutputContainers = null; cachedOutputMappings = null; cachedSourceOutputPairs = null; } } protected IModuleFile createModuleFile(IFile file, IPath path) { // if this is the MANIFEST.MF file and we have classpath component dependencies, // update it return replaceManifestFile(super.createModuleFile(file, path)); } protected IModuleFile replaceManifestFile(IModuleFile moduleFile) { final IFile file = (IFile) moduleFile.getAdapter(IFile.class); final IPath path = moduleFile.getModuleRelativePath(); // if the MANIFEST.MF is being requested and we have classpath component dependencies, // dynamically generate a customized MANIFEST.MF and return that if (path.append(file.getName()).equals(MANIFEST_PATH) && !classpathComponentDependencyURIs.isEmpty()) { final IProject project = file.getProject(); final IPath workingLocation = project.getWorkingLocation(J2EEPlugin.PLUGIN_ID); // create path to temp MANIFEST.MF final IPath tempManifestPath = workingLocation.append(MANIFEST_PATH); final File fsFile = tempManifestPath.toFile(); if (!fsFile.exists()) { // create parent dirs for temp MANIFEST.MF final File parent = fsFile.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { return moduleFile; } } } // create temp MANIFEST.MF using util method try { ClasspathDependencyManifestUtil.updateManifestClasspath(file, classpathComponentDependencyURIs, new FileOutputStream(fsFile)); // create new ModuleFile that points to temp MANIFEST.MF return new ModuleFile(fsFile, file.getName(), path); } catch (IOException ioe) { return moduleFile; } } return moduleFile; } protected IModuleResource[] handleJavaPath(IPath path, IPath javaPath, IPath curPath, IContainer[] javaCont, IModuleResource[] mr, IContainer cc) throws CoreException { if (curPath.equals(javaPath)) { int size = javaCont.length; for (int i = 0; i < size; i++) { IModuleResource[] mr2 = getMembers(javaCont[i], path.append(cc.getName()), null, null); IModuleResource[] mr3 = new IModuleResource[mr.length + mr2.length]; System.arraycopy(mr, 0, mr3, 0, mr.length); System.arraycopy(mr2, 0, mr3, mr.length, mr2.length); mr = mr3; } } else { boolean containsFolder = false; String name = javaPath.segment(curPath.segmentCount()); int size = mr.length; for (int i = 0; i < size && !containsFolder; i++) { if (mr[i] instanceof IModuleFolder) { IModuleFolder mf2 = (IModuleFolder) mr[i]; if (name.equals(mf2.getName())) { containsFolder = true; } } } if (!containsFolder && javaCont.length > 0) { ModuleFolder mf2 = new ModuleFolder(javaCont[0], name, curPath); IModuleResource[] mrf = new IModuleResource[0]; size = javaCont.length; for (int i = 0; i < size; i++) { IModuleResource[] mrf2 = getMembers(javaCont[i], javaPath, null, null); IModuleResource[] mrf3 = new IModuleResource[mrf.length + mrf2.length]; System.arraycopy(mrf, 0, mrf3, 0, mrf.length); System.arraycopy(mrf2, 0, mrf3, mrf.length, mrf2.length); mrf = mrf3; } mf2.setMembers(mrf); IModuleResource[] mr3 = new IModuleResource[mr.length + 1]; System.arraycopy(mr, 0, mr3, 0, mr.length); mr3[mr.length] = mf2; mr = mr3; } } return mr; } /** * Returns the classpath as a list of absolute IPaths. * * @return an array of paths */ public IPath[] getClasspath() { List paths = new ArrayList(); IJavaProject proj = JemProjectUtilities.getJavaProject(getProject()); URL[] urls = JemProjectUtilities.getClasspathAsURLArray(proj); for (int i = 0; i < urls.length; i++) { URL url = urls[i]; paths.add(Path.fromOSString(url.getPath())); } return (IPath[]) paths.toArray(new IPath[paths.size()]); } public String getJNDIName(String ejbName) { if (!J2EEProjectUtilities.isEJBProject(component.getProject())) return null; EjbModuleExtensionHelper modHelper = null; EJBJar jar = null; ArtifactEdit ejbEdit = null; try { ejbEdit = ComponentUtilities.getArtifactEditForRead(component); if (ejbEdit != null) { jar = (EJBJar) ejbEdit.getContentModelRoot(); modHelper = IEJBModelExtenderManager.INSTANCE.getEJBModuleExtension(null); return modHelper == null ? null : modHelper.getJNDIName(jar, jar.getEnterpriseBeanNamed(ejbName)); } } catch (Exception e) { e.printStackTrace(); } finally { if (ejbEdit != null) ejbEdit.dispose(); } return null; } /** * This method will handle a number of J2EE related scenarios. If this is an ear and a child module is passed in, * the URI for that child module will be returned. If no child module was passed, the URI of the EAR is returned. * If this is a child component and the module passed in is the EAR, we grab the module uri for this compared to that * EAR. If no ear module is passed in we look for one and use it and return URI relative to found EAR. If no EAR's * are found the URI is returned in a default manner. * * @return URI string */ public String getURI(IModule module) { // If the component is an ear and the module passed in is a child module if (component!=null && module!=null && J2EEProjectUtilities.isEARProject(component.getProject())) return getContainedURI(module); IVirtualComponent ear = null; String aURI = null; // If the component is a child module and the module passed in is the ear if (module != null && J2EEProjectUtilities.isEARProject(module.getProject())) ear = ComponentCore.createComponent(module.getProject()); // else if the component is a child module and the module passed in is null, search for first ear else if (module==null && component != null) { IProject[] earProjects = J2EEProjectUtilities.getReferencingEARProjects(component.getProject()); if (earProjects.length>0) ear = ComponentCore.createComponent(earProjects[0]); } // We have a valid ear and the component is a valid child if (ear != null && component != null) { EARArtifactEdit earEdit = null; try { earEdit = EARArtifactEdit.getEARArtifactEditForRead(ear); if (earEdit != null) aURI = earEdit.getModuleURI(component); } catch (Exception e) { e.printStackTrace(); } finally { if (earEdit != null) earEdit.dispose(); } } // We have an ear component and no child module else if (component!=null && J2EEProjectUtilities.isEARProject(component.getProject())) { aURI = component.getDeployedName()+IJ2EEModuleConstants.EAR_EXT; } // We have child components but could not find valid ears else if (component!=null && J2EEProjectUtilities.isDynamicWebProject(component.getProject())) { if (module != null && J2EEProjectUtilities.isUtilityProject(module.getProject())) { IVirtualComponent webComp = ComponentCore.createComponent(component.getProject()); IVirtualReference reference = webComp.getReference(module.getProject().getName()); aURI = ComponentUtilities.getDeployUriOfUtilComponent(reference); }else{ aURI = component.getDeployedName()+IJ2EEModuleConstants.WAR_EXT; } } else if (component!=null && (J2EEProjectUtilities.isEJBProject(component.getProject()) || J2EEProjectUtilities.isApplicationClientProject(component.getProject()))) { aURI = component.getDeployedName()+IJ2EEModuleConstants.JAR_EXT; } else if (component!=null && J2EEProjectUtilities.isJCAProject(component.getProject())) { aURI = component.getDeployedName()+IJ2EEModuleConstants.RAR_EXT; } if (aURI !=null && aURI.length()>1 && aURI.startsWith("/")) //$NON-NLS-1$ aURI = aURI.substring(1); return aURI; } private boolean isBinaryModuleArchive(IModule module) { if (module!=null && module.getName().endsWith(IJ2EEModuleConstants.JAR_EXT) || module.getName().endsWith(IJ2EEModuleConstants.WAR_EXT) || module.getName().endsWith(IJ2EEModuleConstants.RAR_EXT)) { if (component!=null && J2EEProjectUtilities.isEARProject(component.getProject())) return true; } return false; } private String getContainedURI(IModule module) { if (component instanceof J2EEModuleVirtualArchiveComponent || isBinaryModuleArchive(module)) return new Path(module.getName()).lastSegment(); IVirtualComponent comp = ComponentCore.createComponent(module.getProject()); String aURI = null; if (comp!=null && component!=null && J2EEProjectUtilities.isEARProject(component.getProject())) { EARArtifactEdit earEdit = null; try { earEdit = EARArtifactEdit.getEARArtifactEditForRead(component); if (earEdit != null) aURI = earEdit.getModuleURI(comp); } catch (Exception e) { e.printStackTrace(); } finally { if (earEdit != null) earEdit.dispose(); } } if (aURI !=null && aURI.length()>1 && aURI.startsWith("/")) //$NON-NLS-1$ aURI = aURI.substring(1); return aURI; } /** * This method returns the context root property from the deployable project's .component file */ public String getContextRoot() { Properties props = component.getMetaProperties(); if(props.containsKey(J2EEConstants.CONTEXTROOT)) return props.getProperty(J2EEConstants.CONTEXTROOT); return component.getName(); } /** * This method is applicable for a web deployable. The module passed in should either be null or * the EAR module the web deployable is contained in. It will return the context root from the EAR * if it has one or return the .component value in the web project if it is standalone. * * @param module * @return contextRoot String */ public String getContextRoot(IModule earModule) { IProject deployProject = component.getProject(); String contextRoot = null; if (earModule == null) return getContextRoot(); else if (J2EEProjectUtilities.isEARProject(earModule.getProject()) && J2EEProjectUtilities.isDynamicWebProject(deployProject)) { EARArtifactEdit edit = null; try { edit = EARArtifactEdit.getEARArtifactEditForRead(earModule.getProject()); contextRoot = edit.getWebContextRoot(deployProject); } finally { if (edit!=null) edit.dispose(); } } return contextRoot; } /** * Find the source container, if any, for the given file. * * @param file * @return IPackageFragmentRoot sourceContainer for IFile */ protected IPackageFragmentRoot getSourceContainer(IFile file) { if (file == null) return null; IPackageFragmentRoot[] srcContainers = getSourceContainers(); for (int i=0; i<srcContainers.length; i++) { IPath srcPath = srcContainers[i].getPath(); if (srcPath.isPrefixOf(file.getFullPath())) return srcContainers[i]; } return null; } /** * Either returns value from cache or stores result as value in cache for the corresponding * output container for the given source container. * * @param sourceContainer * @return IContainer output container for given source container */ protected IContainer getOutputContainer(IPackageFragmentRoot sourceContainer) { if (sourceContainer == null) return null; HashMap pairs = getCachedSourceOutputPairs(); IContainer output = (IContainer) pairs.get(sourceContainer); if (output == null) { output = J2EEProjectUtilities.getOutputContainer(getProject(), sourceContainer); pairs.put(sourceContainer,output); } return output; } private IPackageFragmentRoot[] getSourceContainers() { if (cachedSourceContainers != null) return cachedSourceContainers; return J2EEProjectUtilities.getSourceContainers(getProject()); } protected List getConsumableReferencedMembers(IVirtualComponent vc) throws CoreException { List consumableMembers = new ArrayList(); IVirtualReference[] refComponents = vc.getReferences(); for (int i = 0; i < refComponents.length; i++) { IVirtualReference reference = refComponents[i]; if (reference != null && reference.getDependencyType()==IVirtualReference.DEPENDENCY_TYPE_CONSUMES) { IVirtualComponent consumedComponent = reference.getReferencedComponent(); if (consumedComponent!=null && isProjectOfType(consumedComponent.getProject(),IModuleConstants.JST_UTILITY_MODULE)) { if (consumedComponent != null && consumedComponent.getRootFolder()!=null) { IVirtualFolder vFolder = consumedComponent.getRootFolder(); IModuleResource[] mr = getMembers(vFolder, reference.getRuntimePath().makeRelative()); int size = mr.length; for (int j = 0; j < size; j++) { if (!members.contains(mr[j])) members.add(mr[j]); } addUtilMembers(consumedComponent); List childConsumableMembers = getConsumableReferencedMembers(consumedComponent); if (!childConsumableMembers.isEmpty()) members.addAll(childConsumableMembers); } IContainer[] javaCont = getJavaOutputFolders(consumedComponent.getProject()); int size = javaCont.length; for (int j = 0; j < size; j++) { IModuleResource[] mr = getMembers(javaCont[j], reference.getRuntimePath(), reference.getRuntimePath(), javaCont); int size2 = mr.length; for (int k = 0; k < size2; k++) { if (!members.contains(mr[k])) members.add(mr[k]); } } } } } return consumableMembers; } protected IModule gatherModuleReference(IVirtualComponent component, IVirtualComponent targetComponent ) { IModule module = super.gatherModuleReference(component, targetComponent); // Handle binary module components if (targetComponent instanceof J2EEModuleVirtualArchiveComponent) { if (J2EEProjectUtilities.isEARProject(component.getProject()) || targetComponent.getProject()!=component.getProject()) module = ServerUtil.getModule(J2EEDeployableFactory.ID+":"+targetComponent.getName()); //$NON-NLS-1$ } return module; } /** * Determine if the component is nested J2EE module on the application.xml of this EAR * @param aComponent * @return boolean is passed in component a nested J2EE module on this EAR */ private boolean isNestedJ2EEModule(IVirtualComponent aComponent, IVirtualReference[] references, EARArtifactEdit edit) { if (edit==null) return false; Application app = edit.getApplication(); IVirtualReference reference = getReferenceNamed(references,aComponent.getName()); // Ensure module URI exists on EAR DD for binary archive return app.getFirstModule(reference.getArchiveName()) != null; } private IVirtualReference getReferenceNamed(IVirtualReference[] references, String name) { for (int i=0; i<references.length; i++) { if (references[i].getReferencedComponent().getName().equals(name)) return references[i]; } return null; } protected ArtifactEdit getComponentArtifactEditForRead() { return EARArtifactEdit.getEARArtifactEditForRead(component.getProject()); } /** * The references for J2EE module deployment are only those child modules of EARs or web modules */ protected IVirtualReference[] getReferences(IVirtualComponent aComponent) { if (aComponent == null || aComponent.isBinary()) { return new IVirtualReference[] {}; } else if (J2EEProjectUtilities.isDynamicWebProject(aComponent.getProject())) { return getWebLibModules((J2EEModuleVirtualComponent)aComponent); } else if (J2EEProjectUtilities.isEARProject(aComponent.getProject())) { return super.getReferences(aComponent); } else { return new IVirtualReference[] {}; } } /** * This method will return the list of dependent modules which are utility jars in the web lib * folder of the deployed path of the module. It will not return null. * * @return array of the web library dependent modules */ private IVirtualReference[] getWebLibModules(J2EEModuleVirtualComponent comp) { List result = new ArrayList(); IVirtualReference[] refComponents = comp.getNonManifestReferences(); // Check the deployed path to make sure it has a lib parent folder and matchs the web.xml // base path for (int i = 0; i < refComponents.length; i++) { if (refComponents[i].getRuntimePath().equals(WEBLIB)) result.add(refComponents[i]); } return (IVirtualReference[]) result.toArray(new IVirtualReference[result.size()]); } /* * Add any classpath component dependencies from this component */ private void addReferencedComponentClasspathDependencies(final IVirtualComponent component, final boolean web) { final IVirtualReference[] refs = component.getReferences(); final Set absolutePaths = new HashSet(); for (int i = 0; i < refs.length; i++) { final IVirtualReference reference = refs[i]; final IPath runtimePath = reference.getRuntimePath(); final IVirtualComponent referencedComponent = reference.getReferencedComponent(); // if we are adding to a web project, only process references with the /WEB-INF/lib runtime path if (web && !runtimePath.equals(WEBLIB)) { continue; } // if the reference cannot export dependencies, skip if (!canExportClasspathComponentDependencies(referencedComponent)) { continue; } if (!referencedComponent.isBinary() && referencedComponent instanceof J2EEModuleVirtualComponent) { final IVirtualReference[] cpRefs = ((J2EEModuleVirtualComponent) referencedComponent).getJavaClasspathReferences(); for (int j = 0; j < cpRefs.length; j++) { final IVirtualReference cpRef = cpRefs[j]; IPath cpRefRuntimePath = cpRef.getRuntimePath(); // only process references with ../ mapping if (cpRefRuntimePath.equals(IClasspathDependencyConstants.RUNTIME_MAPPING_INTO_CONTAINER_PATH)) { // runtime path within deployed app will be runtime path of parent component cpRefRuntimePath = runtimePath; } if (cpRef.getReferencedComponent() instanceof VirtualArchiveComponent) { // want to avoid adding dups final IPath absolutePath = ClasspathDependencyUtil.getClasspathVirtualReferenceLocation(cpRef); if (absolutePaths.contains(absolutePath)) { // have already added a member for this archive continue; } else { addUtilMember(component, cpRef, cpRefRuntimePath); absolutePaths.add(absolutePath); } } } } } } private boolean canExportClasspathComponentDependencies(IVirtualComponent component) { final IProject project = component.getProject(); // check for valid project type if (J2EEProjectUtilities.isEJBProject(project) || J2EEProjectUtilities.isDynamicWebProject(project) || J2EEProjectUtilities.isJCAProject(project) || J2EEProjectUtilities.isUtilityProject(project)) { return true; } return false; } private void saveClasspathDependencyURIs(IVirtualComponent component) { if (!component.isBinary() && component instanceof J2EEModuleVirtualComponent) { final IVirtualReference[] cpRefs = ((J2EEModuleVirtualComponent) component).getJavaClasspathReferences(); for (int j = 0; j < cpRefs.length; j++) { final IVirtualReference cpRef = cpRefs[j]; // if we are adding to an EAR project, only process references with the root mapping if (!cpRef.getRuntimePath().equals(IClasspathDependencyConstants.RUNTIME_MAPPING_INTO_CONTAINER_PATH)) { // fails the runtime path test continue; } if (cpRef.getReferencedComponent() instanceof VirtualArchiveComponent) { classpathComponentDependencyURIs.add(cpRef.getArchiveName()); } } } } /** * Returns <code>true</code> if this module has a simple structure based on a * single root folder, and <code>false</code> otherwise. * <p> * In a single root structure, all files that are contained within the root folder * are part of the module, and are already in the correct module structure. No * module resources exist outside of this single folder. * * For J2EE, this method will check if the project is already in J2EE spec standard output form. * The project must follow certain rules, but in general, the project's content roots must be source folders * and the output folder must also be the the content root folder. * </p> * * @return <code>true</code> if this module has a single root structure, and * <code>false</code> otherwise */ public boolean isSingleRootStructure() { StructureEdit edit = null; try { edit = StructureEdit.getStructureEditForRead(getProject()); if (edit == null || edit.getComponent() == null) return false; WorkbenchComponent wbComp = edit.getComponent(); List resourceMaps = wbComp.getResources(); if (J2EEProjectUtilities.isEARProject(getProject())) { // Always return false for EARs so that members for EAR are always calculated and j2ee modules // are filtered out return false; } else if (J2EEProjectUtilities.isDynamicWebProject(getProject())) { // If there are any web lib jar references, this is not a standard project IVirtualReference[] references = ((J2EEModuleVirtualComponent)component).getNonManifestReferences(); for (int i=0; i<references.length; i++) { if (references[i].getReferencedComponent().isBinary()) return false; } // Ensure there are only basic component resource mappings -- one for the content folder // and any for src folders mapped to WEB-INF/classes if (hasDefaultWebResourceMappings(resourceMaps)) { // Verify only one java output folder if (getJavaOutputFolders().length==1) { // Verify the java output folder is to <content root>/WEB-INF/classes IPath javaOutputPath = getJavaOutputFolders()[0].getProjectRelativePath(); IPath compRootPath = component.getRootFolder().getUnderlyingFolder().getProjectRelativePath(); if (compRootPath.append(J2EEConstants.WEB_INF_CLASSES).equals(javaOutputPath)) return true; } } return false; } else if (J2EEProjectUtilities.isEJBProject(getProject()) || J2EEProjectUtilities.isJCAProject(getProject()) || J2EEProjectUtilities.isApplicationClientProject(getProject()) || J2EEProjectUtilities.isUtilityProject(getProject())) { // Ensure there are only source folder component resource mappings to the root content folder if (isRootResourceMapping(resourceMaps,false)) { // Verify only one java outputfolder if (getJavaOutputFolders().length==1) { // At this point for utility projects, this project is optimized, we can just use the output folder if (J2EEProjectUtilities.isUtilityProject(getProject())) return true; // Verify the java output folder is the same as one of the content roots IPath javaOutputPath = getJavaOutputFolders()[0].getProjectRelativePath(); IContainer[] rootFolders = component.getRootFolder().getUnderlyingFolders(); for (int i=0; i<rootFolders.length; i++) { IPath compRootPath = rootFolders[i].getProjectRelativePath(); if (javaOutputPath.equals(compRootPath)) return true; } } } return false; } return true; } finally { if (edit !=null) edit.dispose(); } } /** * Ensure that any component resource mappings are for source folders and * that they map to the root content folder * * @param resourceMaps * @return boolean */ private boolean isRootResourceMapping(List resourceMaps, boolean isForEAR) { // If the list is empty, return false if (resourceMaps.size()<1) return false; for (int i=0; i<resourceMaps.size(); i++) { ComponentResource resourceMap = (ComponentResource) resourceMaps.get(i); // Verify it maps to "/" for the content root if (!resourceMap.getRuntimePath().equals(Path.ROOT)) return false; // If this is not for an EAR, verify it is also a src container if (!isForEAR) { IPath sourcePath = getProject().getFullPath().append(resourceMap.getSourcePath()); if (!isSourceContainer(sourcePath)) return false; } } return true; } /** * Checks if the path argument is to a source container for the project. * * @param a workspace relative full path * @return is path a source container? */ private boolean isSourceContainer(IPath path) { IPackageFragmentRoot[] srcContainers = getSourceContainers(); for (int i=0; i<srcContainers.length; i++) { if (srcContainers[i].getPath().equals(path)) return true; } return false; } /** * Ensure the default web setup is correct with one resource map and any number of java * resource maps to WEB-INF/classes * * @param resourceMaps * @return boolean */ private boolean hasDefaultWebResourceMappings(List resourceMaps) { int rootValidMaps = 0; int javaValidRoots = 0; // If there aren't at least 2 maps, return false if (resourceMaps.size()<2) return false; IPath webInfClasses = new Path(J2EEConstants.WEB_INF_CLASSES).makeAbsolute(); for (int i=0; i<resourceMaps.size(); i++) { ComponentResource resourceMap = (ComponentResource) resourceMaps.get(i); IPath sourcePath = getProject().getFullPath().append(resourceMap.getSourcePath()); // Verify if the map is for the content root if (resourceMap.getRuntimePath().equals(Path.ROOT)) { rootValidMaps++; // Verify if the map is for a java src folder and is mapped to "WEB-INF/classes" } else if (resourceMap.getRuntimePath().equals(webInfClasses) && isSourceContainer(sourcePath)) { javaValidRoots++; // Otherwise we bail because we have a non optimized map } else { return false; } } // Make sure only one of the maps is the content root, and that at least one is for the java folder return rootValidMaps==1 && javaValidRoots>0; } /** * This method is added for performance reasons. * It assumes the virtual component is not using any flexible features and is in a standard J2EE format * with one component root folder and an output folder the same as its content folder. This will bypass * the virtual component API and just return the module resources as they are on disk. * * @return array of ModuleResources * @throws CoreException */ private IModuleResource[] getOptimizedMembers() throws CoreException { if (component != null) { // For java utility modules, we can just use the output container, at this point we know there is only one if (J2EEProjectUtilities.isUtilityProject(getProject())) { return getModuleResources(Path.EMPTY, getJavaOutputFolders()[0]); } // For J2EE modules, we use the contents of the content root else { IVirtualFolder vFolder = component.getRootFolder(); return getModuleResources(Path.EMPTY, vFolder.getUnderlyingFolder()); } } return new IModuleResource[] {}; } /** * This method will return from cache or add to cache whether or not an output container * is mapped in the virtual component. * * @param outputContainer * @return if output container is mapped */ private boolean isOutputContainerMapped(IContainer outputContainer) { if (outputContainer == null) return false; HashMap outputMaps = getCachedOutputMappings(); Boolean result = (Boolean) outputMaps.get(outputContainer); if (result == null) { // If there are any component resources for the container, we know it is mapped if (ComponentCore.createResources(outputContainer).length > 0) result = Boolean.TRUE; // Otherwise it is not mapped else result = Boolean.FALSE; // Cache the result in the map for this output container outputMaps.put(outputContainer, result); } return result.booleanValue(); } /** * Lazy initialize the cached output mappings * @return HashMap */ private HashMap getCachedOutputMappings() { if (cachedOutputMappings==null) cachedOutputMappings = new HashMap(); return cachedOutputMappings; } /** * Lazy initialize the cached source - output pairings * @return HashMap */ private HashMap getCachedSourceOutputPairs() { if (cachedSourceOutputPairs==null) cachedSourceOutputPairs = new HashMap(); return cachedSourceOutputPairs; } /** * This file should be added to the members list from the virtual component maps only if: * a) it is not in a source folder * b) it is in a source folder, and the corresponding output folder is a mapped component resource * * @return boolean should file be added to members */ protected boolean shouldAddComponentFile(IFile file) { IPackageFragmentRoot sourceContainer = getSourceContainer(file); // If the file is not in a source container, return true if (sourceContainer==null) { return true; // Else if it is a source container and the output container is mapped in the component, return true // Otherwise, return false. } else { IContainer outputContainer = getOutputContainer(sourceContainer); return outputContainer!=null && isOutputContainerMapped(outputContainer); } } }
true
true
public IModuleResource[] members() throws CoreException { members.clear(); classpathComponentDependencyURIs.clear(); // Handle binary components if (component instanceof J2EEModuleVirtualArchiveComponent) return getBinaryModuleMembers(); if (J2EEProjectUtilities.isEARProject(component.getProject())) { // If an EAR, add classpath contributions for all referenced modules addReferencedComponentClasspathDependencies(component, false); } else { if (J2EEProjectUtilities.isDynamicWebProject(component.getProject())) { // If a web, add classpath contributions for all WEB-INF/lib modules addReferencedComponentClasspathDependencies(component, true); } if (canExportClasspathComponentDependencies(component)){ saveClasspathDependencyURIs(component); } } // If j2ee project structure is a single root structure, just return optimized members if (isSingleRootStructure()) { final IModuleResource[] resources = getOptimizedMembers(); if (!classpathComponentDependencyURIs.isEmpty()) { for (int i = 0; i < resources.length; i++) { if (resources[i] instanceof IModuleFolder) { IModuleFolder folder = (IModuleFolder) resources[i]; if (folder.getName().equals(J2EEConstants.META_INF)) { IModuleResource[] files = folder.members(); for (int j = 0; j < files.length; j++) { files[i] = replaceManifestFile((IModuleFile) files[j]); } } } } } return resources; } cachedSourceContainers = J2EEProjectUtilities.getSourceContainers(getProject()); try { IPath javaPath = Path.EMPTY; if (J2EEProjectUtilities.isDynamicWebProject(component.getProject())) javaPath = WEB_CLASSES_PATH; if (component != null) { IVirtualFolder vFolder = component.getRootFolder(); IModuleResource[] mr = getMembers(vFolder, Path.EMPTY); int size = mr.length; for (int j = 0; j < size; j++) { members.add(mr[j]); } } IContainer[] javaCont = getJavaOutputFolders(); int size = javaCont.length; for (int i = 0; i < size; i++) { //If the java output is in the scope of the virtual component, ignore to avoid duplicates if (ComponentCore.createResources(javaCont[i]).length > 0) continue; IModuleResource[] mr = getMembers(javaCont[i], javaPath, javaPath, javaCont); int size2 = mr.length; for (int j = 0; j < size2; j++) { members.add(mr[j]); } } if (component != null) { addUtilMembers(component); List consumableMembers = getConsumableReferencedMembers(component); if (!consumableMembers.isEmpty()) members.addAll(consumableMembers); } IModuleResource[] mr = new IModuleResource[members.size()]; members.toArray(mr); return mr; } finally { cachedSourceContainers = null; cachedOutputContainers = null; cachedOutputMappings = null; cachedSourceOutputPairs = null; } }
public IModuleResource[] members() throws CoreException { members.clear(); classpathComponentDependencyURIs.clear(); // Handle binary components if (component instanceof J2EEModuleVirtualArchiveComponent) return getBinaryModuleMembers(); if (J2EEProjectUtilities.isEARProject(component.getProject())) { // If an EAR, add classpath contributions for all referenced modules addReferencedComponentClasspathDependencies(component, false); } else { if (J2EEProjectUtilities.isDynamicWebProject(component.getProject())) { // If a web, add classpath contributions for all WEB-INF/lib modules addReferencedComponentClasspathDependencies(component, true); } if (canExportClasspathComponentDependencies(component)){ saveClasspathDependencyURIs(component); } } // If j2ee project structure is a single root structure, just return optimized members if (isSingleRootStructure()) { final IModuleResource[] resources = getOptimizedMembers(); if (!classpathComponentDependencyURIs.isEmpty()) { for (int i = 0; i < resources.length; i++) { if (resources[i] instanceof IModuleFolder) { IModuleFolder folder = (IModuleFolder) resources[i]; if (folder.getName().equals(J2EEConstants.META_INF)) { IModuleResource[] files = folder.members(); for (int j = 0; j < files.length; j++) { files[j] = replaceManifestFile((IModuleFile) files[j]); } } } } } return resources; } cachedSourceContainers = J2EEProjectUtilities.getSourceContainers(getProject()); try { IPath javaPath = Path.EMPTY; if (J2EEProjectUtilities.isDynamicWebProject(component.getProject())) javaPath = WEB_CLASSES_PATH; if (component != null) { IVirtualFolder vFolder = component.getRootFolder(); IModuleResource[] mr = getMembers(vFolder, Path.EMPTY); int size = mr.length; for (int j = 0; j < size; j++) { members.add(mr[j]); } } IContainer[] javaCont = getJavaOutputFolders(); int size = javaCont.length; for (int i = 0; i < size; i++) { //If the java output is in the scope of the virtual component, ignore to avoid duplicates if (ComponentCore.createResources(javaCont[i]).length > 0) continue; IModuleResource[] mr = getMembers(javaCont[i], javaPath, javaPath, javaCont); int size2 = mr.length; for (int j = 0; j < size2; j++) { members.add(mr[j]); } } if (component != null) { addUtilMembers(component); List consumableMembers = getConsumableReferencedMembers(component); if (!consumableMembers.isEmpty()) members.addAll(consumableMembers); } IModuleResource[] mr = new IModuleResource[members.size()]; members.toArray(mr); return mr; } finally { cachedSourceContainers = null; cachedOutputContainers = null; cachedOutputMappings = null; cachedSourceOutputPairs = null; } }
diff --git a/src/btwmod/tickmonitor/BTWModTickMonitor.java b/src/btwmod/tickmonitor/BTWModTickMonitor.java index 911c57e..2cda6cb 100644 --- a/src/btwmod/tickmonitor/BTWModTickMonitor.java +++ b/src/btwmod/tickmonitor/BTWModTickMonitor.java @@ -1,459 +1,459 @@ package btwmod.tickmonitor; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import net.minecraft.server.MinecraftServer; import net.minecraft.src.ChunkCoordIntPair; import net.minecraft.src.CommandHandler; import btwmods.IMod; import btwmods.ModLoader; import btwmods.StatsAPI; import btwmods.io.Settings; import btwmods.measure.Average; import btwmods.network.CustomPacketEvent; import btwmods.network.INetworkListener; import btwmods.player.IInstanceListener; import btwmods.player.InstanceEvent; import btwmods.stats.IStatsListener; import btwmods.stats.StatsEvent; import btwmods.stats.data.BasicStats; import btwmods.stats.data.BasicStatsComparator; import btwmods.stats.data.BasicStatsMap; import btwmods.util.BasicFormatter; import btwmods.Util; public class BTWModTickMonitor implements IMod, IStatsListener, INetworkListener, IInstanceListener { private static int topNumber = 20; private static boolean includeHistory = false; private static String publicLink = null; private static File htmlFile = new File(new File("."), "stats.html"); private static File jsonFile = new File(new File("."), "stats.txt"); private static long tooLongWarningTime = 1000; private static long reportingDelay = 1000; public static boolean includeHistory() { return includeHistory; } public static int getTopNumber() { return topNumber; } private boolean isRunning = true; // TODO: make this false by default. private long lastStatsTime = 0; private int lastTickCounter = -1; private Average statsActionTime = new Average(10); private Average statsActionIOTime = new Average(10); private Average ticksPerSecond = new Average(10); private Gson gson; public volatile boolean hideChunkCoords = true; @Override public String getName() { return "Tick Monitor"; } @Override public void init(Settings settings) { lastStatsTime = System.currentTimeMillis(); gson = new GsonBuilder() .registerTypeAdapter(Class.class, new TypeAdapters.ClassAdapter()) .registerTypeAdapter(ChunkCoordIntPair.class, new TypeAdapters.ChunkCoordIntPairAdapter()) .registerTypeAdapter(Average.class, new TypeAdapters.AverageTypeAdapter(this)) .registerTypeAdapter(BasicStatsMap.class, new TypeAdapters.BasicStatsMapAdapter()) .setPrettyPrinting() .enableComplexMapKeySerialization() .create(); // Load settings if (settings.hasKey("publiclink") && !(new File(settings.get("publiclink")).isDirectory())) { publicLink = settings.get("publiclink"); } if (settings.hasKey("htmlfile") && !(new File(settings.get("htmlfile")).isDirectory())) { htmlFile = new File(settings.get("htmlfile")); } if (settings.hasKey("jsonfile") && !(new File(settings.get("jsonfile")).isDirectory())) { jsonFile = new File(settings.get("jsonfile")); } if (settings.isBoolean("runonstartup")) { isRunning = settings.getBoolean("runonstartup"); } if (settings.isInt("reportingdelay")) { reportingDelay = Math.max(50, settings.getInt("reportingdelay")); } if (settings.isLong("toolongwarningtime")) { tooLongWarningTime = Math.min(500L, settings.getLong("toolongwarningtime")); } if (settings.isBoolean("hidechunkcoords")) { hideChunkCoords = settings.getBoolean("hidechunkcoords"); } if (settings.isBoolean("includehistory")) { includeHistory = settings.getBoolean("includehistory"); } // Add the listener only if isRunning is true by default. if (isRunning) StatsAPI.addListener(this); ((CommandHandler)MinecraftServer.getServer().getCommandManager()).registerCommand(new MonitorCommand(this)); } @Override public void unload() { StatsAPI.removeListener(this); } public void setIsRunning(boolean value) { if (isRunning == value) return; lastStatsTime = 0; lastTickCounter = -1; if (isRunning) StatsAPI.removeListener(this); else StatsAPI.addListener(this); isRunning = value; } public boolean isRunning() { return isRunning; } /** * WARNING: This runs in a separate thread. Be very strict about what this accesses beyond the passed parameter. Do * not access any of the APIs, and be careful how class variables are used outside of statsAction(). */ @Override public void statsAction(StatsEvent event) { long currentTime = System.currentTimeMillis(); long startNano = System.nanoTime(); boolean detailedMeasurementsEnabled = StatsAPI.detailedMeasurementsEnabled; if (lastStatsTime == 0) { lastStatsTime = System.currentTimeMillis(); } else if (currentTime - lastStatsTime > reportingDelay) { int numTicks = event.tickCounter - lastTickCounter; long timeElapsed = currentTime - lastStatsTime; long timeSinceLastTick = currentTime - event.serverStats.lastTickEnd; - ticksPerSecond.record((int)((double)numTicks / (double)timeElapsed * 100000D)); + ticksPerSecond.record((long)((double)numTicks / (double)timeElapsed * 100000D)); long jsonTime = System.nanoTime(); JsonObject jsonObj = new JsonObject(); - jsonObj.addProperty("timeElapsed", timeElapsed); + jsonObj.addProperty("tickCounter", event.tickCounter); jsonObj.addProperty("timeSinceLastTick", timeSinceLastTick); - jsonObj.addProperty("numTicks", numTicks); + jsonObj.addProperty("ticksSinceLastStatsAction", numTicks); jsonObj.addProperty("time", BasicFormatter.dateFormat.format(new Date(currentTime))); jsonObj.addProperty("detailedMeasurements", StatsAPI.detailedMeasurementsEnabled); jsonObj.add("statsActionTime", gson.toJsonTree(statsActionTime)); jsonObj.add("statsActionIOTime", gson.toJsonTree(statsActionIOTime)); jsonObj.add("ticksPerSecondArray", gson.toJsonTree(ticksPerSecond)); jsonObj.addProperty("jsonTime", "_____JSONTIME_____"); jsonObj.add("statsEvent", gson.toJsonTree(event)); String json = gson.toJson(jsonObj).replace("_____JSONTIME_____", Util.DECIMAL_FORMAT_3.format((jsonTime = System.nanoTime() - jsonTime) * 1.0E-6D)); // Debugging loop to ramp up CPU usage by the thread. //for (int i = 0; i < 20000; i++) new String(new char[10000]).replace('\0', 'a'); StringBuilder html = new StringBuilder("<html><head><title>Minecraft Server Stats</title><meta http-equiv=\"refresh\" content=\"2\"></head><body><h1>Minecraft Server Stats</h1>"); html.append("<table border=\"0\"><tbody>"); html.append("<tr><th align=\"right\">Updated:<th><td>").append(BasicFormatter.dateFormat.format(new Date())).append("</td></tr>"); if (event.serverStats.lastTickEnd >= 0) { html.append("<tr><th align=\"right\">Last Tick:<th><td>").append(timeSinceLastTick >= 1000 ? "Over " + (timeSinceLastTick / 1000) + " seconds" : timeSinceLastTick + "ms").append(" ago.</td></tr>"); } html.append("<tr><th align=\"right\">Average StatsAPI Thread Time:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.statsThreadTime.getAverage() * 1.0E-6D)).append(" ms</td></tr>"); html.append("<tr><th align=\"right\">Average StatsAPI Polled:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.statsThreadQueueCount.getAverage())).append("</td></tr>"); html.append("<tr><th align=\"right\">Average Tick Monitor Time:<th><td>"); if (statsActionTime.getTick() == 0) html.append("..."); else html.append(Util.DECIMAL_FORMAT_3.format(statsActionTime.getAverage() * 1.0E-6D)).append("ms (" + (int)(statsActionIOTime.getAverage() * 100 / statsActionTime.getAverage()) + "% IO)"); html.append("</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Tick Num:<th><td>").append(event.tickCounter); if (lastTickCounter >= 0) html.append(" (~").append(Util.DECIMAL_FORMAT_3.format(ticksPerSecond.getAverage() / 100D)).append("/sec)"); html.append("</td></tr>"); html.append("<tr><th align=\"right\">Average Full Tick:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.tickTime.getAverage() * 1.0E-6D)).append(" ms</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); double worldsTotal = 0; for (int i = 0; i < event.worldStats.length; i++) { worldsTotal += event.worldStats[i].worldTickTime.getAverage(); html.append("<tr><th align=\"right\">World ").append(i).append(" Averages:<th><td>") .append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].worldTickTime.getAverage() * 1.0E-6D) + "ms"); if (detailedMeasurementsEnabled) html.append(" (") .append("E: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].entities.getAverage() * 1.0E-6D)).append("ms") .append(" + M: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].mobSpawning.getAverage() * 1.0E-6D)).append("ms") .append(" + B: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].blockTick.getAverage() * 1.0E-6D)).append("ms") .append(" + W: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].weather.getAverage() * 1.0E-6D)).append("ms") .append(" + T: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].timeSync.getAverage() * 1.0E-6D)).append("ms") .append(" + CS: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].buildActiveChunkSet.getAverage() * 1.0E-6D)).append("ms") .append(" + L: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].checkPlayerLight.getAverage() * 1.0E-6D)).append("ms") .append(")"); html.append("</td></tr>"); html.append("<tr><th align=\"right\">&nbsp;<th><td>") .append("Chunks: ") .append((int)event.worldStats[i].loadedChunks.getLatest()).append(" loaded, ") .append(event.worldStats[i].id2ChunkMap).append(" cached, ") .append((int)event.worldStats[i].droppedChunksSet.getAverage()).append(" dropped"); if (detailedMeasurementsEnabled) html.append(" | ").append((int)event.worldStats[i].measurementQueue.getAverage()).append(" measurements per tick"); html.append("</td></tr>"); } html.append("<tr><th align=\"right\">Worlds Total:<th><td>").append(Util.DECIMAL_FORMAT_3.format(worldsTotal * 1.0E-6D)).append(" ms (" + (int)(worldsTotal / event.serverStats.tickTime.getAverage() * 100) + "% of full tick)</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Average Received Packet Count:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.receivedPacketCount.getAverage())).append("</td></tr>"); html.append("<tr><th align=\"right\">Average Sent Packet Count:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.sentPacketCount.getAverage())).append("</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Average Received Packet Size:<th><td>").append((int)event.serverStats.receivedPacketSize.getAverage()).append(" bytes</td></tr>"); html.append("<tr><th align=\"right\">Average Sent Packet Size:<th><td>").append((int)event.serverStats.sentPacketSize.getAverage()).append(" bytes</td></tr>"); html.append("</tbody></table>"); if (detailedMeasurementsEnabled) { for (int i = 0; i < event.worldStats.length; i++) { outputWorldDetails(event, html, i); } } html.append("</body></html>"); long startWriteTime = System.currentTimeMillis(); long startWriteNano = System.nanoTime(); try { FileWriter htmlWriter = new FileWriter(htmlFile); htmlWriter.write(html.toString()); htmlWriter.close(); } catch (Throwable e) { ModLoader.outputError(getName() + " failed to write to " + htmlFile.getPath() + ": " + e.getMessage()); } try { FileWriter jsonWriter = new FileWriter(jsonFile); jsonWriter.write(json); jsonWriter.close(); } catch (Throwable e) { ModLoader.outputError(getName() + " failed to write to " + jsonFile.getPath() + ": " + e.getMessage()); } long endNano = System.nanoTime(); long endTime = System.currentTimeMillis(); if (System.currentTimeMillis() - currentTime > tooLongWarningTime) ModLoader.outputError(getName() + " took " + (endTime - currentTime) + "ms (~" + ((endTime - startWriteTime) * 100 / (endTime - currentTime)) + "% disk IO) to process stats. Note: This will *not* slow the main Minecraft server thread."); statsActionTime.record(endNano - startNano); statsActionIOTime.record(endNano - startWriteNano); lastTickCounter = event.tickCounter; lastStatsTime = System.currentTimeMillis(); } } private void outputWorldDetails(StatsEvent event, StringBuilder html, int world) { List<Map.Entry<ChunkCoordIntPair, BasicStats>> chunkEntries = new ArrayList<Map.Entry<ChunkCoordIntPair, BasicStats>>(event.worldStats[world].chunkStats.entrySet()); html.append("<h2>World ").append(world).append(" Top " + topNumber + ":</h2>"); html.append("<table border=\"0\"><thead><tr><th>Chunks By Tick Time</th><th>Chunks By Entity Count</th><th>Entities By Tick Time</th><th>Entities By Count</th><th>TileEntities By Tick Time</th></tr></thead><tbody><tr><td valign=\"top\">"); { Collections.sort(chunkEntries, new BasicStatsComparator<ChunkCoordIntPair>(BasicStatsComparator.Stat.TICKTIME, true)); html.append("<table border=\"0\"><thead><tr><th>Chunk</th><th>Tick Time</th><th>Entities</th></tr></thead><tbody>"); double chunksTotal = 0; int entitiesTotal = 0; int displayed = 0; for (int i = 0; i < chunkEntries.size(); i++) { if (chunkEntries.get(i).getValue().tickTime.getTotal() != 0 && displayed <= topNumber) { displayed++; html.append("<tr><td>"); if (hideChunkCoords) html.append("(hidden)"); else html.append(chunkEntries.get(i).getKey().chunkXPos).append("/").append(chunkEntries.get(i).getKey().chunkZPos); html.append("</td><td>").append(Util.DECIMAL_FORMAT_3.format(chunkEntries.get(i).getValue().tickTime.getAverage() * 1.0E-6D)) .append(" ms</td><td>").append(chunkEntries.get(i).getValue().count) .append("</td></tr>"); } chunksTotal += chunkEntries.get(i).getValue().tickTime.getAverage(); entitiesTotal += chunkEntries.get(i).getValue().count; } html.append("<tr><td>Totals</td><td>").append(Util.DECIMAL_FORMAT_3.format(chunksTotal * 1.0E-6D)).append("ms</td><td>").append(entitiesTotal).append("</td></tr>"); html.append("</tbody></table>"); } html.append("</td><td valign=\"top\">"); { Collections.sort(chunkEntries, new BasicStatsComparator<ChunkCoordIntPair>(BasicStatsComparator.Stat.COUNT, true)); html.append("<table border=\"0\"><thead><tr><th>Chunk</th><th>Tick Time</th><th>Entities</th></tr></thead><tbody>"); double chunksTotal = 0; int displayed = 0; int entitiesTotal = 0; for (int i = 0; i < chunkEntries.size(); i++) { if (chunkEntries.get(i).getValue().tickTime.getTotal() != 0 && displayed <= topNumber) { displayed++; html.append("<tr><td>"); if (hideChunkCoords) html.append("(hidden)"); else html.append(chunkEntries.get(i).getKey().chunkXPos).append("/").append(chunkEntries.get(i).getKey().chunkZPos); html.append("</td><td>").append(Util.DECIMAL_FORMAT_3.format(chunkEntries.get(i).getValue().tickTime.getAverage() * 1.0E-6D)) .append(" ms</td><td>").append(chunkEntries.get(i).getValue().count) .append("</td></tr>"); } chunksTotal += chunkEntries.get(i).getValue().tickTime.getAverage(); entitiesTotal += chunkEntries.get(i).getValue().count; } html.append("<tr><td>Totals</td><td>").append(Util.DECIMAL_FORMAT_3.format(chunksTotal * 1.0E-6D)).append("ms</td><td>").append(entitiesTotal).append("</td></tr>"); html.append("</tbody></table>"); } List<Map.Entry<Class, BasicStats>> entityEntries = new ArrayList<Map.Entry<Class, BasicStats>>(event.worldStats[world].entityStats.entrySet()); html.append("</td><td valign=\"top\">"); { Collections.sort(entityEntries, new BasicStatsComparator<Class>(BasicStatsComparator.Stat.TICKTIME, true)); html.append("<table border=\"0\"><thead><tr><th>Entity</th><th>Tick Time</th><th>Count</th></tr></thead><tbody>"); double entitiesTotal = 0; int displayed = 0; for (int i = 0; i < entityEntries.size(); i++) { if (entityEntries.get(i).getValue().tickTime.getTotal() != 0 && displayed <= topNumber) { displayed++; html.append("<tr><td>").append(entityEntries.get(i).getKey().getSimpleName()) .append("</td><td>").append(Util.DECIMAL_FORMAT_3.format(entityEntries.get(i).getValue().tickTime.getAverage() * 1.0E-6D)) .append(" ms</td><td>").append(entityEntries.get(i).getValue().count) .append("</td></tr>"); } entitiesTotal += entityEntries.get(i).getValue().tickTime.getAverage(); } html.append("<tr><td>Totals</td><td colspan=\"2\">").append(Util.DECIMAL_FORMAT_3.format(entitiesTotal * 1.0E-6D)).append("ms</td></tr>"); html.append("</tbody></table>"); } html.append("</td><td valign=\"top\">"); { Collections.sort(entityEntries, new BasicStatsComparator<Class>(BasicStatsComparator.Stat.COUNT, true)); html.append("<table border=\"0\"><thead><tr><th>Entity</th><th>Tick Time</th><th>Count</th></tr></thead><tbody>"); double entitiesTotal = 0; int displayed = 0; for (int i = 0; i < entityEntries.size(); i++) { if (entityEntries.get(i).getValue().tickTime.getTotal() != 0 && displayed <= topNumber) { displayed++; html.append("<tr><td>").append(entityEntries.get(i).getKey().getSimpleName()) .append("</td><td>").append(Util.DECIMAL_FORMAT_3.format(entityEntries.get(i).getValue().tickTime.getAverage() * 1.0E-6D)) .append(" ms</td><td>").append(entityEntries.get(i).getValue().count) .append("</td></tr>"); } entitiesTotal += entityEntries.get(i).getValue().tickTime.getAverage(); } html.append("<tr><td>Totals</td><td colspan=\"2\">").append(Util.DECIMAL_FORMAT_3.format(entitiesTotal * 1.0E-6D)).append("ms</td></tr>"); html.append("</tbody></table>"); } List<Map.Entry<Class, BasicStats>> tileEntityEntries = new ArrayList<Map.Entry<Class, BasicStats>>(event.worldStats[world].tileEntityStats.entrySet()); html.append("</td><td valign=\"top\">"); { Collections.sort(tileEntityEntries, new BasicStatsComparator<Class>(BasicStatsComparator.Stat.TICKTIME, true)); html.append("<table border=\"0\"><thead><tr><th>Tile Entity</th><th>Tick Time</th><th>Count</th></tr></thead><tbody>"); double entitiesTotal = 0; int displayed = 0; for (int i = 0; i < tileEntityEntries.size(); i++) { if (tileEntityEntries.get(i).getValue().tickTime.getTotal() != 0 && displayed <= topNumber) { displayed++; html.append("<tr><td>").append(tileEntityEntries.get(i).getKey().getSimpleName()) .append("</td><td>").append(Util.DECIMAL_FORMAT_3.format(tileEntityEntries.get(i).getValue().tickTime.getAverage() * 1.0E-6D)) .append(" ms</td><td>").append(tileEntityEntries.get(i).getValue().count) .append("</td></tr>"); } entitiesTotal += tileEntityEntries.get(i).getValue().tickTime.getAverage(); } html.append("<tr><td>Totals</td><td colspan=\"2\">").append(Util.DECIMAL_FORMAT_3.format(entitiesTotal * 1.0E-6D)).append("ms</td></tr>"); html.append("</tbody></table>"); } html.append("</td></tr></tbody></table>"); } @Override public IMod getMod() { return this; } @Override public void customPacketAction(CustomPacketEvent event) { // TODO: remove debug throw throw new IllegalArgumentException(); } @Override public void instanceAction(InstanceEvent event) { if (publicLink != null && event.getType() == InstanceEvent.TYPE.LOGIN) event.getPlayerInstance().sendChatToPlayer("Tick stats are available at " + publicLink); } }
false
true
public void statsAction(StatsEvent event) { long currentTime = System.currentTimeMillis(); long startNano = System.nanoTime(); boolean detailedMeasurementsEnabled = StatsAPI.detailedMeasurementsEnabled; if (lastStatsTime == 0) { lastStatsTime = System.currentTimeMillis(); } else if (currentTime - lastStatsTime > reportingDelay) { int numTicks = event.tickCounter - lastTickCounter; long timeElapsed = currentTime - lastStatsTime; long timeSinceLastTick = currentTime - event.serverStats.lastTickEnd; ticksPerSecond.record((int)((double)numTicks / (double)timeElapsed * 100000D)); long jsonTime = System.nanoTime(); JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("timeElapsed", timeElapsed); jsonObj.addProperty("timeSinceLastTick", timeSinceLastTick); jsonObj.addProperty("numTicks", numTicks); jsonObj.addProperty("time", BasicFormatter.dateFormat.format(new Date(currentTime))); jsonObj.addProperty("detailedMeasurements", StatsAPI.detailedMeasurementsEnabled); jsonObj.add("statsActionTime", gson.toJsonTree(statsActionTime)); jsonObj.add("statsActionIOTime", gson.toJsonTree(statsActionIOTime)); jsonObj.add("ticksPerSecondArray", gson.toJsonTree(ticksPerSecond)); jsonObj.addProperty("jsonTime", "_____JSONTIME_____"); jsonObj.add("statsEvent", gson.toJsonTree(event)); String json = gson.toJson(jsonObj).replace("_____JSONTIME_____", Util.DECIMAL_FORMAT_3.format((jsonTime = System.nanoTime() - jsonTime) * 1.0E-6D)); // Debugging loop to ramp up CPU usage by the thread. //for (int i = 0; i < 20000; i++) new String(new char[10000]).replace('\0', 'a'); StringBuilder html = new StringBuilder("<html><head><title>Minecraft Server Stats</title><meta http-equiv=\"refresh\" content=\"2\"></head><body><h1>Minecraft Server Stats</h1>"); html.append("<table border=\"0\"><tbody>"); html.append("<tr><th align=\"right\">Updated:<th><td>").append(BasicFormatter.dateFormat.format(new Date())).append("</td></tr>"); if (event.serverStats.lastTickEnd >= 0) { html.append("<tr><th align=\"right\">Last Tick:<th><td>").append(timeSinceLastTick >= 1000 ? "Over " + (timeSinceLastTick / 1000) + " seconds" : timeSinceLastTick + "ms").append(" ago.</td></tr>"); } html.append("<tr><th align=\"right\">Average StatsAPI Thread Time:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.statsThreadTime.getAverage() * 1.0E-6D)).append(" ms</td></tr>"); html.append("<tr><th align=\"right\">Average StatsAPI Polled:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.statsThreadQueueCount.getAverage())).append("</td></tr>"); html.append("<tr><th align=\"right\">Average Tick Monitor Time:<th><td>"); if (statsActionTime.getTick() == 0) html.append("..."); else html.append(Util.DECIMAL_FORMAT_3.format(statsActionTime.getAverage() * 1.0E-6D)).append("ms (" + (int)(statsActionIOTime.getAverage() * 100 / statsActionTime.getAverage()) + "% IO)"); html.append("</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Tick Num:<th><td>").append(event.tickCounter); if (lastTickCounter >= 0) html.append(" (~").append(Util.DECIMAL_FORMAT_3.format(ticksPerSecond.getAverage() / 100D)).append("/sec)"); html.append("</td></tr>"); html.append("<tr><th align=\"right\">Average Full Tick:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.tickTime.getAverage() * 1.0E-6D)).append(" ms</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); double worldsTotal = 0; for (int i = 0; i < event.worldStats.length; i++) { worldsTotal += event.worldStats[i].worldTickTime.getAverage(); html.append("<tr><th align=\"right\">World ").append(i).append(" Averages:<th><td>") .append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].worldTickTime.getAverage() * 1.0E-6D) + "ms"); if (detailedMeasurementsEnabled) html.append(" (") .append("E: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].entities.getAverage() * 1.0E-6D)).append("ms") .append(" + M: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].mobSpawning.getAverage() * 1.0E-6D)).append("ms") .append(" + B: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].blockTick.getAverage() * 1.0E-6D)).append("ms") .append(" + W: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].weather.getAverage() * 1.0E-6D)).append("ms") .append(" + T: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].timeSync.getAverage() * 1.0E-6D)).append("ms") .append(" + CS: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].buildActiveChunkSet.getAverage() * 1.0E-6D)).append("ms") .append(" + L: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].checkPlayerLight.getAverage() * 1.0E-6D)).append("ms") .append(")"); html.append("</td></tr>"); html.append("<tr><th align=\"right\">&nbsp;<th><td>") .append("Chunks: ") .append((int)event.worldStats[i].loadedChunks.getLatest()).append(" loaded, ") .append(event.worldStats[i].id2ChunkMap).append(" cached, ") .append((int)event.worldStats[i].droppedChunksSet.getAverage()).append(" dropped"); if (detailedMeasurementsEnabled) html.append(" | ").append((int)event.worldStats[i].measurementQueue.getAverage()).append(" measurements per tick"); html.append("</td></tr>"); } html.append("<tr><th align=\"right\">Worlds Total:<th><td>").append(Util.DECIMAL_FORMAT_3.format(worldsTotal * 1.0E-6D)).append(" ms (" + (int)(worldsTotal / event.serverStats.tickTime.getAverage() * 100) + "% of full tick)</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Average Received Packet Count:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.receivedPacketCount.getAverage())).append("</td></tr>"); html.append("<tr><th align=\"right\">Average Sent Packet Count:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.sentPacketCount.getAverage())).append("</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Average Received Packet Size:<th><td>").append((int)event.serverStats.receivedPacketSize.getAverage()).append(" bytes</td></tr>"); html.append("<tr><th align=\"right\">Average Sent Packet Size:<th><td>").append((int)event.serverStats.sentPacketSize.getAverage()).append(" bytes</td></tr>"); html.append("</tbody></table>"); if (detailedMeasurementsEnabled) { for (int i = 0; i < event.worldStats.length; i++) { outputWorldDetails(event, html, i); } } html.append("</body></html>"); long startWriteTime = System.currentTimeMillis(); long startWriteNano = System.nanoTime(); try { FileWriter htmlWriter = new FileWriter(htmlFile); htmlWriter.write(html.toString()); htmlWriter.close(); } catch (Throwable e) { ModLoader.outputError(getName() + " failed to write to " + htmlFile.getPath() + ": " + e.getMessage()); } try { FileWriter jsonWriter = new FileWriter(jsonFile); jsonWriter.write(json); jsonWriter.close(); } catch (Throwable e) { ModLoader.outputError(getName() + " failed to write to " + jsonFile.getPath() + ": " + e.getMessage()); } long endNano = System.nanoTime(); long endTime = System.currentTimeMillis(); if (System.currentTimeMillis() - currentTime > tooLongWarningTime) ModLoader.outputError(getName() + " took " + (endTime - currentTime) + "ms (~" + ((endTime - startWriteTime) * 100 / (endTime - currentTime)) + "% disk IO) to process stats. Note: This will *not* slow the main Minecraft server thread."); statsActionTime.record(endNano - startNano); statsActionIOTime.record(endNano - startWriteNano); lastTickCounter = event.tickCounter; lastStatsTime = System.currentTimeMillis(); } }
public void statsAction(StatsEvent event) { long currentTime = System.currentTimeMillis(); long startNano = System.nanoTime(); boolean detailedMeasurementsEnabled = StatsAPI.detailedMeasurementsEnabled; if (lastStatsTime == 0) { lastStatsTime = System.currentTimeMillis(); } else if (currentTime - lastStatsTime > reportingDelay) { int numTicks = event.tickCounter - lastTickCounter; long timeElapsed = currentTime - lastStatsTime; long timeSinceLastTick = currentTime - event.serverStats.lastTickEnd; ticksPerSecond.record((long)((double)numTicks / (double)timeElapsed * 100000D)); long jsonTime = System.nanoTime(); JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("tickCounter", event.tickCounter); jsonObj.addProperty("timeSinceLastTick", timeSinceLastTick); jsonObj.addProperty("ticksSinceLastStatsAction", numTicks); jsonObj.addProperty("time", BasicFormatter.dateFormat.format(new Date(currentTime))); jsonObj.addProperty("detailedMeasurements", StatsAPI.detailedMeasurementsEnabled); jsonObj.add("statsActionTime", gson.toJsonTree(statsActionTime)); jsonObj.add("statsActionIOTime", gson.toJsonTree(statsActionIOTime)); jsonObj.add("ticksPerSecondArray", gson.toJsonTree(ticksPerSecond)); jsonObj.addProperty("jsonTime", "_____JSONTIME_____"); jsonObj.add("statsEvent", gson.toJsonTree(event)); String json = gson.toJson(jsonObj).replace("_____JSONTIME_____", Util.DECIMAL_FORMAT_3.format((jsonTime = System.nanoTime() - jsonTime) * 1.0E-6D)); // Debugging loop to ramp up CPU usage by the thread. //for (int i = 0; i < 20000; i++) new String(new char[10000]).replace('\0', 'a'); StringBuilder html = new StringBuilder("<html><head><title>Minecraft Server Stats</title><meta http-equiv=\"refresh\" content=\"2\"></head><body><h1>Minecraft Server Stats</h1>"); html.append("<table border=\"0\"><tbody>"); html.append("<tr><th align=\"right\">Updated:<th><td>").append(BasicFormatter.dateFormat.format(new Date())).append("</td></tr>"); if (event.serverStats.lastTickEnd >= 0) { html.append("<tr><th align=\"right\">Last Tick:<th><td>").append(timeSinceLastTick >= 1000 ? "Over " + (timeSinceLastTick / 1000) + " seconds" : timeSinceLastTick + "ms").append(" ago.</td></tr>"); } html.append("<tr><th align=\"right\">Average StatsAPI Thread Time:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.statsThreadTime.getAverage() * 1.0E-6D)).append(" ms</td></tr>"); html.append("<tr><th align=\"right\">Average StatsAPI Polled:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.statsThreadQueueCount.getAverage())).append("</td></tr>"); html.append("<tr><th align=\"right\">Average Tick Monitor Time:<th><td>"); if (statsActionTime.getTick() == 0) html.append("..."); else html.append(Util.DECIMAL_FORMAT_3.format(statsActionTime.getAverage() * 1.0E-6D)).append("ms (" + (int)(statsActionIOTime.getAverage() * 100 / statsActionTime.getAverage()) + "% IO)"); html.append("</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Tick Num:<th><td>").append(event.tickCounter); if (lastTickCounter >= 0) html.append(" (~").append(Util.DECIMAL_FORMAT_3.format(ticksPerSecond.getAverage() / 100D)).append("/sec)"); html.append("</td></tr>"); html.append("<tr><th align=\"right\">Average Full Tick:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.tickTime.getAverage() * 1.0E-6D)).append(" ms</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); double worldsTotal = 0; for (int i = 0; i < event.worldStats.length; i++) { worldsTotal += event.worldStats[i].worldTickTime.getAverage(); html.append("<tr><th align=\"right\">World ").append(i).append(" Averages:<th><td>") .append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].worldTickTime.getAverage() * 1.0E-6D) + "ms"); if (detailedMeasurementsEnabled) html.append(" (") .append("E: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].entities.getAverage() * 1.0E-6D)).append("ms") .append(" + M: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].mobSpawning.getAverage() * 1.0E-6D)).append("ms") .append(" + B: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].blockTick.getAverage() * 1.0E-6D)).append("ms") .append(" + W: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].weather.getAverage() * 1.0E-6D)).append("ms") .append(" + T: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].timeSync.getAverage() * 1.0E-6D)).append("ms") .append(" + CS: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].buildActiveChunkSet.getAverage() * 1.0E-6D)).append("ms") .append(" + L: ").append(Util.DECIMAL_FORMAT_3.format(event.worldStats[i].checkPlayerLight.getAverage() * 1.0E-6D)).append("ms") .append(")"); html.append("</td></tr>"); html.append("<tr><th align=\"right\">&nbsp;<th><td>") .append("Chunks: ") .append((int)event.worldStats[i].loadedChunks.getLatest()).append(" loaded, ") .append(event.worldStats[i].id2ChunkMap).append(" cached, ") .append((int)event.worldStats[i].droppedChunksSet.getAverage()).append(" dropped"); if (detailedMeasurementsEnabled) html.append(" | ").append((int)event.worldStats[i].measurementQueue.getAverage()).append(" measurements per tick"); html.append("</td></tr>"); } html.append("<tr><th align=\"right\">Worlds Total:<th><td>").append(Util.DECIMAL_FORMAT_3.format(worldsTotal * 1.0E-6D)).append(" ms (" + (int)(worldsTotal / event.serverStats.tickTime.getAverage() * 100) + "% of full tick)</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Average Received Packet Count:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.receivedPacketCount.getAverage())).append("</td></tr>"); html.append("<tr><th align=\"right\">Average Sent Packet Count:<th><td>").append(Util.DECIMAL_FORMAT_3.format(event.serverStats.sentPacketCount.getAverage())).append("</td></tr>"); html.append("<tr><td colspan=\"2\" style=\"height: 16px\"></td></tr>"); html.append("<tr><th align=\"right\">Average Received Packet Size:<th><td>").append((int)event.serverStats.receivedPacketSize.getAverage()).append(" bytes</td></tr>"); html.append("<tr><th align=\"right\">Average Sent Packet Size:<th><td>").append((int)event.serverStats.sentPacketSize.getAverage()).append(" bytes</td></tr>"); html.append("</tbody></table>"); if (detailedMeasurementsEnabled) { for (int i = 0; i < event.worldStats.length; i++) { outputWorldDetails(event, html, i); } } html.append("</body></html>"); long startWriteTime = System.currentTimeMillis(); long startWriteNano = System.nanoTime(); try { FileWriter htmlWriter = new FileWriter(htmlFile); htmlWriter.write(html.toString()); htmlWriter.close(); } catch (Throwable e) { ModLoader.outputError(getName() + " failed to write to " + htmlFile.getPath() + ": " + e.getMessage()); } try { FileWriter jsonWriter = new FileWriter(jsonFile); jsonWriter.write(json); jsonWriter.close(); } catch (Throwable e) { ModLoader.outputError(getName() + " failed to write to " + jsonFile.getPath() + ": " + e.getMessage()); } long endNano = System.nanoTime(); long endTime = System.currentTimeMillis(); if (System.currentTimeMillis() - currentTime > tooLongWarningTime) ModLoader.outputError(getName() + " took " + (endTime - currentTime) + "ms (~" + ((endTime - startWriteTime) * 100 / (endTime - currentTime)) + "% disk IO) to process stats. Note: This will *not* slow the main Minecraft server thread."); statsActionTime.record(endNano - startNano); statsActionIOTime.record(endNano - startWriteNano); lastTickCounter = event.tickCounter; lastStatsTime = System.currentTimeMillis(); } }
diff --git a/src/org/opensolaris/opengrok/history/MercurialRepository.java b/src/org/opensolaris/opengrok/history/MercurialRepository.java index 4744c5f6..8c273c22 100644 --- a/src/org/opensolaris/opengrok/history/MercurialRepository.java +++ b/src/org/opensolaris/opengrok/history/MercurialRepository.java @@ -1,342 +1,342 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved. */ package org.opensolaris.opengrok.history; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.opensolaris.opengrok.OpenGrokLogger; import org.opensolaris.opengrok.util.Executor; import org.opensolaris.opengrok.util.IOUtils; import org.opensolaris.opengrok.web.Util; /** * Access to a Mercurial repository. * */ public class MercurialRepository extends Repository { private static final long serialVersionUID = 1L; /** The property name used to obtain the client command for thisrepository. */ public static final String CMD_PROPERTY_KEY = "org.opensolaris.opengrok.history.Mercurial"; /** The command to use to access the repository if none was given explicitly */ public static final String CMD_FALLBACK = "hg"; /** The boolean property and environment variable name to indicate * whether forest-extension in Mercurial adds repositories inside the * repositories. */ public static final String NOFOREST_PROPERTY_KEY = "org.opensolaris.opengrok.history.mercurial.disableForest"; /** Template for formatting hg log output for files. */ private static final String TEMPLATE = "changeset: {rev}:{node|short}\\n" + "{branches}{tags}{parents}\\n" + "user: {author}\\ndate: {date|isodate}\\n" + "description: {desc|strip|obfuscate}\\n"; /** Template for formatting hg log output for directories. */ private static final String DIR_TEMPLATE = TEMPLATE + "files: {files}{file_copies}\\n"; public MercurialRepository() { type = "Mercurial"; datePattern = "yyyy-MM-dd hh:mm ZZZZ"; } /** * Get an executor to be used for retrieving the history log for the * named file. * * @param file The file to retrieve history for * @param changeset the oldest changeset to return from the executor, * or {@code null} if all changesets should be returned * @return An Executor ready to be started */ Executor getHistoryLogExecutor(File file, String changeset) throws HistoryException, IOException { String abs = file.getCanonicalPath(); String filename = ""; if (abs.length() > directoryName.length()) { filename = abs.substring(directoryName.length() + 1); } List<String> cmd = new ArrayList<String>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); cmd.add(this.cmd); cmd.add("log"); if ( !file.isDirectory() ) { cmd.add("-f"); } if (changeset != null) { cmd.add("-r"); String[] parts = changeset.split(":"); if (parts.length == 2) { cmd.add("tip:" + parts[0]); } else { throw new HistoryException( "Don't know how to parse changeset identifier: " + changeset); } } cmd.add("--template"); cmd.add(file.isDirectory() ? DIR_TEMPLATE : TEMPLATE); cmd.add(filename); return new Executor(cmd, new File(directoryName)); } @Override public InputStream getHistoryGet(String parent, String basename, String rev) { InputStream ret = null; File directory = new File(directoryName); Process process = null; InputStream in = null; String revision = rev; if (rev.indexOf(':') != -1) { revision = rev.substring(0, rev.indexOf(':')); } try { String filename = (new File(parent, basename)).getCanonicalPath() .substring(directoryName.length() + 1); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); String argv[] = {cmd, "cat", "-r", revision, filename}; process = Runtime.getRuntime().exec(argv, null, directory); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[32 * 1024]; in = process.getInputStream(); int len; while ((len = in.read(buffer)) != -1) { if (len > 0) { out.write(buffer, 0, len); } } ret = new ByteArrayInputStream(out.toByteArray()); } catch (Exception exp) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString()); } finally { IOUtils.close(in); // Clean up zombie-processes... if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException exp) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; } /** Pattern used to extract author/revision from hg annotate. */ private static final Pattern ANNOTATION_PATTERN = Pattern.compile("^\\s*(\\d+):"); /** * Annotate the specified file/revision. * * @param file file to annotate * @param revision revision to annotate * @return file annotation */ @Override public Annotation annotate(File file, String revision) throws IOException { ArrayList<String> argv = new ArrayList<String>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(cmd); argv.add("annotate"); argv.add("-n"); if (revision != null) { argv.add("-r"); if (revision.indexOf(':') == -1) { argv.add(revision); } else { argv.add(revision.substring(0, revision.indexOf(':'))); } } argv.add(file.getName()); ProcessBuilder pb = new ProcessBuilder(argv); pb.directory(file.getParentFile()); Process process = null; BufferedReader in = null; Annotation ret = null; HashMap<String,HistoryEntry> revs = new HashMap<String,HistoryEntry>(); // Construct hash map for history entries from history cache. This is // needed later to get user string for particular revision. - try { + try { History hist = HistoryGuru.getInstance().getHistory(file, false); for (HistoryEntry e : hist.getHistoryEntries()) { // Chop out the colon and all hexadecimal what follows. // This is because the whole changeset identification is // stored in history index while annotate only needs the // revision identifier. revs.put(e.getRevision().replaceFirst(":[a-f0-9]+", ""), e); } } catch (HistoryException he) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error: cannot get history for file " + file); return null; } try { process = pb.start(); in = new BufferedReader(new InputStreamReader(process.getInputStream())); ret = new Annotation(file.getName()); String line; int lineno = 0; Matcher matcher = ANNOTATION_PATTERN.matcher(""); while ((line = in.readLine()) != null) { ++lineno; matcher.reset(line); if (matcher.find()) { String rev = matcher.group(1); String author = "N/A"; // Use the history index hash map to get the author. if (revs.get(rev) != null) { author = revs.get(rev).getAuthor(); } ret.addLine(rev, Util.getEmail(author.trim()), true); } else { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error: did not find annotation in line " + lineno + ": [" + line + "]"); } } } finally { IOUtils.close(in); if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; } @Override public boolean fileHasAnnotation(File file) { return true; } @Override public void update() throws IOException { File directory = new File(directoryName); List<String> cmd = new ArrayList<String>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); cmd.add(this.cmd); cmd.add("showconfig"); Executor executor = new Executor(cmd, directory); if (executor.exec() != 0) { throw new IOException(executor.getErrorString()); } if (executor.getOutputString().indexOf("paths.default=") != -1) { cmd.clear(); cmd.add(this.cmd); cmd.add("pull"); cmd.add("-u"); executor = new Executor(cmd, directory); if (executor.exec() != 0) { throw new IOException(executor.getErrorString()); } } } @Override public boolean fileHasHistory(File file) { // Todo: is there a cheap test for whether mercurial has history // available for a file? // Otherwise, this is harmless, since mercurial's commands will just // print nothing if there is no history. return true; } @Override boolean isRepositoryFor(File file) { if (file.isDirectory()) { File f = new File(file, ".hg"); return f.exists() && f.isDirectory(); } return false; } @Override boolean supportsSubRepositories() { String val = System.getenv(NOFOREST_PROPERTY_KEY); return !(val == null ? Boolean.getBoolean(NOFOREST_PROPERTY_KEY) : Boolean.parseBoolean(val)); } @Override public boolean isWorking() { if (working == null) { ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); working = checkCmd(cmd); } return working.booleanValue(); } @Override boolean hasHistoryForDirectories() { return true; } @Override History getHistory(File file) throws HistoryException { return getHistory(file, null); } @Override History getHistory(File file, String sinceRevision) throws HistoryException { return new MercurialHistoryParser(this).parse(file, sinceRevision); } }
true
true
public Annotation annotate(File file, String revision) throws IOException { ArrayList<String> argv = new ArrayList<String>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(cmd); argv.add("annotate"); argv.add("-n"); if (revision != null) { argv.add("-r"); if (revision.indexOf(':') == -1) { argv.add(revision); } else { argv.add(revision.substring(0, revision.indexOf(':'))); } } argv.add(file.getName()); ProcessBuilder pb = new ProcessBuilder(argv); pb.directory(file.getParentFile()); Process process = null; BufferedReader in = null; Annotation ret = null; HashMap<String,HistoryEntry> revs = new HashMap<String,HistoryEntry>(); // Construct hash map for history entries from history cache. This is // needed later to get user string for particular revision. try { History hist = HistoryGuru.getInstance().getHistory(file, false); for (HistoryEntry e : hist.getHistoryEntries()) { // Chop out the colon and all hexadecimal what follows. // This is because the whole changeset identification is // stored in history index while annotate only needs the // revision identifier. revs.put(e.getRevision().replaceFirst(":[a-f0-9]+", ""), e); } } catch (HistoryException he) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error: cannot get history for file " + file); return null; } try { process = pb.start(); in = new BufferedReader(new InputStreamReader(process.getInputStream())); ret = new Annotation(file.getName()); String line; int lineno = 0; Matcher matcher = ANNOTATION_PATTERN.matcher(""); while ((line = in.readLine()) != null) { ++lineno; matcher.reset(line); if (matcher.find()) { String rev = matcher.group(1); String author = "N/A"; // Use the history index hash map to get the author. if (revs.get(rev) != null) { author = revs.get(rev).getAuthor(); } ret.addLine(rev, Util.getEmail(author.trim()), true); } else { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error: did not find annotation in line " + lineno + ": [" + line + "]"); } } } finally { IOUtils.close(in); if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; }
public Annotation annotate(File file, String revision) throws IOException { ArrayList<String> argv = new ArrayList<String>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(cmd); argv.add("annotate"); argv.add("-n"); if (revision != null) { argv.add("-r"); if (revision.indexOf(':') == -1) { argv.add(revision); } else { argv.add(revision.substring(0, revision.indexOf(':'))); } } argv.add(file.getName()); ProcessBuilder pb = new ProcessBuilder(argv); pb.directory(file.getParentFile()); Process process = null; BufferedReader in = null; Annotation ret = null; HashMap<String,HistoryEntry> revs = new HashMap<String,HistoryEntry>(); // Construct hash map for history entries from history cache. This is // needed later to get user string for particular revision. try { History hist = HistoryGuru.getInstance().getHistory(file, false); for (HistoryEntry e : hist.getHistoryEntries()) { // Chop out the colon and all hexadecimal what follows. // This is because the whole changeset identification is // stored in history index while annotate only needs the // revision identifier. revs.put(e.getRevision().replaceFirst(":[a-f0-9]+", ""), e); } } catch (HistoryException he) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error: cannot get history for file " + file); return null; } try { process = pb.start(); in = new BufferedReader(new InputStreamReader(process.getInputStream())); ret = new Annotation(file.getName()); String line; int lineno = 0; Matcher matcher = ANNOTATION_PATTERN.matcher(""); while ((line = in.readLine()) != null) { ++lineno; matcher.reset(line); if (matcher.find()) { String rev = matcher.group(1); String author = "N/A"; // Use the history index hash map to get the author. if (revs.get(rev) != null) { author = revs.get(rev).getAuthor(); } ret.addLine(rev, Util.getEmail(author.trim()), true); } else { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error: did not find annotation in line " + lineno + ": [" + line + "]"); } } } finally { IOUtils.close(in); if (process != null) { try { process.exitValue(); } catch (IllegalThreadStateException e) { // the process is still running??? just kill it.. process.destroy(); } } } return ret; }
diff --git a/src/net/amunak/bukkit/plugin_DropsToInventory/BlockBreakEventListener.java b/src/net/amunak/bukkit/plugin_DropsToInventory/BlockBreakEventListener.java index dad0d58..556eece 100644 --- a/src/net/amunak/bukkit/plugin_DropsToInventory/BlockBreakEventListener.java +++ b/src/net/amunak/bukkit/plugin_DropsToInventory/BlockBreakEventListener.java @@ -1,211 +1,212 @@ package net.amunak.bukkit.plugin_DropsToInventory; /** * Copyright 2013 Jiří Barouš * * 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/>. */ import java.util.ArrayList; import java.util.List; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.ItemStack; /** * block break event listener * * @author Amunak */ public final class BlockBreakEventListener implements Listener { protected static Log log; public List<String> blockFilter; public List<String> safeBlocks; private List<Material> durabilityFixAppliedItems = new ArrayList<Material>(); private List<Material> durabilityFixSwords = new ArrayList<Material>(); public DropsToInventory plugin; public Integer filterMode; public Boolean useSafeBlocks; public Boolean fixEnchantmentBug; public Boolean fixItemDurability; public BlockBreakEventListener(DropsToInventory p) { plugin = p; log = new Log(plugin); log.raiseFineLevel = plugin.config.getBoolean("options.general.verboseLogging"); log.fine("registering BlockBreakEventListener"); filterMode = BlockFilter.fromString(plugin.config.getString("options.blocks.filterMode")); useSafeBlocks = plugin.config.getBoolean("options.blocks.useOnlySafeBlocks"); fixEnchantmentBug = !plugin.config.getBoolean("options.blocks.ignoreEnchantmentBug"); fixItemDurability = plugin.config.getBoolean("options.blocks.fixItemDurability"); if (!filterMode.equals(BlockFilter.NONE)) { blockFilter = plugin.config.getStringList("lists.blockFilter"); + Common.fixEnumLists(blockFilter); } if (useSafeBlocks) { safeBlocks = plugin.config.getStringList("lists.safeBlocks"); - } - Common.fixEnumLists(blockFilter, safeBlocks); + Common.fixEnumLists(safeBlocks); + } if (fixItemDurability) { log.fine("we will try to fix item durability bug"); durabilityFixAppliedItems.add(Material.WOOD_SWORD); durabilityFixAppliedItems.add(Material.WOOD_PICKAXE); durabilityFixAppliedItems.add(Material.WOOD_AXE); durabilityFixAppliedItems.add(Material.WOOD_SPADE); durabilityFixAppliedItems.add(Material.STONE_SWORD); durabilityFixAppliedItems.add(Material.STONE_PICKAXE); durabilityFixAppliedItems.add(Material.STONE_AXE); durabilityFixAppliedItems.add(Material.STONE_SPADE); durabilityFixAppliedItems.add(Material.IRON_SWORD); durabilityFixAppliedItems.add(Material.IRON_PICKAXE); durabilityFixAppliedItems.add(Material.IRON_AXE); durabilityFixAppliedItems.add(Material.IRON_SPADE); durabilityFixAppliedItems.add(Material.GOLD_SWORD); durabilityFixAppliedItems.add(Material.GOLD_PICKAXE); durabilityFixAppliedItems.add(Material.GOLD_AXE); durabilityFixAppliedItems.add(Material.GOLD_SPADE); durabilityFixAppliedItems.add(Material.DIAMOND_SWORD); durabilityFixAppliedItems.add(Material.DIAMOND_PICKAXE); durabilityFixAppliedItems.add(Material.DIAMOND_AXE); durabilityFixAppliedItems.add(Material.DIAMOND_SPADE); durabilityFixSwords.add(Material.WOOD_SWORD); durabilityFixSwords.add(Material.STONE_SWORD); durabilityFixSwords.add(Material.IRON_SWORD); durabilityFixSwords.add(Material.GOLD_SWORD); durabilityFixSwords.add(Material.DIAMOND_SWORD); } log.fine("BlockBreakEventListener registered"); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onBlockBreakEvent(BlockBreakEvent event) { log.fine(event.getPlayer().getName() + " broke " + event.getBlock().getType()); if (event.getPlayer().getGameMode().equals(GameMode.SURVIVAL) && (!useSafeBlocks || safeBlocks.contains(event.getBlock().getType().toString())) && (!fixEnchantmentBug || !enchantBugPresent(event)) && (BlockFilter.isEligible(event.getBlock().getType(), blockFilter, filterMode))) { log.fine("dropping " + event.getBlock().getType() + " to inventory of " + event.getPlayer().getName()); plugin.moveDropToInventory(event.getPlayer(), event.getBlock().getDrops(event.getPlayer().getItemInHand()), event.getExpToDrop(), event.getBlock().getLocation()); /* event.getBlock().getDrops().clear(); //bugged * event.setExpToDrop(0); */ event.setCancelled(true); event.getBlock().setTypeId(Material.AIR.getId()); recalculateDurability(event.getPlayer().getItemInHand()); } } private boolean enchantBugPresent(BlockBreakEvent event) { List<Enchantment> buggedEnchants = new ArrayList<Enchantment>(); buggedEnchants.add(Enchantment.LOOT_BONUS_BLOCKS); buggedEnchants.add(Enchantment.SILK_TOUCH); for (Enchantment enchantment : buggedEnchants) { if (event.getPlayer().getInventory().getItemInHand().getEnchantmentLevel(enchantment) > 0) { log.fine(event.getPlayer().getName() + " has enchant bug present"); return true; } } return false; } /** * Changes durability as if the block was broken normally. Durability * enchant is applied if necessary. This works only for BLOCK BREAKS with * SWORDS, PICKAXES, AXES AND SHOVELS! * * @param item the item durability is counter on */ private void recalculateDurability(ItemStack item) { Integer enchantLevel = item.getEnchantmentLevel(Enchantment.DURABILITY); if (fixItemDurability && durabilityFixAppliedItems.contains(item.getType()) //counting with durability enchant: && (enchantLevel == 0 || (plugin.random.nextInt(100) <= 100 / (enchantLevel + 1)))) { log.fine("trying to fix durability on " + item.getType() + " with durability enchant " + enchantLevel); if (durabilityFixSwords.contains(item.getType())) { item.setDurability((short) (item.getDurability() + 2)); } else { item.setDurability((short) (item.getDurability() + 1)); } } } /** * Holds filter modes and methods to retreive them */ private static class BlockFilter { public static final Integer NONE = 0; public static final Integer BLACKLIST = 1; public static final Integer WHITELIST = 2; public static String toString(Integer i) { if (i.equals(BLACKLIST)) { return "BLACKLIST"; } else if (i.equals(WHITELIST)) { return "WHITELIST"; } else { return "NONE"; } } public static Integer fromString(String s) { if (s.equalsIgnoreCase("BLACKLIST")) { return BLACKLIST; } else if (s.equalsIgnoreCase("WHITELIST")) { return WHITELIST; } else { return NONE; } } /** * checks whether a block is eligible to be used according to a filter * mode * * @param isInList is block in list * @param mode filter mode to check against * @return true if elegible, else otherwise */ public static Boolean isEligible(boolean isInList, Integer mode) { boolean result; result = mode.equals(NONE) || (mode.equals(BLACKLIST) && !isInList) || (mode.equals(WHITELIST) && isInList); log.fine("block is eligible: " + result); return result; } /** * checks a block material against list and if it is eligible to be used * according to a filter mode * * @param mat the material * @param list list of materials (strings) * @param mode filter mode to check against * @return */ public static Boolean isEligible(Material mat, List list, Integer mode) { return isEligible(list.contains(mat.toString()), mode); } } }
false
true
public BlockBreakEventListener(DropsToInventory p) { plugin = p; log = new Log(plugin); log.raiseFineLevel = plugin.config.getBoolean("options.general.verboseLogging"); log.fine("registering BlockBreakEventListener"); filterMode = BlockFilter.fromString(plugin.config.getString("options.blocks.filterMode")); useSafeBlocks = plugin.config.getBoolean("options.blocks.useOnlySafeBlocks"); fixEnchantmentBug = !plugin.config.getBoolean("options.blocks.ignoreEnchantmentBug"); fixItemDurability = plugin.config.getBoolean("options.blocks.fixItemDurability"); if (!filterMode.equals(BlockFilter.NONE)) { blockFilter = plugin.config.getStringList("lists.blockFilter"); } if (useSafeBlocks) { safeBlocks = plugin.config.getStringList("lists.safeBlocks"); } Common.fixEnumLists(blockFilter, safeBlocks); if (fixItemDurability) { log.fine("we will try to fix item durability bug"); durabilityFixAppliedItems.add(Material.WOOD_SWORD); durabilityFixAppliedItems.add(Material.WOOD_PICKAXE); durabilityFixAppliedItems.add(Material.WOOD_AXE); durabilityFixAppliedItems.add(Material.WOOD_SPADE); durabilityFixAppliedItems.add(Material.STONE_SWORD); durabilityFixAppliedItems.add(Material.STONE_PICKAXE); durabilityFixAppliedItems.add(Material.STONE_AXE); durabilityFixAppliedItems.add(Material.STONE_SPADE); durabilityFixAppliedItems.add(Material.IRON_SWORD); durabilityFixAppliedItems.add(Material.IRON_PICKAXE); durabilityFixAppliedItems.add(Material.IRON_AXE); durabilityFixAppliedItems.add(Material.IRON_SPADE); durabilityFixAppliedItems.add(Material.GOLD_SWORD); durabilityFixAppliedItems.add(Material.GOLD_PICKAXE); durabilityFixAppliedItems.add(Material.GOLD_AXE); durabilityFixAppliedItems.add(Material.GOLD_SPADE); durabilityFixAppliedItems.add(Material.DIAMOND_SWORD); durabilityFixAppliedItems.add(Material.DIAMOND_PICKAXE); durabilityFixAppliedItems.add(Material.DIAMOND_AXE); durabilityFixAppliedItems.add(Material.DIAMOND_SPADE); durabilityFixSwords.add(Material.WOOD_SWORD); durabilityFixSwords.add(Material.STONE_SWORD); durabilityFixSwords.add(Material.IRON_SWORD); durabilityFixSwords.add(Material.GOLD_SWORD); durabilityFixSwords.add(Material.DIAMOND_SWORD); } log.fine("BlockBreakEventListener registered"); }
public BlockBreakEventListener(DropsToInventory p) { plugin = p; log = new Log(plugin); log.raiseFineLevel = plugin.config.getBoolean("options.general.verboseLogging"); log.fine("registering BlockBreakEventListener"); filterMode = BlockFilter.fromString(plugin.config.getString("options.blocks.filterMode")); useSafeBlocks = plugin.config.getBoolean("options.blocks.useOnlySafeBlocks"); fixEnchantmentBug = !plugin.config.getBoolean("options.blocks.ignoreEnchantmentBug"); fixItemDurability = plugin.config.getBoolean("options.blocks.fixItemDurability"); if (!filterMode.equals(BlockFilter.NONE)) { blockFilter = plugin.config.getStringList("lists.blockFilter"); Common.fixEnumLists(blockFilter); } if (useSafeBlocks) { safeBlocks = plugin.config.getStringList("lists.safeBlocks"); Common.fixEnumLists(safeBlocks); } if (fixItemDurability) { log.fine("we will try to fix item durability bug"); durabilityFixAppliedItems.add(Material.WOOD_SWORD); durabilityFixAppliedItems.add(Material.WOOD_PICKAXE); durabilityFixAppliedItems.add(Material.WOOD_AXE); durabilityFixAppliedItems.add(Material.WOOD_SPADE); durabilityFixAppliedItems.add(Material.STONE_SWORD); durabilityFixAppliedItems.add(Material.STONE_PICKAXE); durabilityFixAppliedItems.add(Material.STONE_AXE); durabilityFixAppliedItems.add(Material.STONE_SPADE); durabilityFixAppliedItems.add(Material.IRON_SWORD); durabilityFixAppliedItems.add(Material.IRON_PICKAXE); durabilityFixAppliedItems.add(Material.IRON_AXE); durabilityFixAppliedItems.add(Material.IRON_SPADE); durabilityFixAppliedItems.add(Material.GOLD_SWORD); durabilityFixAppliedItems.add(Material.GOLD_PICKAXE); durabilityFixAppliedItems.add(Material.GOLD_AXE); durabilityFixAppliedItems.add(Material.GOLD_SPADE); durabilityFixAppliedItems.add(Material.DIAMOND_SWORD); durabilityFixAppliedItems.add(Material.DIAMOND_PICKAXE); durabilityFixAppliedItems.add(Material.DIAMOND_AXE); durabilityFixAppliedItems.add(Material.DIAMOND_SPADE); durabilityFixSwords.add(Material.WOOD_SWORD); durabilityFixSwords.add(Material.STONE_SWORD); durabilityFixSwords.add(Material.IRON_SWORD); durabilityFixSwords.add(Material.GOLD_SWORD); durabilityFixSwords.add(Material.DIAMOND_SWORD); } log.fine("BlockBreakEventListener registered"); }
diff --git a/ttools/src/main/uk/ac/starlink/ttools/plot/Plot3D.java b/ttools/src/main/uk/ac/starlink/ttools/plot/Plot3D.java index f886409d6..9b2736a01 100644 --- a/ttools/src/main/uk/ac/starlink/ttools/plot/Plot3D.java +++ b/ttools/src/main/uk/ac/starlink/ttools/plot/Plot3D.java @@ -1,778 +1,781 @@ package uk.ac.starlink.ttools.plot; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.util.Arrays; import java.util.BitSet; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JComponent; /** * Component which paints a 3d plot. * * @author Mark Taylor * @since 22 Nov 2005 */ public abstract class Plot3D extends TablePlot { private RangeChecker rangeChecker_; private PlotVolume lastVol_; private Transformer3D lastTrans_; private int plotTime_; private Object plotvolWorkspace_; private int[] padBorders_; private double zmax_; private final JComponent plotArea_; protected double[] loBounds_; protected double[] hiBounds_; protected double[] loBoundsG_; protected double[] hiBoundsG_; private static final MarkStyle DOT_STYLE = MarkShape.POINT.getStyle( Color.BLACK, 1 ); private static final Logger logger_ = Logger.getLogger( "uk.ac.starlink.ttools.plot" ); /** * Constructor. */ public Plot3D() { setLayout( new BorderLayout() ); plotArea_ = new Plot3DDataPanel(); plotArea_.setBackground( Color.white ); plotArea_.setOpaque( true ); plotArea_.setPreferredSize( new Dimension( 450, 450 ) ); plotArea_.setBorder( BorderFactory .createLineBorder( Color.DARK_GRAY ) ); add( plotArea_, BorderLayout.CENTER ); setOpaque( false ); } /** * Provides notification that the range constraints are now as described * in a supplied <code>state</code> object. * A suitable {@link RangeChecker} object should be returned, * but the implementation should take care of any other updates to * its internal state which are required as well. * * @param state plot state * @return a range checker appropriate to <code>state</code>'s range * constraints */ protected abstract RangeChecker configureRanges( Plot3DState state ); /** * Works out padding factors to be used for the plot volume. * The return value is the <code>padFactor</code>; the amount of * space outside the unit cube in both dimensions. 1 means no * extra space. The <code>padBorders</code> array is a 4-element * array whose values on entry are ignored; on exit it should contain * space, additional to <code>padFactor</code>, to be left around * the edges of the plot. The order is (left,right,bottom,top). * * @param state plot state * @param g graphics context * @param padBorders 4-element array, filled on return * @return pad factor (>=1) * @see PlotVolume#PlotVolume */ protected abstract double getPadding( Plot3DState state, Graphics g, int[] padBorders ); /** * Indicates whether only the front part of the plot should be plotted. * * @param state plot state * @return true iff parts of the plot behind the centre of the Z axis * should be ignored */ protected abstract boolean frontOnly( Plot3DState state ); /** * Returns an array of 3 flags which indicate whether logarithmic scaling * is in force on the X, Y and Z axes respectively. * * @return 3-element array of Cartesian axis log scaling flags */ protected abstract boolean[] get3DLogFlags(); /** * Draws grid lines which contain all the known points. * According to the value of the <code>front</code> parameter, * either the lines which are behind all the data points, * or the lines which are in front of all the data points are drawn. * Thus, the routine needs to be called twice to plot all the lines. * The graphics context has had all the customisation it needs. * * @param state plot state * @param g graphics context * @param trans transformer which maps data space to 3d graphics space * @param vol the plotting volume onto which the plot is done * @param front true for lines in front of data, false for lines behind */ protected abstract void plotAxes( Plot3DState state, Graphics g, Transformer3D trans, PlotVolume vol, boolean front ); public void setState( PlotState state ) { super.setState( state ); lastVol_ = null; lastTrans_ = null; /* Adjust internal state according to requested ranges. */ if ( state.getValid() ) { rangeChecker_ = configureRanges( (Plot3DState) state ); } } /** * Returns the bounds of the actual plotting area. * * @return plot area bounds */ public Rectangle getPlotBounds() { return plotArea_.getBounds(); } /** * Returns the bounds of the apparent display area. * This is the actual plotting area with some padding. * * @return display area bounds */ public Rectangle getDisplayBounds() { Rectangle display = new Rectangle( getPlotBounds() ); display.x += padBorders_[ 0 ]; display.y += padBorders_[ 3 ]; display.width -= padBorders_[ 0 ] + padBorders_[ 1 ]; display.height -= padBorders_[ 2 ] + padBorders_[ 3 ]; return display; } /** * Performs the painting - this method does the actual work. */ private void drawData( Graphics g, Component c ) { /* Prepare data. */ Plot3DState state = (Plot3DState) getState(); + if ( state == null || ! state.getValid() ) { + return; + } PlotData data = state.getPlotData(); - if ( data == null || state == null || ! state.getValid() ) { + if ( data == null ) { return; } int nset = data.getSetCount(); /* Set up a transformer to do the mapping from data space to * normalised 3-d view space. */ Transformer3D trans = new Transformer3D( state.getRotation(), loBoundsG_, hiBoundsG_, state.getZoomScale() ); /* Work out padding factors for the plot volume. */ padBorders_ = new int[ 4 ]; double padFactor = getPadding( state, g, padBorders_ ); /* Prepare an array of styles which we may need to plot on the * PlotVolume object. */ MarkStyle[] styles = new MarkStyle[ nset + 1 ]; for ( int is = 0; is < nset; is++ ) { styles[ is ] = (MarkStyle) data.getSetStyle( is ); } styles[ nset ] = DOT_STYLE; int iDotStyle = nset; /* See if all the markers are opaque; if they are we can use a * simpler rendering algorithm. */ boolean allOpaque = true; for ( int is = 0; is < nset && allOpaque; is++ ) { allOpaque = allOpaque && styles[ is ].getOpaqueLimit() == 1; } Shader[] shaders = state.getShaders(); for ( int iaux = 0; iaux < shaders.length; iaux++ ) { Shader shader = shaders[ iaux ]; allOpaque = allOpaque && ! Shaders.isTransparent( shaders[ iaux ] ); } /* See if there are any error bars to be plotted. If not, we can * use more efficient rendering machinery. */ boolean anyErrors = false; for ( int is = 0; is < nset && ! anyErrors; is++ ) { anyErrors = anyErrors || MarkStyle.hasErrors( (MarkStyle) styles[ is ], data ); } /* See if there may be labels to draw. */ boolean hasLabels = data.hasLabels(); /* Get fogginess. */ double fog = state.getFogginess(); /* Work out how points will be shaded according to auxiliary axis * coordinates. This does not include the effect of fogging, * which will be handled separately. */ DataColorTweaker tweaker = ShaderTweaker.createTweaker( 3, state ); /* Decide what rendering algorithm we're going to have to use, and * create a PlotVolume object accordingly. */ PlotVolume vol; if ( isVectorContext( g ) ) { if ( ! allOpaque ) { logger_.warning( "Can't render transparency in PostScript" ); } vol = new VectorSortPlotVolume( c, g, styles, padFactor, padBorders_, fog, tweaker ); } else if ( allOpaque ) { vol = new ZBufferPlotVolume( c, g, styles, padFactor, padBorders_, fog, hasLabels, tweaker, getZBufferWorkspace() ); } else { vol = new BitmapSortPlotVolume( c, g, styles, padFactor, padBorders_, fog, hasLabels, anyErrors, -1.0, 2.0, tweaker, getBitmapSortWorkspace() ); } logger_.config( "PlotVolume class is: " + vol.getClass().getName() ); /* If we're zoomed on a spherical plot and the points are only * on the surface of the sphere, then we don't want to see the * points on the far surface. */ boolean frontOnly = frontOnly( state ); /* Plot back part of bounding box. */ boolean grid = state.getGrid(); if ( grid && ! frontOnly ) { plotAxes( g, trans, vol, false ); } /* Work out which sets have markers and which sets have error bars * drawn. */ boolean[] showPoints = new boolean[ nset ]; boolean[] showErrors = new boolean[ nset ]; for ( int is = 0; is < nset; is++ ) { MarkStyle style = (MarkStyle) styles[ is ]; showPoints[ is ] = ! style.getHidePoints(); showErrors[ is ] = MarkStyle.hasErrors( style, data ); } /* Start the stopwatch to time how long it takes to plot all points. */ long tStart = System.currentTimeMillis(); /* If this is an intermediate plot (during a rotation, with a * guaranteed non-intermediate one to follow shortly), then prepare * to plot only a fraction of the points. In this way we can * ensure reasonable responsiveness - dragging the plot to rotate * it will not take ages between frames. */ boolean isRotating = state.getRotating(); int step = isRotating ? Math.max( plotTime_ / 100, 1 ) : 1; /* If we're only looking at the front surface of a sphere and we're * zoomed we can arrange a limit on the Z coordinate to filter points. * This is partly optimisation (not plotting points that aren't * seen because they are off screen laterally) and partly so we * don't see points on the far surface (zmax=0.5). * By my quick trig the limit for optimisation ought to be * Math.sqrt(0.5)*(1-Math.sqrt(1-0.25/(zoom*zoom)), * but that gives a region that's too small so I must have gone wrong. * There's something about aspect ratio to take into account too. * So, leave it as 0.5 for now, which is correct but not optimal. */ zmax_ = frontOnly ? 0.5 : Double.MAX_VALUE; /* Submit each point for drawing in the display volume as * appropriate. */ int nInclude = 0; int nVisible = 0; boolean[] logFlags = get3DLogFlags(); boolean[] showMarkPoints = new boolean[ nset ]; boolean[] showMarkErrors = new boolean[ nset ]; double[] centre = new double[ 3 ]; int nerr = data.getNerror(); double[] xerrs = new double[ nerr ]; double[] yerrs = new double[ nerr ]; double[] zerrs = new double[ nerr ]; RangeChecker ranger = rangeChecker_; int ip = 0; PointSequence pseq = data.getPointSequence(); while ( pseq.next() ) { boolean use = false; boolean useErrors = false; int labelSet = -1; for ( int is = 0; is < nset; is++ ) { boolean included = pseq.isIncluded( is ); use = use || included; boolean showP = included && showPoints[ is ]; boolean showE = included && showErrors[ is ]; useErrors = useErrors || showE; showMarkPoints[ is ] = showP; showMarkErrors[ is ] = showE; if ( included && hasLabels ) { labelSet = is; } } if ( use ) { nInclude++; double[] coords = pseq.getPoint(); centre[ 0 ] = coords[ 0 ]; centre[ 1 ] = coords[ 1 ]; centre[ 2 ] = coords[ 2 ]; if ( ranger.inRange( coords ) && logize( coords, logFlags ) ) { trans.transform( coords ); if ( coords[ 2 ] < zmax_ ) { if ( useErrors ) { double[][] errors = pseq.getErrors(); useErrors = useErrors && transformErrors( trans, ranger, logFlags, errors, xerrs, yerrs, zerrs ); } boolean vis = false; for ( int is = 0; is < nset; is++ ) { int numErr = useErrors && showMarkErrors[ is ] ? nerr : 0; String label; if ( is == labelSet ) { label = pseq.getLabel(); if ( label != null && label.trim().length() == 0 ) { label = null; } } else { label = null; } boolean plotted = vol.plot3d( coords, is, showMarkPoints[ is ], label, numErr, xerrs, yerrs, zerrs ); vis = vis || plotted; } if ( vis ) { nVisible++; } } } } while ( ( ++ip % step ) != 0 && pseq.next() ); } pseq.close(); int nPoint = ip; /* Plot a teeny static dot in the middle of the data. */ double[] dot = new double[ data.getNdim() ]; dot[ 0 ] = 0.5; dot[ 1 ] = 0.5; dot[ 2 ] = 0.5; vol.plot3d( dot, iDotStyle, true, null, 0, null, null, null ); /* Tell the volume that all the points are in for plotting. * This will do the painting on the graphics context if it hasn't * been done already. */ vol.flush(); /* Calculate time to plot all points. */ if ( ! isRotating ) { plotTime_ = (int) ( System.currentTimeMillis() - tStart ); } /* Plot front part of bounding box. */ if ( grid ) { plotAxes( g, trans, vol, true ); } /* Store information about the most recent plot. */ lastVol_ = vol; lastTrans_ = trans; firePlotChangedLater( new PlotEvent( this, state, nPoint, nInclude, nVisible ) ); /* Log the time this painting took for tuning purposes. */ logger_.fine( "3D plot time (ms): " + ( System.currentTimeMillis() - tStart ) ); } /** * Draws grid lines which contain all the known points. * According to the value of the <code>front</code> parameter, * either the lines which are behind all the data points, * or the lines which are in front of all the data points are drawn. * Thus, the routine needs to be called twice to plot all the lines. * * @param g graphics context * @param trans transformer which maps data space to 3d graphics space * @param vol the plotting volume onto which the plot is done * @param front true for lines in front of data, false for lines behind */ private void plotAxes( Graphics g, Transformer3D trans, PlotVolume vol, boolean front ) { Plot3DState state = (Plot3DState) getState(); Graphics2D g2 = (Graphics2D) g; Object antialias = g2.getRenderingHint( RenderingHints.KEY_ANTIALIASING ); g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, state.getAntialias() ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_DEFAULT ); plotAxes( state, g, trans, vol, front ); g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, antialias ); } /** * Returns an iterator over the points plotted last time this component * painted itself. * * @return point iterator */ public PointIterator getPlottedPointIterator() { PlotData data = getState().getPlotData(); if ( lastVol_ != null && lastTrans_ != null && data != null ) { return new PlotDataPointIterator( data, getPointPlacer() ); } else { return PointIterator.EMPTY; } } /** * Returns a point placer for mapping 3D data points to the screen. * * @return point placer */ public PointPlacer getPointPlacer() { final PlotVolume vol = lastVol_; final Transformer3D trans = lastTrans_; if ( trans == null || vol == null ) { return null; } final boolean[] logFlags = get3DLogFlags(); final RangeChecker ranger = rangeChecker_; Rectangle plotBounds = getPlotBounds(); final int xmin = plotBounds.x + 1; final int xmax = plotBounds.x + plotBounds.width - 2; final int ymin = plotBounds.y + 1; final int ymax = plotBounds.y + plotBounds.height - 2; final double zmax = zmax_; return new PointPlacer() { public Point getXY( double[] coords ) { if ( ranger.inRange( coords ) && logize( coords, get3DLogFlags() ) ) { trans.transform( coords ); double z = coords[ 2 ]; if ( z <= zmax ) { int px = vol.projectX( coords[ 0 ] ); int py = vol.projectY( coords[ 1 ] ); Insets insets = getInsets(); px += insets.left; py += insets.top; if ( px >= xmin && px <= xmax && py >= ymin && py <= ymax ) { return new Point( px, py ); } } } return null; } }; } /** * Lazily constructs and returns a ZBufferPlotVolume workspace object * owned by this plot. * * @return new or used workspace object */ private ZBufferPlotVolume.Workspace getZBufferWorkspace() { if ( ! ( plotvolWorkspace_ instanceof ZBufferPlotVolume.Workspace ) ) { plotvolWorkspace_ = new ZBufferPlotVolume.Workspace(); } return (ZBufferPlotVolume.Workspace) plotvolWorkspace_; } /** * Lazily constructs and returns a BitmapSortPlotVolume workspace object * owned by this plot. * * @return new or used workspace object */ private BitmapSortPlotVolume.Workspace getBitmapSortWorkspace() { if ( ! ( plotvolWorkspace_ instanceof BitmapSortPlotVolume.Workspace ) ) { plotvolWorkspace_ = new BitmapSortPlotVolume.Workspace(); } return (BitmapSortPlotVolume.Workspace ) plotvolWorkspace_; } /** * Converts coordinates to logarithmic values if necessary. * The <code>coords</code> array holds the input values on entry, * and each of these will be turned into logarithms of themselves * on exit iff the corresponding element of the logFlags array is * true. * The return value will be true if the conversion went OK, and * false if it couldn't be done for at least one coordinate, * because it was non-positive. * * @param coords 3-element coordinate array */ protected static boolean logize( double[] coords, boolean[] logFlags ) { for ( int iax = 0; iax < 3; iax++ ) { if ( logFlags[ iax ] ) { if ( coords[ iax ] > 0 ) { coords[ iax ] = Math.log( coords[ iax ] ); } else { return false; } } } return true; } /** * Determines whether a 3-d coordinate is within given 3-d bounds. * Sitting on the boundary counts as in range. * If any of the elements of <code>coords</code> is NaN, false * is returned. * * @param coords 3-element array giving coordinates to test * @param lo 3-element array giving lower bounds of range * @param hi 3-element array giving upper bounds of range * @return true iff <code>coords</code> is between <code>lo</code> * and <code>hi</code> */ private static boolean inRange( double[] coords, double[] lo, double[] hi ) { return coords[ 0 ] >= lo[ 0 ] && coords[ 0 ] <= hi[ 0 ] && coords[ 1 ] >= lo[ 1 ] && coords[ 1 ] <= hi[ 1 ] && coords[ 2 ] >= lo[ 2 ] && coords[ 2 ] <= hi[ 2 ]; } /** * Transforms errors from the form they assume in input data (offsets * to a central data point in data space) to a set of absolute * coordinates of points in the transformed graphics space. * The arrangement of the input data offsets * (<code>loErrs</code>, <code>hiErrs</code>) is as determined by the * {@link PlotData} object. * The number and ordering of the output data points * (<code>xerrs</code>, <code>yerrs</code>, <code>zerrs</code>) * are as required by {@link ErrorRenderer} objects. * * <p>Points which don't represent errors, either because they have * zero offsets or because they fall outside of the range of this 3D plot, * are represented in the output coordinates as <code>Double.NaN</code>. * The return value indicates whether any of the transformed values * have non-blank values - if false, then error drawing is pointless. * * @param trans data space -> graphics space transformer * @param ranger range checker - anything out of range will be discarded * @param logFlags flags for which axes will be plotted logarithmically * @param errors data space error points, in pairs * @param xerrs graphics space X coordinates for error points * @param yerrs graphics space Y coordinates for error points * @param zerrs graphics space Z coordinates for error points * @return true if some of the calculated errors are non-blank */ protected static boolean transformErrors( Transformer3D trans, RangeChecker ranger, boolean[] logFlags, double[][] errors, double[] xerrs, double[] yerrs, double[] zerrs ) { /* Initialise output error values. */ int nerr = xerrs.length; assert nerr == yerrs.length; assert nerr == zerrs.length; for ( int ierr = 0; ierr < nerr; ierr++ ) { xerrs[ ierr ] = Double.NaN; yerrs[ ierr ] = Double.NaN; zerrs[ ierr ] = Double.NaN; } /* Initialise other variables. */ boolean hasError = false; int ierr = 0; int nerrDim = errors.length / 2; for ( int ied = 0; ied < nerrDim; ied++ ) { double[] lo = errors[ ied * 2 + 0 ]; double[] hi = errors[ ied * 2 + 1 ]; if ( lo != null ) { if ( ranger.inRange( lo ) && logize( lo, logFlags ) ) { trans.transform( lo ); xerrs[ ierr ] = lo[ 0 ]; yerrs[ ierr ] = lo[ 1 ]; zerrs[ ierr ] = lo[ 2 ]; hasError = true; } } ierr++; if ( hi != null ) { if ( ranger.inRange( hi ) && logize( hi, logFlags ) ) { trans.transform( hi ); xerrs[ ierr ] = hi[ 0 ]; yerrs[ ierr ] = hi[ 1 ]; zerrs[ ierr ] = hi[ 2 ]; hasError = true; } } ierr++; } return hasError; } /** * Hook for handling OutOfMemoryErrors which may be generated during * plotting. May be called from the event dispatch thread. * The Plot3D implementation returns false. * * @param e error * @return true iff the error is handled (for intance user is informed) */ protected boolean paintMemoryError( OutOfMemoryError e ) { return false; } /** * Interface for checking that a 3-d coordinate is in range. */ protected static abstract class RangeChecker { /** * Returns true iff the 3-element coords array is considered in * plotting range for a particular 3D plot. * Sitting on the boundary normally counts as in range. * If any of the elements of <code>coords</code> is NaN, * the return should be <code>false</code>. * * @param coords 3-element coordinates of a point in data space * @return true iff coords in in range for this plot */ abstract boolean inRange( double[] coords ); } /** * Transforms points in 3d data space to points in 3d graphics space. */ protected static class Transformer3D { final double[] loBounds_; final double[] factors_; final double[] rot_; final double zoom_; /** * Constructs a transformer. A cuboid of interest in data space * is specified by the <code>loBounds</code> and <code>hiBounds</code> * arrays. When the <code>transform()</code> method is called * on a point within this region, it will transform it to * lie in a unit sphere centred on (0.5, 0.5, 0.5) and hence, * <i>a fortiori</i>, in the unit cube. * * @param rotation 9-element unitary rotation matrix * @param loBounds lower bounds of cuboid of interest (xlo,ylo,zlo) * @param hiBounds upper bounds of cuboid of interest (xhi,yhi,zhi) * @param zoom zoom factor to apply to X-Y values */ Transformer3D( double[] rotation, double[] loBounds, double[] hiBounds, double zoom ) { rot_ = (double[]) rotation.clone(); loBounds_ = new double[ 3 ]; factors_ = new double[ 3 ]; zoom_ = zoom; for ( int i = 0; i < 3; i++ ) { double lo = loBounds[ i ]; double hi = hiBounds[ i ]; if ( lo == hi ) { lo = lo - 1.0; hi = hi + 1.0; } loBounds_[ i ] = lo; factors_[ i ] = 1.0 / ( hi - lo ); } } /** * Transforms a point in data space to a point in graphics space. * * @param coords point coordinates (modified on exit) */ void transform( double[] coords ) { /* Shift the coordinates to within a unit sphere centered on * the origin. */ for ( int i = 0; i < 3; i++ ) { coords[ i ] = ( coords[ i ] - loBounds_[ i ] ) * factors_[ i ] - 0.5; } /* Perform rotations as determined by the rotation matrix. */ double x = coords[ 0 ]; double y = coords[ 1 ]; double z = coords[ 2 ]; coords[ 0 ] = rot_[ 0 ] * x + rot_[ 1 ] * y + rot_[ 2 ] * z; coords[ 1 ] = rot_[ 3 ] * x + rot_[ 4 ] * y + rot_[ 5 ] * z; coords[ 2 ] = rot_[ 6 ] * x + rot_[ 7 ] * y + rot_[ 8 ] * z; /* Zoom. */ coords[ 0 ] *= zoom_; coords[ 1 ] *= zoom_; /* Shift the origin so the unit sphere is centred at (.5,.5,.5). */ for ( int i = 0; i < 3; i++ ) { coords[ i ] += 0.5; } } /** * Returns the vector in data space which points into the screen. * * @return vector normal to view */ double[] getDepthVector() { return Matrices.normalise( Matrices.mvMult( Matrices.invert( rot_ ), new double[] { 0., 0., 1. } ) ); } } /** * Component containing the plot. */ private class Plot3DDataPanel extends JComponent { private boolean failed_ = false; Plot3DDataPanel() { setBackground( Color.WHITE ); setOpaque( true ); } protected void paintComponent( Graphics g ) { super.paintComponent( g ); if ( isOpaque() ) { ((Graphics2D) g).setBackground( getBackground() ); g.clearRect( 0, 0, getWidth(), getHeight() ); } if ( ! failed_ ) { try { drawData( g, this ); } catch ( OutOfMemoryError e ) { failed_ = true; if ( ! paintMemoryError( e ) ) { logger_.log( Level.WARNING, "Out of memory in 3D plot", e ); } } } } } }
false
true
private void drawData( Graphics g, Component c ) { /* Prepare data. */ Plot3DState state = (Plot3DState) getState(); PlotData data = state.getPlotData(); if ( data == null || state == null || ! state.getValid() ) { return; } int nset = data.getSetCount(); /* Set up a transformer to do the mapping from data space to * normalised 3-d view space. */ Transformer3D trans = new Transformer3D( state.getRotation(), loBoundsG_, hiBoundsG_, state.getZoomScale() ); /* Work out padding factors for the plot volume. */ padBorders_ = new int[ 4 ]; double padFactor = getPadding( state, g, padBorders_ ); /* Prepare an array of styles which we may need to plot on the * PlotVolume object. */ MarkStyle[] styles = new MarkStyle[ nset + 1 ]; for ( int is = 0; is < nset; is++ ) { styles[ is ] = (MarkStyle) data.getSetStyle( is ); } styles[ nset ] = DOT_STYLE; int iDotStyle = nset; /* See if all the markers are opaque; if they are we can use a * simpler rendering algorithm. */ boolean allOpaque = true; for ( int is = 0; is < nset && allOpaque; is++ ) { allOpaque = allOpaque && styles[ is ].getOpaqueLimit() == 1; } Shader[] shaders = state.getShaders(); for ( int iaux = 0; iaux < shaders.length; iaux++ ) { Shader shader = shaders[ iaux ]; allOpaque = allOpaque && ! Shaders.isTransparent( shaders[ iaux ] ); } /* See if there are any error bars to be plotted. If not, we can * use more efficient rendering machinery. */ boolean anyErrors = false; for ( int is = 0; is < nset && ! anyErrors; is++ ) { anyErrors = anyErrors || MarkStyle.hasErrors( (MarkStyle) styles[ is ], data ); } /* See if there may be labels to draw. */ boolean hasLabels = data.hasLabels(); /* Get fogginess. */ double fog = state.getFogginess(); /* Work out how points will be shaded according to auxiliary axis * coordinates. This does not include the effect of fogging, * which will be handled separately. */ DataColorTweaker tweaker = ShaderTweaker.createTweaker( 3, state ); /* Decide what rendering algorithm we're going to have to use, and * create a PlotVolume object accordingly. */ PlotVolume vol; if ( isVectorContext( g ) ) { if ( ! allOpaque ) { logger_.warning( "Can't render transparency in PostScript" ); } vol = new VectorSortPlotVolume( c, g, styles, padFactor, padBorders_, fog, tweaker ); } else if ( allOpaque ) { vol = new ZBufferPlotVolume( c, g, styles, padFactor, padBorders_, fog, hasLabels, tweaker, getZBufferWorkspace() ); } else { vol = new BitmapSortPlotVolume( c, g, styles, padFactor, padBorders_, fog, hasLabels, anyErrors, -1.0, 2.0, tweaker, getBitmapSortWorkspace() ); } logger_.config( "PlotVolume class is: " + vol.getClass().getName() ); /* If we're zoomed on a spherical plot and the points are only * on the surface of the sphere, then we don't want to see the * points on the far surface. */ boolean frontOnly = frontOnly( state ); /* Plot back part of bounding box. */ boolean grid = state.getGrid(); if ( grid && ! frontOnly ) { plotAxes( g, trans, vol, false ); } /* Work out which sets have markers and which sets have error bars * drawn. */ boolean[] showPoints = new boolean[ nset ]; boolean[] showErrors = new boolean[ nset ]; for ( int is = 0; is < nset; is++ ) { MarkStyle style = (MarkStyle) styles[ is ]; showPoints[ is ] = ! style.getHidePoints(); showErrors[ is ] = MarkStyle.hasErrors( style, data ); } /* Start the stopwatch to time how long it takes to plot all points. */ long tStart = System.currentTimeMillis(); /* If this is an intermediate plot (during a rotation, with a * guaranteed non-intermediate one to follow shortly), then prepare * to plot only a fraction of the points. In this way we can * ensure reasonable responsiveness - dragging the plot to rotate * it will not take ages between frames. */ boolean isRotating = state.getRotating(); int step = isRotating ? Math.max( plotTime_ / 100, 1 ) : 1; /* If we're only looking at the front surface of a sphere and we're * zoomed we can arrange a limit on the Z coordinate to filter points. * This is partly optimisation (not plotting points that aren't * seen because they are off screen laterally) and partly so we * don't see points on the far surface (zmax=0.5). * By my quick trig the limit for optimisation ought to be * Math.sqrt(0.5)*(1-Math.sqrt(1-0.25/(zoom*zoom)), * but that gives a region that's too small so I must have gone wrong. * There's something about aspect ratio to take into account too. * So, leave it as 0.5 for now, which is correct but not optimal. */ zmax_ = frontOnly ? 0.5 : Double.MAX_VALUE; /* Submit each point for drawing in the display volume as * appropriate. */ int nInclude = 0; int nVisible = 0; boolean[] logFlags = get3DLogFlags(); boolean[] showMarkPoints = new boolean[ nset ]; boolean[] showMarkErrors = new boolean[ nset ]; double[] centre = new double[ 3 ]; int nerr = data.getNerror(); double[] xerrs = new double[ nerr ]; double[] yerrs = new double[ nerr ]; double[] zerrs = new double[ nerr ]; RangeChecker ranger = rangeChecker_; int ip = 0; PointSequence pseq = data.getPointSequence(); while ( pseq.next() ) { boolean use = false; boolean useErrors = false; int labelSet = -1; for ( int is = 0; is < nset; is++ ) { boolean included = pseq.isIncluded( is ); use = use || included; boolean showP = included && showPoints[ is ]; boolean showE = included && showErrors[ is ]; useErrors = useErrors || showE; showMarkPoints[ is ] = showP; showMarkErrors[ is ] = showE; if ( included && hasLabels ) { labelSet = is; } } if ( use ) { nInclude++; double[] coords = pseq.getPoint(); centre[ 0 ] = coords[ 0 ]; centre[ 1 ] = coords[ 1 ]; centre[ 2 ] = coords[ 2 ]; if ( ranger.inRange( coords ) && logize( coords, logFlags ) ) { trans.transform( coords ); if ( coords[ 2 ] < zmax_ ) { if ( useErrors ) { double[][] errors = pseq.getErrors(); useErrors = useErrors && transformErrors( trans, ranger, logFlags, errors, xerrs, yerrs, zerrs ); } boolean vis = false; for ( int is = 0; is < nset; is++ ) { int numErr = useErrors && showMarkErrors[ is ] ? nerr : 0; String label; if ( is == labelSet ) { label = pseq.getLabel(); if ( label != null && label.trim().length() == 0 ) { label = null; } } else { label = null; } boolean plotted = vol.plot3d( coords, is, showMarkPoints[ is ], label, numErr, xerrs, yerrs, zerrs ); vis = vis || plotted; } if ( vis ) { nVisible++; } } } } while ( ( ++ip % step ) != 0 && pseq.next() ); } pseq.close(); int nPoint = ip; /* Plot a teeny static dot in the middle of the data. */ double[] dot = new double[ data.getNdim() ]; dot[ 0 ] = 0.5; dot[ 1 ] = 0.5; dot[ 2 ] = 0.5; vol.plot3d( dot, iDotStyle, true, null, 0, null, null, null ); /* Tell the volume that all the points are in for plotting. * This will do the painting on the graphics context if it hasn't * been done already. */ vol.flush(); /* Calculate time to plot all points. */ if ( ! isRotating ) { plotTime_ = (int) ( System.currentTimeMillis() - tStart ); } /* Plot front part of bounding box. */ if ( grid ) { plotAxes( g, trans, vol, true ); } /* Store information about the most recent plot. */ lastVol_ = vol; lastTrans_ = trans; firePlotChangedLater( new PlotEvent( this, state, nPoint, nInclude, nVisible ) ); /* Log the time this painting took for tuning purposes. */ logger_.fine( "3D plot time (ms): " + ( System.currentTimeMillis() - tStart ) ); }
private void drawData( Graphics g, Component c ) { /* Prepare data. */ Plot3DState state = (Plot3DState) getState(); if ( state == null || ! state.getValid() ) { return; } PlotData data = state.getPlotData(); if ( data == null ) { return; } int nset = data.getSetCount(); /* Set up a transformer to do the mapping from data space to * normalised 3-d view space. */ Transformer3D trans = new Transformer3D( state.getRotation(), loBoundsG_, hiBoundsG_, state.getZoomScale() ); /* Work out padding factors for the plot volume. */ padBorders_ = new int[ 4 ]; double padFactor = getPadding( state, g, padBorders_ ); /* Prepare an array of styles which we may need to plot on the * PlotVolume object. */ MarkStyle[] styles = new MarkStyle[ nset + 1 ]; for ( int is = 0; is < nset; is++ ) { styles[ is ] = (MarkStyle) data.getSetStyle( is ); } styles[ nset ] = DOT_STYLE; int iDotStyle = nset; /* See if all the markers are opaque; if they are we can use a * simpler rendering algorithm. */ boolean allOpaque = true; for ( int is = 0; is < nset && allOpaque; is++ ) { allOpaque = allOpaque && styles[ is ].getOpaqueLimit() == 1; } Shader[] shaders = state.getShaders(); for ( int iaux = 0; iaux < shaders.length; iaux++ ) { Shader shader = shaders[ iaux ]; allOpaque = allOpaque && ! Shaders.isTransparent( shaders[ iaux ] ); } /* See if there are any error bars to be plotted. If not, we can * use more efficient rendering machinery. */ boolean anyErrors = false; for ( int is = 0; is < nset && ! anyErrors; is++ ) { anyErrors = anyErrors || MarkStyle.hasErrors( (MarkStyle) styles[ is ], data ); } /* See if there may be labels to draw. */ boolean hasLabels = data.hasLabels(); /* Get fogginess. */ double fog = state.getFogginess(); /* Work out how points will be shaded according to auxiliary axis * coordinates. This does not include the effect of fogging, * which will be handled separately. */ DataColorTweaker tweaker = ShaderTweaker.createTweaker( 3, state ); /* Decide what rendering algorithm we're going to have to use, and * create a PlotVolume object accordingly. */ PlotVolume vol; if ( isVectorContext( g ) ) { if ( ! allOpaque ) { logger_.warning( "Can't render transparency in PostScript" ); } vol = new VectorSortPlotVolume( c, g, styles, padFactor, padBorders_, fog, tweaker ); } else if ( allOpaque ) { vol = new ZBufferPlotVolume( c, g, styles, padFactor, padBorders_, fog, hasLabels, tweaker, getZBufferWorkspace() ); } else { vol = new BitmapSortPlotVolume( c, g, styles, padFactor, padBorders_, fog, hasLabels, anyErrors, -1.0, 2.0, tweaker, getBitmapSortWorkspace() ); } logger_.config( "PlotVolume class is: " + vol.getClass().getName() ); /* If we're zoomed on a spherical plot and the points are only * on the surface of the sphere, then we don't want to see the * points on the far surface. */ boolean frontOnly = frontOnly( state ); /* Plot back part of bounding box. */ boolean grid = state.getGrid(); if ( grid && ! frontOnly ) { plotAxes( g, trans, vol, false ); } /* Work out which sets have markers and which sets have error bars * drawn. */ boolean[] showPoints = new boolean[ nset ]; boolean[] showErrors = new boolean[ nset ]; for ( int is = 0; is < nset; is++ ) { MarkStyle style = (MarkStyle) styles[ is ]; showPoints[ is ] = ! style.getHidePoints(); showErrors[ is ] = MarkStyle.hasErrors( style, data ); } /* Start the stopwatch to time how long it takes to plot all points. */ long tStart = System.currentTimeMillis(); /* If this is an intermediate plot (during a rotation, with a * guaranteed non-intermediate one to follow shortly), then prepare * to plot only a fraction of the points. In this way we can * ensure reasonable responsiveness - dragging the plot to rotate * it will not take ages between frames. */ boolean isRotating = state.getRotating(); int step = isRotating ? Math.max( plotTime_ / 100, 1 ) : 1; /* If we're only looking at the front surface of a sphere and we're * zoomed we can arrange a limit on the Z coordinate to filter points. * This is partly optimisation (not plotting points that aren't * seen because they are off screen laterally) and partly so we * don't see points on the far surface (zmax=0.5). * By my quick trig the limit for optimisation ought to be * Math.sqrt(0.5)*(1-Math.sqrt(1-0.25/(zoom*zoom)), * but that gives a region that's too small so I must have gone wrong. * There's something about aspect ratio to take into account too. * So, leave it as 0.5 for now, which is correct but not optimal. */ zmax_ = frontOnly ? 0.5 : Double.MAX_VALUE; /* Submit each point for drawing in the display volume as * appropriate. */ int nInclude = 0; int nVisible = 0; boolean[] logFlags = get3DLogFlags(); boolean[] showMarkPoints = new boolean[ nset ]; boolean[] showMarkErrors = new boolean[ nset ]; double[] centre = new double[ 3 ]; int nerr = data.getNerror(); double[] xerrs = new double[ nerr ]; double[] yerrs = new double[ nerr ]; double[] zerrs = new double[ nerr ]; RangeChecker ranger = rangeChecker_; int ip = 0; PointSequence pseq = data.getPointSequence(); while ( pseq.next() ) { boolean use = false; boolean useErrors = false; int labelSet = -1; for ( int is = 0; is < nset; is++ ) { boolean included = pseq.isIncluded( is ); use = use || included; boolean showP = included && showPoints[ is ]; boolean showE = included && showErrors[ is ]; useErrors = useErrors || showE; showMarkPoints[ is ] = showP; showMarkErrors[ is ] = showE; if ( included && hasLabels ) { labelSet = is; } } if ( use ) { nInclude++; double[] coords = pseq.getPoint(); centre[ 0 ] = coords[ 0 ]; centre[ 1 ] = coords[ 1 ]; centre[ 2 ] = coords[ 2 ]; if ( ranger.inRange( coords ) && logize( coords, logFlags ) ) { trans.transform( coords ); if ( coords[ 2 ] < zmax_ ) { if ( useErrors ) { double[][] errors = pseq.getErrors(); useErrors = useErrors && transformErrors( trans, ranger, logFlags, errors, xerrs, yerrs, zerrs ); } boolean vis = false; for ( int is = 0; is < nset; is++ ) { int numErr = useErrors && showMarkErrors[ is ] ? nerr : 0; String label; if ( is == labelSet ) { label = pseq.getLabel(); if ( label != null && label.trim().length() == 0 ) { label = null; } } else { label = null; } boolean plotted = vol.plot3d( coords, is, showMarkPoints[ is ], label, numErr, xerrs, yerrs, zerrs ); vis = vis || plotted; } if ( vis ) { nVisible++; } } } } while ( ( ++ip % step ) != 0 && pseq.next() ); } pseq.close(); int nPoint = ip; /* Plot a teeny static dot in the middle of the data. */ double[] dot = new double[ data.getNdim() ]; dot[ 0 ] = 0.5; dot[ 1 ] = 0.5; dot[ 2 ] = 0.5; vol.plot3d( dot, iDotStyle, true, null, 0, null, null, null ); /* Tell the volume that all the points are in for plotting. * This will do the painting on the graphics context if it hasn't * been done already. */ vol.flush(); /* Calculate time to plot all points. */ if ( ! isRotating ) { plotTime_ = (int) ( System.currentTimeMillis() - tStart ); } /* Plot front part of bounding box. */ if ( grid ) { plotAxes( g, trans, vol, true ); } /* Store information about the most recent plot. */ lastVol_ = vol; lastTrans_ = trans; firePlotChangedLater( new PlotEvent( this, state, nPoint, nInclude, nVisible ) ); /* Log the time this painting took for tuning purposes. */ logger_.fine( "3D plot time (ms): " + ( System.currentTimeMillis() - tStart ) ); }
diff --git a/src/jvm/clojure/lang/LispReader.java b/src/jvm/clojure/lang/LispReader.java index 8f67b3b2..4b987dc5 100644 --- a/src/jvm/clojure/lang/LispReader.java +++ b/src/jvm/clojure/lang/LispReader.java @@ -1,1256 +1,1258 @@ /** * Copyright (c) Rich Hickey. All rights reserved. * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file epl-v10.html at the root of this distribution. * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * You must not remove this notice, or any other, from this software. **/ package clojure.lang; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.lang.Character; import java.lang.Class; import java.lang.Exception; import java.lang.IllegalArgumentException; import java.lang.IllegalStateException; import java.lang.Integer; import java.lang.Number; import java.lang.NumberFormatException; import java.lang.Object; import java.lang.RuntimeException; import java.lang.String; import java.lang.StringBuilder; import java.lang.Throwable; import java.lang.UnsupportedOperationException; import java.lang.reflect.Constructor; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LispReader{ static final Symbol QUOTE = Symbol.intern("quote"); static final Symbol THE_VAR = Symbol.intern("var"); //static Symbol SYNTAX_QUOTE = Symbol.intern(null, "syntax-quote"); static Symbol UNQUOTE = Symbol.intern("clojure.core", "unquote"); static Symbol UNQUOTE_SPLICING = Symbol.intern("clojure.core", "unquote-splicing"); static Symbol CONCAT = Symbol.intern("clojure.core", "concat"); static Symbol SEQ = Symbol.intern("clojure.core", "seq"); static Symbol LIST = Symbol.intern("clojure.core", "list"); static Symbol APPLY = Symbol.intern("clojure.core", "apply"); static Symbol HASHMAP = Symbol.intern("clojure.core", "hash-map"); static Symbol HASHSET = Symbol.intern("clojure.core", "hash-set"); static Symbol VECTOR = Symbol.intern("clojure.core", "vector"); static Symbol WITH_META = Symbol.intern("clojure.core", "with-meta"); static Symbol META = Symbol.intern("clojure.core", "meta"); static Symbol DEREF = Symbol.intern("clojure.core", "deref"); //static Symbol DEREF_BANG = Symbol.intern("clojure.core", "deref!"); static IFn[] macros = new IFn[256]; static IFn[] dispatchMacros = new IFn[256]; //static Pattern symbolPat = Pattern.compile("[:]?([\\D&&[^:/]][^:/]*/)?[\\D&&[^:/]][^:/]*"); static Pattern symbolPat = Pattern.compile("[:]?([\\D&&[^/]].*/)?([\\D&&[^/]][^/]*)"); //static Pattern varPat = Pattern.compile("([\\D&&[^:\\.]][^:\\.]*):([\\D&&[^:\\.]][^:\\.]*)"); //static Pattern intPat = Pattern.compile("[-+]?[0-9]+\\.?"); static Pattern intPat = Pattern.compile( "([-+]?)(?:(0)|([1-9][0-9]*)|0[xX]([0-9A-Fa-f]+)|0([0-7]+)|([1-9][0-9]?)[rR]([0-9A-Za-z]+)|0[0-9]+)(N)?"); static Pattern ratioPat = Pattern.compile("([-+]?[0-9]+)/([0-9]+)"); static Pattern floatPat = Pattern.compile("([-+]?[0-9]+(\\.[0-9]*)?([eE][-+]?[0-9]+)?)(M)?"); static final Symbol SLASH = Symbol.intern("/"); static final Symbol CLOJURE_SLASH = Symbol.intern("clojure.core","/"); //static Pattern accessorPat = Pattern.compile("\\.[a-zA-Z_]\\w*"); //static Pattern instanceMemberPat = Pattern.compile("\\.([a-zA-Z_][\\w\\.]*)\\.([a-zA-Z_]\\w*)"); //static Pattern staticMemberPat = Pattern.compile("([a-zA-Z_][\\w\\.]*)\\.([a-zA-Z_]\\w*)"); //static Pattern classNamePat = Pattern.compile("([a-zA-Z_][\\w\\.]*)\\."); //symbol->gensymbol static Var GENSYM_ENV = Var.create(null).setDynamic(); //sorted-map num->gensymbol static Var ARG_ENV = Var.create(null).setDynamic(); static IFn ctorReader = new CtorReader(); static { macros['"'] = new StringReader(); macros[';'] = new CommentReader(); macros['\''] = new WrappingReader(QUOTE); macros['@'] = new WrappingReader(DEREF);//new DerefReader(); macros['^'] = new MetaReader(); macros['`'] = new SyntaxQuoteReader(); macros['~'] = new UnquoteReader(); macros['('] = new ListReader(); macros[')'] = new UnmatchedDelimiterReader(); macros['['] = new VectorReader(); macros[']'] = new UnmatchedDelimiterReader(); macros['{'] = new MapReader(); macros['}'] = new UnmatchedDelimiterReader(); // macros['|'] = new ArgVectorReader(); macros['\\'] = new CharacterReader(); macros['%'] = new ArgReader(); macros['#'] = new DispatchReader(); dispatchMacros['^'] = new MetaReader(); dispatchMacros['\''] = new VarReader(); dispatchMacros['"'] = new RegexReader(); dispatchMacros['('] = new FnReader(); dispatchMacros['{'] = new SetReader(); dispatchMacros['='] = new EvalReader(); dispatchMacros['!'] = new CommentReader(); dispatchMacros['<'] = new UnreadableReader(); dispatchMacros['_'] = new DiscardReader(); } static boolean isWhitespace(int ch){ return Character.isWhitespace(ch) || ch == ','; } static void unread(PushbackReader r, int ch) { if(ch != -1) try { r.unread(ch); } catch(IOException e) { throw Util.sneakyThrow(e); } } public static class ReaderException extends RuntimeException{ final int line; public ReaderException(int line, Throwable cause){ super(cause); this.line = line; } } static public int read1(Reader r){ try { return r.read(); } catch(IOException e) { throw Util.sneakyThrow(e); } } static public Object read(PushbackReader r, boolean eofIsError, Object eofValue, boolean isRecursive) { try { for(; ;) { int ch = read1(r); while(isWhitespace(ch)) ch = read1(r); if(ch == -1) { if(eofIsError) throw Util.runtimeException("EOF while reading"); return eofValue; } if(Character.isDigit(ch)) { Object n = readNumber(r, (char) ch); if(RT.suppressRead()) return null; return n; } IFn macroFn = getMacro(ch); if(macroFn != null) { Object ret = macroFn.invoke(r, (char) ch); if(RT.suppressRead()) return null; //no op macros return the reader if(ret == r) continue; return ret; } if(ch == '+' || ch == '-') { int ch2 = read1(r); if(Character.isDigit(ch2)) { unread(r, ch2); Object n = readNumber(r, (char) ch); if(RT.suppressRead()) return null; return n; } unread(r, ch2); } String token = readToken(r, (char) ch); if(RT.suppressRead()) return null; return interpretToken(token); } } catch(Exception e) { if(isRecursive || !(r instanceof LineNumberingPushbackReader)) throw Util.sneakyThrow(e); LineNumberingPushbackReader rdr = (LineNumberingPushbackReader) r; //throw Util.runtimeException(String.format("ReaderError:(%d,1) %s", rdr.getLineNumber(), e.getMessage()), e); throw new ReaderException(rdr.getLineNumber(), e); } } static private String readToken(PushbackReader r, char initch) { StringBuilder sb = new StringBuilder(); sb.append(initch); for(; ;) { int ch = read1(r); if(ch == -1 || isWhitespace(ch) || isTerminatingMacro(ch)) { unread(r, ch); return sb.toString(); } sb.append((char) ch); } } static private Object readNumber(PushbackReader r, char initch) { StringBuilder sb = new StringBuilder(); sb.append(initch); for(; ;) { int ch = read1(r); if(ch == -1 || isWhitespace(ch) || isMacro(ch)) { unread(r, ch); break; } sb.append((char) ch); } String s = sb.toString(); Object n = matchNumber(s); if(n == null) throw new NumberFormatException("Invalid number: " + s); return n; } static private int readUnicodeChar(String token, int offset, int length, int base) { if(token.length() != offset + length) throw new IllegalArgumentException("Invalid unicode character: \\" + token); int uc = 0; for(int i = offset; i < offset + length; ++i) { int d = Character.digit(token.charAt(i), base); if(d == -1) throw new IllegalArgumentException("Invalid digit: " + token.charAt(i)); uc = uc * base + d; } return (char) uc; } static private int readUnicodeChar(PushbackReader r, int initch, int base, int length, boolean exact) { int uc = Character.digit(initch, base); if(uc == -1) throw new IllegalArgumentException("Invalid digit: " + (char) initch); int i = 1; for(; i < length; ++i) { int ch = read1(r); if(ch == -1 || isWhitespace(ch) || isMacro(ch)) { unread(r, ch); break; } int d = Character.digit(ch, base); if(d == -1) throw new IllegalArgumentException("Invalid digit: " + (char) ch); uc = uc * base + d; } if(i != length && exact) throw new IllegalArgumentException("Invalid character length: " + i + ", should be: " + length); return uc; } static private Object interpretToken(String s) { if(s.equals("nil")) { return null; } else if(s.equals("true")) { return RT.T; } else if(s.equals("false")) { return RT.F; } else if(s.equals("/")) { return SLASH; } else if(s.equals("clojure.core//")) { return CLOJURE_SLASH; } Object ret = null; ret = matchSymbol(s); if(ret != null) return ret; throw Util.runtimeException("Invalid token: " + s); } private static Object matchSymbol(String s){ Matcher m = symbolPat.matcher(s); if(m.matches()) { int gc = m.groupCount(); String ns = m.group(1); String name = m.group(2); if(ns != null && ns.endsWith(":/") || name.endsWith(":") || s.indexOf("::", 1) != -1) return null; if(s.startsWith("::")) { Symbol ks = Symbol.intern(s.substring(2)); Namespace kns; if(ks.ns != null) kns = Compiler.namespaceFor(ks); else kns = Compiler.currentNS(); //auto-resolving keyword if (kns != null) return Keyword.intern(kns.name.name,ks.name); else return null; } boolean isKeyword = s.charAt(0) == ':'; Symbol sym = Symbol.intern(s.substring(isKeyword ? 1 : 0)); if(isKeyword) return Keyword.intern(sym); return sym; } return null; } private static Object matchNumber(String s){ Matcher m = intPat.matcher(s); if(m.matches()) { if(m.group(2) != null) { if(m.group(8) != null) return BigInt.ZERO; return Numbers.num(0); } boolean negate = (m.group(1).equals("-")); String n; int radix = 10; if((n = m.group(3)) != null) radix = 10; else if((n = m.group(4)) != null) radix = 16; else if((n = m.group(5)) != null) radix = 8; else if((n = m.group(7)) != null) radix = Integer.parseInt(m.group(6)); if(n == null) return null; BigInteger bn = new BigInteger(n, radix); if(negate) bn = bn.negate(); if(m.group(8) != null) return BigInt.fromBigInteger(bn); return bn.bitLength() < 64 ? Numbers.num(bn.longValue()) : BigInt.fromBigInteger(bn); } m = floatPat.matcher(s); if(m.matches()) { if(m.group(4) != null) return new BigDecimal(m.group(1)); return Double.parseDouble(s); } m = ratioPat.matcher(s); if(m.matches()) { return Numbers.divide(Numbers.reduceBigInt(BigInt.fromBigInteger(new BigInteger(m.group(1)))), Numbers.reduceBigInt(BigInt.fromBigInteger(new BigInteger(m.group(2))))); } return null; } static private IFn getMacro(int ch){ if(ch < macros.length) return macros[ch]; return null; } static private boolean isMacro(int ch){ return (ch < macros.length && macros[ch] != null); } static private boolean isTerminatingMacro(int ch){ return (ch != '#' && ch != '\'' && isMacro(ch)); } public static class RegexReader extends AFn{ static StringReader stringrdr = new StringReader(); public Object invoke(Object reader, Object doublequote) { StringBuilder sb = new StringBuilder(); Reader r = (Reader) reader; for(int ch = read1(r); ch != '"'; ch = read1(r)) { if(ch == -1) throw Util.runtimeException("EOF while reading regex"); sb.append( (char) ch ); if(ch == '\\') //escape { ch = read1(r); if(ch == -1) throw Util.runtimeException("EOF while reading regex"); sb.append( (char) ch ) ; } } return Pattern.compile(sb.toString()); } } public static class StringReader extends AFn{ public Object invoke(Object reader, Object doublequote) { StringBuilder sb = new StringBuilder(); Reader r = (Reader) reader; for(int ch = read1(r); ch != '"'; ch = read1(r)) { if(ch == -1) throw Util.runtimeException("EOF while reading string"); if(ch == '\\') //escape { ch = read1(r); if(ch == -1) throw Util.runtimeException("EOF while reading string"); switch(ch) { case 't': ch = '\t'; break; case 'r': ch = '\r'; break; case 'n': ch = '\n'; break; case '\\': break; case '"': break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'u': { ch = read1(r); if (Character.digit(ch, 16) == -1) throw Util.runtimeException("Invalid unicode escape: \\u" + (char) ch); ch = readUnicodeChar((PushbackReader) r, ch, 16, 4, true); break; } default: { if(Character.isDigit(ch)) { ch = readUnicodeChar((PushbackReader) r, ch, 8, 3, false); if(ch > 0377) throw Util.runtimeException("Octal escape sequence must be in range [0, 377]."); } else throw Util.runtimeException("Unsupported escape character: \\" + (char) ch); } } } sb.append((char) ch); } return sb.toString(); } } public static class CommentReader extends AFn{ public Object invoke(Object reader, Object semicolon) { Reader r = (Reader) reader; int ch; do { ch = read1(r); } while(ch != -1 && ch != '\n' && ch != '\r'); return r; } } public static class DiscardReader extends AFn{ public Object invoke(Object reader, Object underscore) { PushbackReader r = (PushbackReader) reader; read(r, true, null, true); return r; } } public static class WrappingReader extends AFn{ final Symbol sym; public WrappingReader(Symbol sym){ this.sym = sym; } public Object invoke(Object reader, Object quote) { PushbackReader r = (PushbackReader) reader; Object o = read(r, true, null, true); return RT.list(sym, o); } } public static class DeprecatedWrappingReader extends AFn{ final Symbol sym; final String macro; public DeprecatedWrappingReader(Symbol sym, String macro){ this.sym = sym; this.macro = macro; } public Object invoke(Object reader, Object quote) { System.out.println("WARNING: reader macro " + macro + " is deprecated; use " + sym.getName() + " instead"); PushbackReader r = (PushbackReader) reader; Object o = read(r, true, null, true); return RT.list(sym, o); } } public static class VarReader extends AFn{ public Object invoke(Object reader, Object quote) { PushbackReader r = (PushbackReader) reader; Object o = read(r, true, null, true); // if(o instanceof Symbol) // { // Object v = Compiler.maybeResolveIn(Compiler.currentNS(), (Symbol) o); // if(v instanceof Var) // return v; // } return RT.list(THE_VAR, o); } } /* static class DerefReader extends AFn{ public Object invoke(Object reader, Object quote) { PushbackReader r = (PushbackReader) reader; int ch = read1(r); if(ch == -1) throw Util.runtimeException("EOF while reading character"); if(ch == '!') { Object o = read(r, true, null, true); return RT.list(DEREF_BANG, o); } else { r.unread(ch); Object o = read(r, true, null, true); return RT.list(DEREF, o); } } } */ public static class DispatchReader extends AFn{ public Object invoke(Object reader, Object hash) { int ch = read1((Reader) reader); if(ch == -1) throw Util.runtimeException("EOF while reading character"); IFn fn = dispatchMacros[ch]; // Try the ctor reader first if(fn == null) { unread((PushbackReader) reader, ch); Object result = ctorReader.invoke(reader, ch); if(result != null) return result; else throw Util.runtimeException(String.format("No dispatch macro for: %c", (char) ch)); } return fn.invoke(reader, ch); } } static Symbol garg(int n){ return Symbol.intern(null, (n == -1 ? "rest" : ("p" + n)) + "__" + RT.nextID() + "#"); } public static class FnReader extends AFn{ public Object invoke(Object reader, Object lparen) { PushbackReader r = (PushbackReader) reader; if(ARG_ENV.deref() != null) throw new IllegalStateException("Nested #()s are not allowed"); try { Var.pushThreadBindings( RT.map(ARG_ENV, PersistentTreeMap.EMPTY)); unread(r, '('); Object form = read(r, true, null, true); PersistentVector args = PersistentVector.EMPTY; PersistentTreeMap argsyms = (PersistentTreeMap) ARG_ENV.deref(); ISeq rargs = argsyms.rseq(); if(rargs != null) { int higharg = (Integer) ((Map.Entry) rargs.first()).getKey(); if(higharg > 0) { for(int i = 1; i <= higharg; ++i) { Object sym = argsyms.valAt(i); if(sym == null) sym = garg(i); args = args.cons(sym); } } Object restsym = argsyms.valAt(-1); if(restsym != null) { args = args.cons(Compiler._AMP_); args = args.cons(restsym); } } return RT.list(Compiler.FN, args, form); } finally { Var.popThreadBindings(); } } } static Symbol registerArg(int n){ PersistentTreeMap argsyms = (PersistentTreeMap) ARG_ENV.deref(); if(argsyms == null) { throw new IllegalStateException("arg literal not in #()"); } Symbol ret = (Symbol) argsyms.valAt(n); if(ret == null) { ret = garg(n); ARG_ENV.set(argsyms.assoc(n, ret)); } return ret; } static class ArgReader extends AFn{ public Object invoke(Object reader, Object pct) { PushbackReader r = (PushbackReader) reader; if(ARG_ENV.deref() == null) { return interpretToken(readToken(r, '%')); } int ch = read1(r); unread(r, ch); //% alone is first arg if(ch == -1 || isWhitespace(ch) || isTerminatingMacro(ch)) { return registerArg(1); } Object n = read(r, true, null, true); if(n.equals(Compiler._AMP_)) return registerArg(-1); if(!(n instanceof Number)) throw new IllegalStateException("arg literal must be %, %& or %integer"); return registerArg(((Number) n).intValue()); } } public static class MetaReader extends AFn{ public Object invoke(Object reader, Object caret) { PushbackReader r = (PushbackReader) reader; int line = -1; if(r instanceof LineNumberingPushbackReader) line = ((LineNumberingPushbackReader) r).getLineNumber(); Object meta = read(r, true, null, true); if(meta instanceof Symbol || meta instanceof String) meta = RT.map(RT.TAG_KEY, meta); else if (meta instanceof Keyword) meta = RT.map(meta, RT.T); else if(!(meta instanceof IPersistentMap)) throw new IllegalArgumentException("Metadata must be Symbol,Keyword,String or Map"); Object o = read(r, true, null, true); if(o instanceof IMeta) { if(line != -1 && o instanceof ISeq) meta = ((IPersistentMap) meta).assoc(RT.LINE_KEY, line); if(o instanceof IReference) { ((IReference)o).resetMeta((IPersistentMap) meta); return o; } Object ometa = RT.meta(o); for(ISeq s = RT.seq(meta); s != null; s = s.next()) { IMapEntry kv = (IMapEntry) s.first(); ometa = RT.assoc(ometa, kv.getKey(), kv.getValue()); } return ((IObj) o).withMeta((IPersistentMap) ometa); } else throw new IllegalArgumentException("Metadata can only be applied to IMetas"); } } public static class SyntaxQuoteReader extends AFn{ public Object invoke(Object reader, Object backquote) { PushbackReader r = (PushbackReader) reader; try { Var.pushThreadBindings( RT.map(GENSYM_ENV, PersistentHashMap.EMPTY)); Object form = read(r, true, null, true); return syntaxQuote(form); } finally { Var.popThreadBindings(); } } static Object syntaxQuote(Object form) { Object ret; if(Compiler.isSpecial(form)) ret = RT.list(Compiler.QUOTE, form); else if(form instanceof Symbol) { Symbol sym = (Symbol) form; if(sym.ns == null && sym.name.endsWith("#")) { IPersistentMap gmap = (IPersistentMap) GENSYM_ENV.deref(); if(gmap == null) throw new IllegalStateException("Gensym literal not in syntax-quote"); Symbol gs = (Symbol) gmap.valAt(sym); if(gs == null) GENSYM_ENV.set(gmap.assoc(sym, gs = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1) + "__" + RT.nextID() + "__auto__"))); sym = gs; } else if(sym.ns == null && sym.name.endsWith(".")) { Symbol csym = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1)); csym = Compiler.resolveSymbol(csym); sym = Symbol.intern(null, csym.name.concat(".")); } else if(sym.ns == null && sym.name.startsWith(".")) { // Simply quote method names. } else { Object maybeClass = null; if(sym.ns != null) maybeClass = Compiler.currentNS().getMapping( Symbol.intern(null, sym.ns)); if(maybeClass instanceof Class) { // Classname/foo -> package.qualified.Classname/foo sym = Symbol.intern( ((Class)maybeClass).getName(), sym.name); } else sym = Compiler.resolveSymbol(sym); } ret = RT.list(Compiler.QUOTE, sym); } else if(isUnquote(form)) return RT.second(form); else if(isUnquoteSplicing(form)) throw new IllegalStateException("splice not in list"); else if(form instanceof IPersistentCollection) { - if(form instanceof IPersistentMap) + if(form instanceof IRecord) + ret = form; + else if(form instanceof IPersistentMap) { IPersistentVector keyvals = flattenMap(form); ret = RT.list(APPLY, HASHMAP, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(keyvals.seq())))); } else if(form instanceof IPersistentVector) { ret = RT.list(APPLY, VECTOR, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentVector) form).seq())))); } else if(form instanceof IPersistentSet) { ret = RT.list(APPLY, HASHSET, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentSet) form).seq())))); } else if(form instanceof ISeq || form instanceof IPersistentList) { ISeq seq = RT.seq(form); if(seq == null) ret = RT.cons(LIST,null); else ret = RT.list(SEQ, RT.cons(CONCAT, sqExpandList(seq))); } else throw new UnsupportedOperationException("Unknown Collection type"); } else if(form instanceof Keyword || form instanceof Number || form instanceof Character || form instanceof String) ret = form; else ret = RT.list(Compiler.QUOTE, form); if(form instanceof IObj && RT.meta(form) != null) { //filter line numbers IPersistentMap newMeta = ((IObj) form).meta().without(RT.LINE_KEY); if(newMeta.count() > 0) return RT.list(WITH_META, ret, syntaxQuote(((IObj) form).meta())); } return ret; } private static ISeq sqExpandList(ISeq seq) { PersistentVector ret = PersistentVector.EMPTY; for(; seq != null; seq = seq.next()) { Object item = seq.first(); if(isUnquote(item)) ret = ret.cons(RT.list(LIST, RT.second(item))); else if(isUnquoteSplicing(item)) ret = ret.cons(RT.second(item)); else ret = ret.cons(RT.list(LIST, syntaxQuote(item))); } return ret.seq(); } private static IPersistentVector flattenMap(Object form){ IPersistentVector keyvals = PersistentVector.EMPTY; for(ISeq s = RT.seq(form); s != null; s = s.next()) { IMapEntry e = (IMapEntry) s.first(); keyvals = (IPersistentVector) keyvals.cons(e.key()); keyvals = (IPersistentVector) keyvals.cons(e.val()); } return keyvals; } } static boolean isUnquoteSplicing(Object form){ return form instanceof ISeq && Util.equals(RT.first(form),UNQUOTE_SPLICING); } static boolean isUnquote(Object form){ return form instanceof ISeq && Util.equals(RT.first(form),UNQUOTE); } static class UnquoteReader extends AFn{ public Object invoke(Object reader, Object comma) { PushbackReader r = (PushbackReader) reader; int ch = read1(r); if(ch == -1) throw Util.runtimeException("EOF while reading character"); if(ch == '@') { Object o = read(r, true, null, true); return RT.list(UNQUOTE_SPLICING, o); } else { unread(r, ch); Object o = read(r, true, null, true); return RT.list(UNQUOTE, o); } } } public static class CharacterReader extends AFn{ public Object invoke(Object reader, Object backslash) { PushbackReader r = (PushbackReader) reader; int ch = read1(r); if(ch == -1) throw Util.runtimeException("EOF while reading character"); String token = readToken(r, (char) ch); if(token.length() == 1) return Character.valueOf(token.charAt(0)); else if(token.equals("newline")) return '\n'; else if(token.equals("space")) return ' '; else if(token.equals("tab")) return '\t'; else if(token.equals("backspace")) return '\b'; else if(token.equals("formfeed")) return '\f'; else if(token.equals("return")) return '\r'; else if(token.startsWith("u")) { char c = (char) readUnicodeChar(token, 1, 4, 16); if(c >= '\uD800' && c <= '\uDFFF') // surrogate code unit? throw Util.runtimeException("Invalid character constant: \\u" + Integer.toString(c, 16)); return c; } else if(token.startsWith("o")) { int len = token.length() - 1; if(len > 3) throw Util.runtimeException("Invalid octal escape sequence length: " + len); int uc = readUnicodeChar(token, 1, len, 8); if(uc > 0377) throw Util.runtimeException("Octal escape sequence must be in range [0, 377]."); return (char) uc; } throw Util.runtimeException("Unsupported character: \\" + token); } } public static class ListReader extends AFn{ public Object invoke(Object reader, Object leftparen) { PushbackReader r = (PushbackReader) reader; int line = -1; if(r instanceof LineNumberingPushbackReader) line = ((LineNumberingPushbackReader) r).getLineNumber(); List list = readDelimitedList(')', r, true); if(list.isEmpty()) return PersistentList.EMPTY; IObj s = (IObj) PersistentList.create(list); // IObj s = (IObj) RT.seq(list); if(line != -1) return s.withMeta(RT.map(RT.LINE_KEY, line)); else return s; } } /* static class CtorReader extends AFn{ static final Symbol cls = Symbol.intern("class"); public Object invoke(Object reader, Object leftangle) { PushbackReader r = (PushbackReader) reader; // #<class classname> // #<classname args*> // #<classname/staticMethod args*> List list = readDelimitedList('>', r, true); if(list.isEmpty()) throw Util.runtimeException("Must supply 'class', classname or classname/staticMethod"); Symbol s = (Symbol) list.get(0); Object[] args = list.subList(1, list.size()).toArray(); if(s.equals(cls)) { return RT.classForName(args[0].toString()); } else if(s.ns != null) //static method { String classname = s.ns; String method = s.name; return Reflector.invokeStaticMethod(classname, method, args); } else { return Reflector.invokeConstructor(RT.classForName(s.name), args); } } } */ public static class EvalReader extends AFn{ public Object invoke(Object reader, Object eq) { if (!RT.booleanCast(RT.READEVAL.deref())) { throw Util.runtimeException("EvalReader not allowed when *read-eval* is false."); } PushbackReader r = (PushbackReader) reader; Object o = read(r, true, null, true); if(o instanceof Symbol) { return RT.classForName(o.toString()); } else if(o instanceof IPersistentList) { Symbol fs = (Symbol) RT.first(o); if(fs.equals(THE_VAR)) { Symbol vs = (Symbol) RT.second(o); return RT.var(vs.ns, vs.name); //Compiler.resolve((Symbol) RT.second(o),true); } if(fs.name.endsWith(".")) { Object[] args = RT.toArray(RT.next(o)); return Reflector.invokeConstructor(RT.classForName(fs.name.substring(0, fs.name.length() - 1)), args); } if(Compiler.namesStaticMember(fs)) { Object[] args = RT.toArray(RT.next(o)); return Reflector.invokeStaticMethod(fs.ns, fs.name, args); } Object v = Compiler.maybeResolveIn(Compiler.currentNS(), fs); if(v instanceof Var) { return ((IFn) v).applyTo(RT.next(o)); } throw Util.runtimeException("Can't resolve " + fs); } else throw new IllegalArgumentException("Unsupported #= form"); } } //static class ArgVectorReader extends AFn{ // public Object invoke(Object reader, Object leftparen) { // PushbackReader r = (PushbackReader) reader; // return ArgVector.create(readDelimitedList('|', r, true)); // } // //} public static class VectorReader extends AFn{ public Object invoke(Object reader, Object leftparen) { PushbackReader r = (PushbackReader) reader; return LazilyPersistentVector.create(readDelimitedList(']', r, true)); } } public static class MapReader extends AFn{ public Object invoke(Object reader, Object leftparen) { PushbackReader r = (PushbackReader) reader; Object[] a = readDelimitedList('}', r, true).toArray(); if((a.length & 1) == 1) throw Util.runtimeException("Map literal must contain an even number of forms"); return RT.map(a); } } public static class SetReader extends AFn{ public Object invoke(Object reader, Object leftbracket) { PushbackReader r = (PushbackReader) reader; return PersistentHashSet.createWithCheck(readDelimitedList('}', r, true)); } } public static class UnmatchedDelimiterReader extends AFn{ public Object invoke(Object reader, Object rightdelim) { throw Util.runtimeException("Unmatched delimiter: " + rightdelim); } } public static class UnreadableReader extends AFn{ public Object invoke(Object reader, Object leftangle) { throw Util.runtimeException("Unreadable form"); } } public static List readDelimitedList(char delim, PushbackReader r, boolean isRecursive) { final int firstline = (r instanceof LineNumberingPushbackReader) ? ((LineNumberingPushbackReader) r).getLineNumber() : -1; ArrayList a = new ArrayList(); for(; ;) { int ch = read1(r); while(isWhitespace(ch)) ch = read1(r); if(ch == -1) { if(firstline < 0) throw Util.runtimeException("EOF while reading"); else throw Util.runtimeException("EOF while reading, starting at line " + firstline); } if(ch == delim) break; IFn macroFn = getMacro(ch); if(macroFn != null) { Object mret = macroFn.invoke(r, (char) ch); //no op macros return the reader if(mret != r) a.add(mret); } else { unread(r, ch); Object o = read(r, true, null, isRecursive); if(o != r) a.add(o); } } return a; } public static class CtorReader extends AFn{ public Object invoke(Object reader, Object firstChar){ PushbackReader r = (PushbackReader) reader; Object name = read(r, true, null, false); if (!(name instanceof Symbol)) throw new RuntimeException("Reader tag must be a symbol"); Symbol sym = (Symbol)name; return sym.getName().contains(".") ? readRecord(r, sym) : readTagged(r, sym); } private Object readTagged(PushbackReader reader, Symbol tag){ Object o = read(reader, true, null, true); ILookup data_readers = (ILookup)RT.DATA_READERS.deref(); IFn data_reader = (IFn)RT.get(data_readers, tag); if(data_reader == null){ data_readers = (ILookup)RT.DEFAULT_DATA_READERS.deref(); data_reader = (IFn)RT.get(data_readers, tag); if(data_reader == null) throw new RuntimeException("No reader function for tag " + tag.toString()); } return data_reader.invoke(o); } private Object readRecord(PushbackReader r, Symbol recordName){ Class recordClass = RT.classForName(recordName.toString()); char endch; boolean shortForm = true; int ch = read1(r); // flush whitespace //while(isWhitespace(ch)) // ch = read1(r); // A defrecord ctor can take two forms. Check for map->R version first. if(ch == '{') { endch = '}'; shortForm = false; } else if (ch == '[') endch = ']'; else throw Util.runtimeException("Unreadable constructor form starting with \"#" + recordName + (char) ch + "\""); Object[] recordEntries = readDelimitedList(endch, r, true).toArray(); Object ret = null; Constructor[] allctors = ((Class)recordClass).getConstructors(); if(shortForm) { boolean ctorFound = false; for (Constructor ctor : allctors) if(ctor.getParameterTypes().length == recordEntries.length) ctorFound = true; if(!ctorFound) throw Util.runtimeException("Unexpected number of constructor arguments to " + recordClass.toString() + ": got " + recordEntries.length); ret = Reflector.invokeConstructor(recordClass, recordEntries); } else { IPersistentMap vals = RT.map(recordEntries); for(ISeq s = RT.keys(vals); s != null; s = s.next()) { if(!(s.first() instanceof Keyword)) throw Util.runtimeException("Unreadable defrecord form: key must be of type clojure.lang.Keyword, got " + s.first().toString()); } ret = Reflector.invokeStaticMethod(recordClass, "create", new Object[]{vals}); } return ret; } } /* public static void main(String[] args) throws Exception{ //RT.init(); PushbackReader rdr = new PushbackReader( new java.io.StringReader( "(+ 21 21)" ) ); Object input = LispReader.read(rdr, false, new Object(), false ); System.out.println(Compiler.eval(input)); } public static void main(String[] args){ LineNumberingPushbackReader r = new LineNumberingPushbackReader(new InputStreamReader(System.in)); OutputStreamWriter w = new OutputStreamWriter(System.out); Object ret = null; try { for(; ;) { ret = LispReader.read(r, true, null, false); RT.print(ret, w); w.write('\n'); if(ret != null) w.write(ret.getClass().toString()); w.write('\n'); w.flush(); } } catch(Exception e) { e.printStackTrace(); } } */ }
true
true
static Object syntaxQuote(Object form) { Object ret; if(Compiler.isSpecial(form)) ret = RT.list(Compiler.QUOTE, form); else if(form instanceof Symbol) { Symbol sym = (Symbol) form; if(sym.ns == null && sym.name.endsWith("#")) { IPersistentMap gmap = (IPersistentMap) GENSYM_ENV.deref(); if(gmap == null) throw new IllegalStateException("Gensym literal not in syntax-quote"); Symbol gs = (Symbol) gmap.valAt(sym); if(gs == null) GENSYM_ENV.set(gmap.assoc(sym, gs = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1) + "__" + RT.nextID() + "__auto__"))); sym = gs; } else if(sym.ns == null && sym.name.endsWith(".")) { Symbol csym = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1)); csym = Compiler.resolveSymbol(csym); sym = Symbol.intern(null, csym.name.concat(".")); } else if(sym.ns == null && sym.name.startsWith(".")) { // Simply quote method names. } else { Object maybeClass = null; if(sym.ns != null) maybeClass = Compiler.currentNS().getMapping( Symbol.intern(null, sym.ns)); if(maybeClass instanceof Class) { // Classname/foo -> package.qualified.Classname/foo sym = Symbol.intern( ((Class)maybeClass).getName(), sym.name); } else sym = Compiler.resolveSymbol(sym); } ret = RT.list(Compiler.QUOTE, sym); } else if(isUnquote(form)) return RT.second(form); else if(isUnquoteSplicing(form)) throw new IllegalStateException("splice not in list"); else if(form instanceof IPersistentCollection) { if(form instanceof IPersistentMap) { IPersistentVector keyvals = flattenMap(form); ret = RT.list(APPLY, HASHMAP, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(keyvals.seq())))); } else if(form instanceof IPersistentVector) { ret = RT.list(APPLY, VECTOR, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentVector) form).seq())))); } else if(form instanceof IPersistentSet) { ret = RT.list(APPLY, HASHSET, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentSet) form).seq())))); } else if(form instanceof ISeq || form instanceof IPersistentList) { ISeq seq = RT.seq(form); if(seq == null) ret = RT.cons(LIST,null); else ret = RT.list(SEQ, RT.cons(CONCAT, sqExpandList(seq))); } else throw new UnsupportedOperationException("Unknown Collection type"); } else if(form instanceof Keyword || form instanceof Number || form instanceof Character || form instanceof String) ret = form; else ret = RT.list(Compiler.QUOTE, form); if(form instanceof IObj && RT.meta(form) != null) { //filter line numbers IPersistentMap newMeta = ((IObj) form).meta().without(RT.LINE_KEY); if(newMeta.count() > 0) return RT.list(WITH_META, ret, syntaxQuote(((IObj) form).meta())); } return ret; }
static Object syntaxQuote(Object form) { Object ret; if(Compiler.isSpecial(form)) ret = RT.list(Compiler.QUOTE, form); else if(form instanceof Symbol) { Symbol sym = (Symbol) form; if(sym.ns == null && sym.name.endsWith("#")) { IPersistentMap gmap = (IPersistentMap) GENSYM_ENV.deref(); if(gmap == null) throw new IllegalStateException("Gensym literal not in syntax-quote"); Symbol gs = (Symbol) gmap.valAt(sym); if(gs == null) GENSYM_ENV.set(gmap.assoc(sym, gs = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1) + "__" + RT.nextID() + "__auto__"))); sym = gs; } else if(sym.ns == null && sym.name.endsWith(".")) { Symbol csym = Symbol.intern(null, sym.name.substring(0, sym.name.length() - 1)); csym = Compiler.resolveSymbol(csym); sym = Symbol.intern(null, csym.name.concat(".")); } else if(sym.ns == null && sym.name.startsWith(".")) { // Simply quote method names. } else { Object maybeClass = null; if(sym.ns != null) maybeClass = Compiler.currentNS().getMapping( Symbol.intern(null, sym.ns)); if(maybeClass instanceof Class) { // Classname/foo -> package.qualified.Classname/foo sym = Symbol.intern( ((Class)maybeClass).getName(), sym.name); } else sym = Compiler.resolveSymbol(sym); } ret = RT.list(Compiler.QUOTE, sym); } else if(isUnquote(form)) return RT.second(form); else if(isUnquoteSplicing(form)) throw new IllegalStateException("splice not in list"); else if(form instanceof IPersistentCollection) { if(form instanceof IRecord) ret = form; else if(form instanceof IPersistentMap) { IPersistentVector keyvals = flattenMap(form); ret = RT.list(APPLY, HASHMAP, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(keyvals.seq())))); } else if(form instanceof IPersistentVector) { ret = RT.list(APPLY, VECTOR, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentVector) form).seq())))); } else if(form instanceof IPersistentSet) { ret = RT.list(APPLY, HASHSET, RT.list(SEQ, RT.cons(CONCAT, sqExpandList(((IPersistentSet) form).seq())))); } else if(form instanceof ISeq || form instanceof IPersistentList) { ISeq seq = RT.seq(form); if(seq == null) ret = RT.cons(LIST,null); else ret = RT.list(SEQ, RT.cons(CONCAT, sqExpandList(seq))); } else throw new UnsupportedOperationException("Unknown Collection type"); } else if(form instanceof Keyword || form instanceof Number || form instanceof Character || form instanceof String) ret = form; else ret = RT.list(Compiler.QUOTE, form); if(form instanceof IObj && RT.meta(form) != null) { //filter line numbers IPersistentMap newMeta = ((IObj) form).meta().without(RT.LINE_KEY); if(newMeta.count() > 0) return RT.list(WITH_META, ret, syntaxQuote(((IObj) form).meta())); } return ret; }
diff --git a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/rpc/flattening/helpers/ExceptionHelper.java b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/rpc/flattening/helpers/ExceptionHelper.java index 086532950..38ddf64ef 100644 --- a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/rpc/flattening/helpers/ExceptionHelper.java +++ b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/rpc/flattening/helpers/ExceptionHelper.java @@ -1,47 +1,50 @@ /* * Copyright 2011 Diamond Light Source Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.diamond.scisoft.analysis.rpc.flattening.helpers; import java.util.Map; import uk.ac.diamond.scisoft.analysis.rpc.flattening.IRootFlattener; public class ExceptionHelper extends MapFlatteningHelper<Exception> { public ExceptionHelper() { super(Exception.class); } @Override public Exception unflatten(Map<?, ?> thisMap, IRootFlattener rootFlattener) { String all = (String) thisMap.get(CONTENT); int i = all.lastIndexOf(": "); + if (i < 0) { + return new Exception(all); + } String msg = all.substring(i+2).trim(); all = all.substring(0, i); i = all.lastIndexOf('\n'); return i < 0 ? new Exception(msg) : new Exception(msg, new Exception(all.substring(0, i))); } @Override public Object flatten(Object obj, IRootFlattener rootFlattener) { Exception thisException = (Exception) obj; Map<String, Object> outMap = createMap(getTypeCanonicalName()); outMap.put(CONTENT, thisException.getLocalizedMessage()); return outMap; } }
true
true
public Exception unflatten(Map<?, ?> thisMap, IRootFlattener rootFlattener) { String all = (String) thisMap.get(CONTENT); int i = all.lastIndexOf(": "); String msg = all.substring(i+2).trim(); all = all.substring(0, i); i = all.lastIndexOf('\n'); return i < 0 ? new Exception(msg) : new Exception(msg, new Exception(all.substring(0, i))); }
public Exception unflatten(Map<?, ?> thisMap, IRootFlattener rootFlattener) { String all = (String) thisMap.get(CONTENT); int i = all.lastIndexOf(": "); if (i < 0) { return new Exception(all); } String msg = all.substring(i+2).trim(); all = all.substring(0, i); i = all.lastIndexOf('\n'); return i < 0 ? new Exception(msg) : new Exception(msg, new Exception(all.substring(0, i))); }
diff --git a/modular-pircbot-modules/src/main/java/org/jibble/pircbot/modules/AuthModePircModule.java b/modular-pircbot-modules/src/main/java/org/jibble/pircbot/modules/AuthModePircModule.java index c611c79..467c470 100644 --- a/modular-pircbot-modules/src/main/java/org/jibble/pircbot/modules/AuthModePircModule.java +++ b/modular-pircbot-modules/src/main/java/org/jibble/pircbot/modules/AuthModePircModule.java @@ -1,43 +1,43 @@ package org.jibble.pircbot.modules; import org.apache.commons.lang3.StringUtils; import org.jibble.pircbot.ExtendedPircBot; /** * Automatically executes the <tt>AUTH</tt> and <tt>MODE</tt> commands when the * bot connects to the server. * * @author Emmanuel Cron */ public class AuthModePircModule extends AbstractPircModule { private String authUsername; private String authPassword; private String modes; /** * Creates a new AUTH/MODE module. * * @param authUsername the user name to user in the <tt>AUTH</tt> command * @param authPassword the password to user in the <tt>AUTH</tt> command * @param modes the modes to request with the <tt>MODE</tt> command; if no * particular mode needs to be requested, this parameter can be * <tt>null</tt> or empty */ public AuthModePircModule(String authUsername, String authPassword, String modes) { this.authUsername = authUsername; this.authPassword = authPassword; this.modes = modes; } @Override public void onConnect(ExtendedPircBot bot) { bot.sendRawLineViaQueue("auth " + authUsername + " " + authPassword); if (StringUtils.isNotBlank(modes)) { - bot.sendRawLineViaQueue("mode " + bot.getNick() + " +x"); + bot.sendRawLineViaQueue("mode " + bot.getNick() + modes); } } }
true
true
public void onConnect(ExtendedPircBot bot) { bot.sendRawLineViaQueue("auth " + authUsername + " " + authPassword); if (StringUtils.isNotBlank(modes)) { bot.sendRawLineViaQueue("mode " + bot.getNick() + " +x"); } }
public void onConnect(ExtendedPircBot bot) { bot.sendRawLineViaQueue("auth " + authUsername + " " + authPassword); if (StringUtils.isNotBlank(modes)) { bot.sendRawLineViaQueue("mode " + bot.getNick() + modes); } }
diff --git a/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java b/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java index dadadef2..e421dc8f 100644 --- a/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java +++ b/java/de/hattrickorganizer/gui/transferscout/PlayerConverter.java @@ -1,865 +1,856 @@ // %1329240092:de.hattrickorganizer.gui.transferscout% package de.hattrickorganizer.gui.transferscout; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import de.hattrickorganizer.model.HOVerwaltung; /** * Parses a player out of a text copied from HT. Tries also to give error informations but this may * be wrong! * * @author Marco Senn */ public class PlayerConverter { //~ Instance fields ---------------------------------------------------------------------------- /** List of all 21 ratings for the active language */ private List<String> skills; private List<Integer> skillvalues; private List<String> specialities; private List<Integer> specialitiesvalues; private int error; final HOVerwaltung homodel = HOVerwaltung.instance(); //~ Constructors ------------------------------------------------------------------------------- /** * We prepare our skill and specialities and sort them */ public PlayerConverter() { // Get all skills for active language // This should be the same language as in Hattrick skills = new ArrayList<String>(); skills.add(homodel.getLanguageString("nonexisting").toLowerCase()); skills.add(homodel.getLanguageString("katastrophal").toLowerCase()); skills.add(homodel.getLanguageString("erbaermlich").toLowerCase()); skills.add(homodel.getLanguageString("armselig").toLowerCase()); skills.add(homodel.getLanguageString("schwach").toLowerCase()); skills.add(homodel.getLanguageString("durchschnittlich").toLowerCase()); skills.add(homodel.getLanguageString("passabel").toLowerCase()); skills.add(homodel.getLanguageString("gut").toLowerCase()); skills.add(homodel.getLanguageString("sehr_gut").toLowerCase()); skills.add(homodel.getLanguageString("hervorragend").toLowerCase()); skills.add(homodel.getLanguageString("grossartig").toLowerCase()); skills.add(homodel.getLanguageString("brilliant").toLowerCase()); skills.add(homodel.getLanguageString("fantastisch").toLowerCase()); skills.add(homodel.getLanguageString("Weltklasse").toLowerCase()); skills.add(homodel.getLanguageString("uebernatuerlich").toLowerCase()); skills.add(homodel.getLanguageString("gigantisch").toLowerCase()); skills.add(homodel.getLanguageString("ausserirdisch").toLowerCase()); skills.add(homodel.getLanguageString("mythisch").toLowerCase()); skills.add(homodel.getLanguageString("maerchenhaft").toLowerCase()); skills.add(homodel.getLanguageString("galaktisch").toLowerCase()); skills.add(homodel.getLanguageString("goettlich").toLowerCase()); skillvalues = new ArrayList<Integer>(); for (int k = 0; k < skills.size(); k++) { skillvalues.add(new Integer(k)); } // Sort skills by length (shortest first) int p = skills.size() - 1; while (p > 0) { int k = p; while ((k < skills.size()) && (skills.get(k - 1).toString().length() > skills.get(k).toString().length())) { final String t = skills.get(k - 1).toString(); skills.set(k - 1, skills.get(k).toString()); skills.set(k, t); final Integer i = (Integer) skillvalues.get(k - 1); skillvalues.set(k - 1, (Integer) skillvalues.get(k)); skillvalues.set(k, i); k++; } p--; } // Get all specialities for active language // This should be the same language as in Hattrick specialities = new ArrayList<String>(); specialities.add(homodel.getLanguageString("sp_Technical").toLowerCase()); specialities.add(homodel.getLanguageString("sp_Quick").toLowerCase()); specialities.add(homodel.getLanguageString("sp_Powerful").toLowerCase()); specialities.add(homodel.getLanguageString("sp_Unpredictable").toLowerCase()); specialities.add(homodel.getLanguageString("sp_Head").toLowerCase()); specialities.add(homodel.getLanguageString("sp_Regainer").toLowerCase()); specialitiesvalues = new ArrayList<Integer>(); for (int k = 0; k < 6; k++) { specialitiesvalues.add(new Integer(k)); } // Sort specialities by length (shortest first) p = specialities.size() - 1; while (p > 0) { int k = p; while ((k < specialities.size()) && (specialities.get(k - 1).toString().length() > specialities.get(k).toString() .length())) { final String t = specialities.get(k - 1).toString(); specialities.set(k - 1, specialities.get(k).toString()); specialities.set(k, t); final Integer i = (Integer) specialitiesvalues.get(k - 1); specialitiesvalues.set(k - 1, (Integer) specialitiesvalues.get(k)); specialitiesvalues.set(k, i); k++; } p--; } } //~ Methods ------------------------------------------------------------------------------------ /** * Returns possible error. If error is nonzero, there was a problem. * * @return Returns possible error */ public final int getError() { return error; } /** * Parses the copied text and returns a Player Object * * @param text the copied text from HT site * * @return Player a Player object * * @throws Exception Throws exception on some parse errors */ public final Player build(String text) throws Exception { error = 0; final Player player = new Player(); // Init some helper variables String mytext = text; final List<String> lines = new ArrayList<String>(); int p = -1; String tmp = ""; // Detect linefeed // \n will do for linux and windows // \r is for mac String feed = ""; if (text.indexOf("\n") >= 0) { feed = "\n"; } else { if (text.indexOf("\r") >= 0) { feed = "\r"; } } // If we detected some possible player if (!feed.equals("")) { // // We start reformating given input here and extracting // only needed lines for player detection // // Delete empty lines from input String txt = text; boolean startFound = false; while ((p = txt.indexOf(feed)) >= 0) { tmp = txt.substring(0, p).trim(); if (tmp.indexOf("»") > 0) { startFound = true; } if (!tmp.equals("") && startFound) { lines.add(tmp); } txt = txt.substring(p + 1); } //-- get name and store club name tmp = lines.get(0).toString(); player.setPlayerName(tmp.substring(tmp.indexOf("»")+1).trim()); String teamname = tmp.substring(0, tmp.indexOf("»")).trim(); //-- get playerid int found_at_line = -1; int n = 0; for (int m = 0; m<10; m++) { tmp = lines.get(m).toString(); try { - if ((p = tmp.indexOf("(")) > -1 && (n = tmp.indexOf(")")) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim()) > 100000) { - player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim())); + // Players from China etc. have Brackets in their names!!! + // Therefore we need lastIndexOf + // This also deals with player categories + if ((p = tmp.indexOf("(")) > -1 && (n = tmp.indexOf(")")) > -1 && Integer.parseInt(tmp.substring(tmp.lastIndexOf("(")+1, tmp.lastIndexOf(")")).trim()) > 100000) { + player.setPlayerID(Integer.parseInt(tmp.substring(tmp.lastIndexOf("(")+1, tmp.lastIndexOf(")")).trim())); found_at_line = m; break; } } catch (Exception e) { if (p < 0) continue; } - try { - // handle categories: Player Name (TW) (123456789) - if (tmp.indexOf("(", p+1) > -1 && tmp.indexOf(")", n+1) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim()) > 100000) { - player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim())); - found_at_line = m; - break; - } - } catch (Exception e) { - continue; - } } //-- get age tmp = lines.get(found_at_line + 1).toString(); String age = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { age = age + tmp.charAt(p); } else { break; } p++; } if (!age.equals("")) { player.setAge(Integer.valueOf(age).intValue()); } else { error = 2; } //-- get ageDays int ageIndex = tmp.indexOf(age) + age.length(); tmp = tmp.substring(ageIndex); String ageDays = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { ageDays = ageDays + tmp.charAt(p); } else { break; } p++; } if (!ageDays.equals("")) { player.setAgeDays(Integer.valueOf(ageDays).intValue()); } else { error = 2; } // clean lines till here if (found_at_line > 0) { for (int m=0; m<=(found_at_line+1); m++) { lines.remove(0); } } // remove club line and all lines until the time info (e.g. "since 06.04.2008") boolean teamfound = false; boolean datefound = false; for (int m = 0; m<12; m++) { tmp = lines.get(m).toString(); if (tmp.indexOf(teamname)>-1) { teamfound = true; } if (teamfound && !datefound) { lines.remove(m); m--; } if (teamfound && tmp.indexOf("(")>-1 && tmp.indexOf(")")>-1) { datefound = true; break; } } // Extract TSI-line p = 2; while (p < lines.size()) { //Search for TSI-line (ending in numbers) tmp = lines.get(p).toString(); if ((tmp.charAt(tmp.length() - 1) >= '0') && (tmp.charAt(tmp.length() - 1) <= '9') ) { if (tmp.length()>9 && tmp.substring(tmp.length()-9, tmp.length()).indexOf(".")>-1) { p++; continue; } found_at_line = p; break; } p++; } //-- get tsi String tsi = ""; p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { tsi = tsi + tmp.charAt(p); } p++; } if (!tsi.equals("")) { player.setTSI(Integer.valueOf(tsi).intValue()); } else { error = 2; } //-- check for line wage / season (since FoxTrick 0.4.8.2) String wage = ""; p = 0; tmp = lines.get(found_at_line+2).toString(); //extract spaces tmp = tmp.replace(" ",""); //get first number while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { break; } p++; } //stop after first non-number while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { wage += tmp.charAt(p); } else break; p++; } if (!wage.equals("") && Integer.parseInt(wage) >= 500) { found_at_line++; - } else { - error = 2; } //-- check bookings tmp = lines.get(found_at_line+2).toString(); try { if (tmp.indexOf(":") > -1 && tmp.indexOf("0") == -1) { player.setBooked(tmp); } } catch (Exception e) { /* ignore */ } //-- Get injury tmp = lines.get(found_at_line+3).toString(); try { String injury = ""; for (int j = 0; j < tmp.length(); j++) { if ((tmp.charAt(j) >= '0') && (tmp.charAt(j) <= '9') && (tmp.charAt(j-1) != '[')) { injury = String.valueOf(tmp.charAt(j)); break; } } if (!injury.equals("")) { player.setInjury(Integer.valueOf(injury).intValue()); } } catch (Exception e) { /* ignore */ } // Search for actual year (expires) and also next year // (end of year problem) final Date d = new Date(); SimpleDateFormat f = new SimpleDateFormat("yyyy"); final String year = f.format(d); final String year2 = String.valueOf((Integer.parseInt(year)+1)); p = 0; for (int m = 6; m < 8; m++) { // Delete all rows not containing our year tmp = lines.get(m).toString(); if (p > 10) { // already 10 lines deleted - there must be something wrong, break break; } if ((tmp.indexOf(year) > -1) || (tmp.indexOf(year2) > -1)) { found_at_line = m; break; } else { lines.remove(m); m--; p++; } } String exp = getDeadlineString(tmp); // Extract minimal bid tmp = lines.get(found_at_line+1).toString(); n = 0; int k = 0; String bid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { bid += tmp.charAt(k); } k++; } // Extract current bid if any tmp = lines.get(found_at_line + 2).toString(); n = 0; k = 0; String curbid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { curbid += tmp.charAt(k); } else if ((tmp.charAt(k) != ' ') && curbid.length()>0) { // avoid to add numbers from bidding team names break; } k++; } player.setPrice(getPrice(bid, curbid)); //-------------------------------------------- // exp is of format: ddmmyyyyhhmm try { player.setExpiryDate(exp.substring(0, 2) + "." + exp.substring(2, 4) + "." + exp.substring(6, 8)); player.setExpiryTime(exp.substring(8, 10) + ":" + exp.substring(10, 12)); } catch (RuntimeException e) { // error getting deadline - just set current date f = new SimpleDateFormat("dd.MM.yyyy"); player.setExpiryDate(f.format(new Date())); f = new SimpleDateFormat("HH:mm"); player.setExpiryTime(f.format(new Date())); if (error == 0) { error = 1; } } // truncate text from player name to date (year) final String name = player.getPlayerName(); if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p + name.length()); } if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p); } char[] cs = new char[teamname.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(teamname, new String(cs)).toLowerCase(); cs = new char[name.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(name.toLowerCase(), new String(cs)).toLowerCase(); // We can search all the skills in text now p = skills.size() - 1; final List<List<Object>> foundskills = new ArrayList<List<Object>>(); while (p >= 0) { final String singleskill = skills.get(p).toString(); k = mytext.indexOf(singleskill); if (k >= 0) { final List<Object> pair = new ArrayList<Object>(); pair.add(new Integer(k)); pair.add(singleskill); pair.add(new Integer(p)); foundskills.add(pair); final char[] ct = new char[singleskill.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singleskill, new String(ct)); } else { p--; } } if ((foundskills.size() < 11) && (error == 0)) { error = 1; } // Sort skills by location p = foundskills.size() - 1; while (p > 0) { k = p; while (k < foundskills.size()) { final List<Object> ts1 = foundskills.get(k - 1); final List<Object> ts2 = foundskills.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundskills.set(k - 1, ts2); foundskills.set(k, ts1); k++; } else { break; } } p--; } // check format try { p = mytext.indexOf("/20"); if (p > -1 && mytext.indexOf("/20", p+5) > -1 && foundskills.size() >= 11) { setSkillsBarStyle(player, foundskills); } else if (foundskills.size() >= 12) { setSkillsClassicStyle(player, foundskills); } else if (foundskills.size() == 11) { // no "20" in the text, but 11 skills (e.g. IE6) setSkillsBarStyle(player, foundskills); } } catch (Exception e) { error = 2; } // We can search the speciality in text now p = specialities.size() - 1; final List<List<Object>> foundspecialities = new ArrayList<List<Object>>(); while (p >= 0) { final String singlespeciality = specialities.get(p).toString(); k = mytext.indexOf(singlespeciality); if (k >= 0) { final List<Object> pair = new ArrayList<Object>(); pair.add(new Integer(k)); pair.add(singlespeciality); pair.add(new Integer(p)); foundspecialities.add(pair); final char[] ct = new char[singlespeciality.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singlespeciality, new String(ct)); } else { p--; } } if ((foundspecialities.size() > 1) && (error == 0)) { error = 1; } // Sort specialities by location p = foundspecialities.size() - 1; while (p > 0) { k = p; while (k < foundspecialities.size()) { final List<Object> ts1 = foundspecialities.get(k - 1); final List<Object> ts2 = foundspecialities.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundspecialities.set(k - 1, ts2); foundspecialities.set(k, ts1); k++; } else { break; } } p--; } if (foundspecialities.size() > 0) { player.setSpeciality(((Integer) specialitiesvalues.get(((Integer) (foundspecialities.get(0)).get(2)).intValue())).intValue() + 1); } else { player.setSpeciality(0); } } return player; } /** * Set parsed skills in the player object. Bar style. */ private void setSkillsBarStyle(Player player, final List<List<Object>> foundskills) throws Exception { // player skills (long default format with bars) player.setForm(((Integer) skillvalues.get(((Integer) (foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) (foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) (foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) (foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) (foundskills.get(4)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) (foundskills.get(5)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) (foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) (foundskills.get(7)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) (foundskills.get(8)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) (foundskills.get(9)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) (foundskills.get(10)).get(2)).intValue())).intValue()); } /** * Set parsed skills in the player object. Classic style with 2 skills per line. */ private void setSkillsClassicStyle(Player player, final List<List<Object>> foundskills) throws Exception { // player skills (2er format without bars) player.setForm(((Integer) skillvalues.get(((Integer) (foundskills.get(0)).get(2)).intValue())).intValue()); player.setStamina(((Integer) skillvalues.get(((Integer) (foundskills.get(1)).get(2)).intValue())).intValue()); player.setExperience(((Integer) skillvalues.get(((Integer) (foundskills.get(2)).get(2)).intValue())).intValue()); player.setLeadership(((Integer) skillvalues.get(((Integer) (foundskills.get(3)).get(2)).intValue())).intValue()); player.setGoalKeeping(((Integer) skillvalues.get(((Integer) (foundskills.get(5)).get(2)).intValue())).intValue()); player.setDefense(((Integer) skillvalues.get(((Integer) (foundskills.get(9)).get(2)).intValue())).intValue()); player.setPlayMaking(((Integer) skillvalues.get(((Integer) (foundskills.get(6)).get(2)).intValue())).intValue()); player.setWing(((Integer) skillvalues.get(((Integer) (foundskills.get(8)).get(2)).intValue())).intValue()); player.setPassing(((Integer) skillvalues.get(((Integer) (foundskills.get(7)).get(2)).intValue())).intValue()); player.setAttack(((Integer) skillvalues.get(((Integer) (foundskills.get(10)).get(2)).intValue())).intValue()); player.setSetPieces(((Integer) skillvalues.get(((Integer) (foundskills.get(11)).get(2)).intValue())).intValue()); } public static int getPrice(String bid, String curbid) { int price = 0; try { price = Integer.parseInt(bid); if (curbid.length()>0 && Integer.parseInt(curbid) >= Integer.parseInt(bid)) { price = Integer.parseInt(curbid); } } catch (Exception e) { /* nothing */ } return price; } public static String getDeadlineString(String tmp) { // get deadline String exp = ""; int p = 0; int k = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { k++; } else { tmp = tmp.substring(k); break; } p++; } p = 0; k = 0; String part1 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { k++; } else { part1 = tmp.substring(0, k); if (part1.length() < 2) { part1 = "0" + part1; } tmp = tmp.substring(k + 1); break; } p++; } p = 0; k = 0; String part2 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { k++; } else { part2 = tmp.substring(0, k); if (part2.length() < 2) { part2 = "0" + part2; } tmp = tmp.substring(k + 1); break; } p++; } p = 0; k = 0; String part3 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { k++; } else { part3 = tmp.substring(0, k); if (part3.length() < 2) { part3 = "0" + part3; } tmp = tmp.substring(k + 1); break; } p++; } p = 0; String part4 = ""; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { part4 = part4 + tmp.charAt(p); } p++; } final Calendar c = Calendar.getInstance(); SimpleDateFormat f = new SimpleDateFormat("ddMMyyyy"); final Date d1 = c.getTime(); final String date1 = f.format(d1); c.add(Calendar.DATE, 1); final Date d2 = c.getTime(); final String date2 = f.format(d2); c.add(Calendar.DATE, 1); final Date d3 = c.getTime(); final String date3 = f.format(d3); String date = part1 + part2 + part3; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part1 + part3 + part2; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part2 + part1 + part3; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part2 + part3 + part1; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part3 + part1 + part2; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { date = part3 + part2 + part1; if ((date1.equals(date)) || (date2.equals(date)) || (date3.equals(date))) { exp = date + part4; } else { exp = part1 + part2 + part3 + part4; } } } } } } return exp; } }
false
true
public final Player build(String text) throws Exception { error = 0; final Player player = new Player(); // Init some helper variables String mytext = text; final List<String> lines = new ArrayList<String>(); int p = -1; String tmp = ""; // Detect linefeed // \n will do for linux and windows // \r is for mac String feed = ""; if (text.indexOf("\n") >= 0) { feed = "\n"; } else { if (text.indexOf("\r") >= 0) { feed = "\r"; } } // If we detected some possible player if (!feed.equals("")) { // // We start reformating given input here and extracting // only needed lines for player detection // // Delete empty lines from input String txt = text; boolean startFound = false; while ((p = txt.indexOf(feed)) >= 0) { tmp = txt.substring(0, p).trim(); if (tmp.indexOf("»") > 0) { startFound = true; } if (!tmp.equals("") && startFound) { lines.add(tmp); } txt = txt.substring(p + 1); } //-- get name and store club name tmp = lines.get(0).toString(); player.setPlayerName(tmp.substring(tmp.indexOf("»")+1).trim()); String teamname = tmp.substring(0, tmp.indexOf("»")).trim(); //-- get playerid int found_at_line = -1; int n = 0; for (int m = 0; m<10; m++) { tmp = lines.get(m).toString(); try { if ((p = tmp.indexOf("(")) > -1 && (n = tmp.indexOf(")")) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim()) > 100000) { player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(")+1, tmp.indexOf(")")).trim())); found_at_line = m; break; } } catch (Exception e) { if (p < 0) continue; } try { // handle categories: Player Name (TW) (123456789) if (tmp.indexOf("(", p+1) > -1 && tmp.indexOf(")", n+1) > -1 && Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim()) > 100000) { player.setPlayerID(Integer.parseInt(tmp.substring(tmp.indexOf("(", p+1)+1, tmp.indexOf(")", n+1)).trim())); found_at_line = m; break; } } catch (Exception e) { continue; } } //-- get age tmp = lines.get(found_at_line + 1).toString(); String age = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { age = age + tmp.charAt(p); } else { break; } p++; } if (!age.equals("")) { player.setAge(Integer.valueOf(age).intValue()); } else { error = 2; } //-- get ageDays int ageIndex = tmp.indexOf(age) + age.length(); tmp = tmp.substring(ageIndex); String ageDays = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { ageDays = ageDays + tmp.charAt(p); } else { break; } p++; } if (!ageDays.equals("")) { player.setAgeDays(Integer.valueOf(ageDays).intValue()); } else { error = 2; } // clean lines till here if (found_at_line > 0) { for (int m=0; m<=(found_at_line+1); m++) { lines.remove(0); } } // remove club line and all lines until the time info (e.g. "since 06.04.2008") boolean teamfound = false; boolean datefound = false; for (int m = 0; m<12; m++) { tmp = lines.get(m).toString(); if (tmp.indexOf(teamname)>-1) { teamfound = true; } if (teamfound && !datefound) { lines.remove(m); m--; } if (teamfound && tmp.indexOf("(")>-1 && tmp.indexOf(")")>-1) { datefound = true; break; } } // Extract TSI-line p = 2; while (p < lines.size()) { //Search for TSI-line (ending in numbers) tmp = lines.get(p).toString(); if ((tmp.charAt(tmp.length() - 1) >= '0') && (tmp.charAt(tmp.length() - 1) <= '9') ) { if (tmp.length()>9 && tmp.substring(tmp.length()-9, tmp.length()).indexOf(".")>-1) { p++; continue; } found_at_line = p; break; } p++; } //-- get tsi String tsi = ""; p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { tsi = tsi + tmp.charAt(p); } p++; } if (!tsi.equals("")) { player.setTSI(Integer.valueOf(tsi).intValue()); } else { error = 2; } //-- check for line wage / season (since FoxTrick 0.4.8.2) String wage = ""; p = 0; tmp = lines.get(found_at_line+2).toString(); //extract spaces tmp = tmp.replace(" ",""); //get first number while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { break; } p++; } //stop after first non-number while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { wage += tmp.charAt(p); } else break; p++; } if (!wage.equals("") && Integer.parseInt(wage) >= 500) { found_at_line++; } else { error = 2; } //-- check bookings tmp = lines.get(found_at_line+2).toString(); try { if (tmp.indexOf(":") > -1 && tmp.indexOf("0") == -1) { player.setBooked(tmp); } } catch (Exception e) { /* ignore */ } //-- Get injury tmp = lines.get(found_at_line+3).toString(); try { String injury = ""; for (int j = 0; j < tmp.length(); j++) { if ((tmp.charAt(j) >= '0') && (tmp.charAt(j) <= '9') && (tmp.charAt(j-1) != '[')) { injury = String.valueOf(tmp.charAt(j)); break; } } if (!injury.equals("")) { player.setInjury(Integer.valueOf(injury).intValue()); } } catch (Exception e) { /* ignore */ } // Search for actual year (expires) and also next year // (end of year problem) final Date d = new Date(); SimpleDateFormat f = new SimpleDateFormat("yyyy"); final String year = f.format(d); final String year2 = String.valueOf((Integer.parseInt(year)+1)); p = 0; for (int m = 6; m < 8; m++) { // Delete all rows not containing our year tmp = lines.get(m).toString(); if (p > 10) { // already 10 lines deleted - there must be something wrong, break break; } if ((tmp.indexOf(year) > -1) || (tmp.indexOf(year2) > -1)) { found_at_line = m; break; } else { lines.remove(m); m--; p++; } } String exp = getDeadlineString(tmp); // Extract minimal bid tmp = lines.get(found_at_line+1).toString(); n = 0; int k = 0; String bid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { bid += tmp.charAt(k); } k++; } // Extract current bid if any tmp = lines.get(found_at_line + 2).toString(); n = 0; k = 0; String curbid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { curbid += tmp.charAt(k); } else if ((tmp.charAt(k) != ' ') && curbid.length()>0) { // avoid to add numbers from bidding team names break; } k++; } player.setPrice(getPrice(bid, curbid)); //-------------------------------------------- // exp is of format: ddmmyyyyhhmm try { player.setExpiryDate(exp.substring(0, 2) + "." + exp.substring(2, 4) + "." + exp.substring(6, 8)); player.setExpiryTime(exp.substring(8, 10) + ":" + exp.substring(10, 12)); } catch (RuntimeException e) { // error getting deadline - just set current date f = new SimpleDateFormat("dd.MM.yyyy"); player.setExpiryDate(f.format(new Date())); f = new SimpleDateFormat("HH:mm"); player.setExpiryTime(f.format(new Date())); if (error == 0) { error = 1; } } // truncate text from player name to date (year) final String name = player.getPlayerName(); if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p + name.length()); } if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p); } char[] cs = new char[teamname.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(teamname, new String(cs)).toLowerCase(); cs = new char[name.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(name.toLowerCase(), new String(cs)).toLowerCase(); // We can search all the skills in text now p = skills.size() - 1; final List<List<Object>> foundskills = new ArrayList<List<Object>>(); while (p >= 0) { final String singleskill = skills.get(p).toString(); k = mytext.indexOf(singleskill); if (k >= 0) { final List<Object> pair = new ArrayList<Object>(); pair.add(new Integer(k)); pair.add(singleskill); pair.add(new Integer(p)); foundskills.add(pair); final char[] ct = new char[singleskill.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singleskill, new String(ct)); } else { p--; } } if ((foundskills.size() < 11) && (error == 0)) { error = 1; } // Sort skills by location p = foundskills.size() - 1; while (p > 0) { k = p; while (k < foundskills.size()) { final List<Object> ts1 = foundskills.get(k - 1); final List<Object> ts2 = foundskills.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundskills.set(k - 1, ts2); foundskills.set(k, ts1); k++; } else { break; } } p--; } // check format try { p = mytext.indexOf("/20"); if (p > -1 && mytext.indexOf("/20", p+5) > -1 && foundskills.size() >= 11) { setSkillsBarStyle(player, foundskills); } else if (foundskills.size() >= 12) { setSkillsClassicStyle(player, foundskills); } else if (foundskills.size() == 11) { // no "20" in the text, but 11 skills (e.g. IE6) setSkillsBarStyle(player, foundskills); } } catch (Exception e) { error = 2; } // We can search the speciality in text now p = specialities.size() - 1; final List<List<Object>> foundspecialities = new ArrayList<List<Object>>(); while (p >= 0) { final String singlespeciality = specialities.get(p).toString(); k = mytext.indexOf(singlespeciality); if (k >= 0) { final List<Object> pair = new ArrayList<Object>(); pair.add(new Integer(k)); pair.add(singlespeciality); pair.add(new Integer(p)); foundspecialities.add(pair); final char[] ct = new char[singlespeciality.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singlespeciality, new String(ct)); } else { p--; } } if ((foundspecialities.size() > 1) && (error == 0)) { error = 1; } // Sort specialities by location p = foundspecialities.size() - 1; while (p > 0) { k = p; while (k < foundspecialities.size()) { final List<Object> ts1 = foundspecialities.get(k - 1); final List<Object> ts2 = foundspecialities.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundspecialities.set(k - 1, ts2); foundspecialities.set(k, ts1); k++; } else { break; } } p--; } if (foundspecialities.size() > 0) { player.setSpeciality(((Integer) specialitiesvalues.get(((Integer) (foundspecialities.get(0)).get(2)).intValue())).intValue() + 1); } else { player.setSpeciality(0); } } return player; }
public final Player build(String text) throws Exception { error = 0; final Player player = new Player(); // Init some helper variables String mytext = text; final List<String> lines = new ArrayList<String>(); int p = -1; String tmp = ""; // Detect linefeed // \n will do for linux and windows // \r is for mac String feed = ""; if (text.indexOf("\n") >= 0) { feed = "\n"; } else { if (text.indexOf("\r") >= 0) { feed = "\r"; } } // If we detected some possible player if (!feed.equals("")) { // // We start reformating given input here and extracting // only needed lines for player detection // // Delete empty lines from input String txt = text; boolean startFound = false; while ((p = txt.indexOf(feed)) >= 0) { tmp = txt.substring(0, p).trim(); if (tmp.indexOf("»") > 0) { startFound = true; } if (!tmp.equals("") && startFound) { lines.add(tmp); } txt = txt.substring(p + 1); } //-- get name and store club name tmp = lines.get(0).toString(); player.setPlayerName(tmp.substring(tmp.indexOf("»")+1).trim()); String teamname = tmp.substring(0, tmp.indexOf("»")).trim(); //-- get playerid int found_at_line = -1; int n = 0; for (int m = 0; m<10; m++) { tmp = lines.get(m).toString(); try { // Players from China etc. have Brackets in their names!!! // Therefore we need lastIndexOf // This also deals with player categories if ((p = tmp.indexOf("(")) > -1 && (n = tmp.indexOf(")")) > -1 && Integer.parseInt(tmp.substring(tmp.lastIndexOf("(")+1, tmp.lastIndexOf(")")).trim()) > 100000) { player.setPlayerID(Integer.parseInt(tmp.substring(tmp.lastIndexOf("(")+1, tmp.lastIndexOf(")")).trim())); found_at_line = m; break; } } catch (Exception e) { if (p < 0) continue; } } //-- get age tmp = lines.get(found_at_line + 1).toString(); String age = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { age = age + tmp.charAt(p); } else { break; } p++; } if (!age.equals("")) { player.setAge(Integer.valueOf(age).intValue()); } else { error = 2; } //-- get ageDays int ageIndex = tmp.indexOf(age) + age.length(); tmp = tmp.substring(ageIndex); String ageDays = ""; p = 0; n = 0; while (p < tmp.length()) { if ((tmp.charAt(p) < '0') || (tmp.charAt(p) > '9')) { n++; } else { tmp = tmp.substring(n); break; } p++; } p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { ageDays = ageDays + tmp.charAt(p); } else { break; } p++; } if (!ageDays.equals("")) { player.setAgeDays(Integer.valueOf(ageDays).intValue()); } else { error = 2; } // clean lines till here if (found_at_line > 0) { for (int m=0; m<=(found_at_line+1); m++) { lines.remove(0); } } // remove club line and all lines until the time info (e.g. "since 06.04.2008") boolean teamfound = false; boolean datefound = false; for (int m = 0; m<12; m++) { tmp = lines.get(m).toString(); if (tmp.indexOf(teamname)>-1) { teamfound = true; } if (teamfound && !datefound) { lines.remove(m); m--; } if (teamfound && tmp.indexOf("(")>-1 && tmp.indexOf(")")>-1) { datefound = true; break; } } // Extract TSI-line p = 2; while (p < lines.size()) { //Search for TSI-line (ending in numbers) tmp = lines.get(p).toString(); if ((tmp.charAt(tmp.length() - 1) >= '0') && (tmp.charAt(tmp.length() - 1) <= '9') ) { if (tmp.length()>9 && tmp.substring(tmp.length()-9, tmp.length()).indexOf(".")>-1) { p++; continue; } found_at_line = p; break; } p++; } //-- get tsi String tsi = ""; p = 0; while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { tsi = tsi + tmp.charAt(p); } p++; } if (!tsi.equals("")) { player.setTSI(Integer.valueOf(tsi).intValue()); } else { error = 2; } //-- check for line wage / season (since FoxTrick 0.4.8.2) String wage = ""; p = 0; tmp = lines.get(found_at_line+2).toString(); //extract spaces tmp = tmp.replace(" ",""); //get first number while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { break; } p++; } //stop after first non-number while (p < tmp.length()) { if ((tmp.charAt(p) >= '0') && (tmp.charAt(p) <= '9')) { wage += tmp.charAt(p); } else break; p++; } if (!wage.equals("") && Integer.parseInt(wage) >= 500) { found_at_line++; } //-- check bookings tmp = lines.get(found_at_line+2).toString(); try { if (tmp.indexOf(":") > -1 && tmp.indexOf("0") == -1) { player.setBooked(tmp); } } catch (Exception e) { /* ignore */ } //-- Get injury tmp = lines.get(found_at_line+3).toString(); try { String injury = ""; for (int j = 0; j < tmp.length(); j++) { if ((tmp.charAt(j) >= '0') && (tmp.charAt(j) <= '9') && (tmp.charAt(j-1) != '[')) { injury = String.valueOf(tmp.charAt(j)); break; } } if (!injury.equals("")) { player.setInjury(Integer.valueOf(injury).intValue()); } } catch (Exception e) { /* ignore */ } // Search for actual year (expires) and also next year // (end of year problem) final Date d = new Date(); SimpleDateFormat f = new SimpleDateFormat("yyyy"); final String year = f.format(d); final String year2 = String.valueOf((Integer.parseInt(year)+1)); p = 0; for (int m = 6; m < 8; m++) { // Delete all rows not containing our year tmp = lines.get(m).toString(); if (p > 10) { // already 10 lines deleted - there must be something wrong, break break; } if ((tmp.indexOf(year) > -1) || (tmp.indexOf(year2) > -1)) { found_at_line = m; break; } else { lines.remove(m); m--; p++; } } String exp = getDeadlineString(tmp); // Extract minimal bid tmp = lines.get(found_at_line+1).toString(); n = 0; int k = 0; String bid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { bid += tmp.charAt(k); } k++; } // Extract current bid if any tmp = lines.get(found_at_line + 2).toString(); n = 0; k = 0; String curbid = ""; while (k < tmp.length()) { if ((tmp.charAt(k) < '0') || (tmp.charAt(k) > '9')) { n++; } else { tmp = tmp.substring(n); break; } k++; } k = 0; while (k < tmp.length()) { if ((tmp.charAt(k) >= '0') && (tmp.charAt(k) <= '9')) { curbid += tmp.charAt(k); } else if ((tmp.charAt(k) != ' ') && curbid.length()>0) { // avoid to add numbers from bidding team names break; } k++; } player.setPrice(getPrice(bid, curbid)); //-------------------------------------------- // exp is of format: ddmmyyyyhhmm try { player.setExpiryDate(exp.substring(0, 2) + "." + exp.substring(2, 4) + "." + exp.substring(6, 8)); player.setExpiryTime(exp.substring(8, 10) + ":" + exp.substring(10, 12)); } catch (RuntimeException e) { // error getting deadline - just set current date f = new SimpleDateFormat("dd.MM.yyyy"); player.setExpiryDate(f.format(new Date())); f = new SimpleDateFormat("HH:mm"); player.setExpiryTime(f.format(new Date())); if (error == 0) { error = 1; } } // truncate text from player name to date (year) final String name = player.getPlayerName(); if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p + name.length()); } if ((p = mytext.indexOf(name)) >= 0) { mytext = mytext.substring(p); } char[] cs = new char[teamname.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(teamname, new String(cs)).toLowerCase(); cs = new char[name.length()]; for (int cl = 0; cl < cs.length; cl++) { cs[cl] = '*'; } mytext = mytext.replaceAll(name.toLowerCase(), new String(cs)).toLowerCase(); // We can search all the skills in text now p = skills.size() - 1; final List<List<Object>> foundskills = new ArrayList<List<Object>>(); while (p >= 0) { final String singleskill = skills.get(p).toString(); k = mytext.indexOf(singleskill); if (k >= 0) { final List<Object> pair = new ArrayList<Object>(); pair.add(new Integer(k)); pair.add(singleskill); pair.add(new Integer(p)); foundskills.add(pair); final char[] ct = new char[singleskill.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singleskill, new String(ct)); } else { p--; } } if ((foundskills.size() < 11) && (error == 0)) { error = 1; } // Sort skills by location p = foundskills.size() - 1; while (p > 0) { k = p; while (k < foundskills.size()) { final List<Object> ts1 = foundskills.get(k - 1); final List<Object> ts2 = foundskills.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundskills.set(k - 1, ts2); foundskills.set(k, ts1); k++; } else { break; } } p--; } // check format try { p = mytext.indexOf("/20"); if (p > -1 && mytext.indexOf("/20", p+5) > -1 && foundskills.size() >= 11) { setSkillsBarStyle(player, foundskills); } else if (foundskills.size() >= 12) { setSkillsClassicStyle(player, foundskills); } else if (foundskills.size() == 11) { // no "20" in the text, but 11 skills (e.g. IE6) setSkillsBarStyle(player, foundskills); } } catch (Exception e) { error = 2; } // We can search the speciality in text now p = specialities.size() - 1; final List<List<Object>> foundspecialities = new ArrayList<List<Object>>(); while (p >= 0) { final String singlespeciality = specialities.get(p).toString(); k = mytext.indexOf(singlespeciality); if (k >= 0) { final List<Object> pair = new ArrayList<Object>(); pair.add(new Integer(k)); pair.add(singlespeciality); pair.add(new Integer(p)); foundspecialities.add(pair); final char[] ct = new char[singlespeciality.length()]; for (int cl = 0; cl < ct.length; cl++) { ct[cl] = '*'; } mytext = mytext.replaceFirst(singlespeciality, new String(ct)); } else { p--; } } if ((foundspecialities.size() > 1) && (error == 0)) { error = 1; } // Sort specialities by location p = foundspecialities.size() - 1; while (p > 0) { k = p; while (k < foundspecialities.size()) { final List<Object> ts1 = foundspecialities.get(k - 1); final List<Object> ts2 = foundspecialities.get(k); if (((Integer) ts1.get(0)).intValue() > ((Integer) ts2.get(0)).intValue()) { foundspecialities.set(k - 1, ts2); foundspecialities.set(k, ts1); k++; } else { break; } } p--; } if (foundspecialities.size() > 0) { player.setSpeciality(((Integer) specialitiesvalues.get(((Integer) (foundspecialities.get(0)).get(2)).intValue())).intValue() + 1); } else { player.setSpeciality(0); } } return player; }
diff --git a/src/be/ibridge/kettle/core/dialog/DatabaseExplorerDialog.java b/src/be/ibridge/kettle/core/dialog/DatabaseExplorerDialog.java index 04f8e369..931ac7d6 100644 --- a/src/be/ibridge/kettle/core/dialog/DatabaseExplorerDialog.java +++ b/src/be/ibridge/kettle/core/dialog/DatabaseExplorerDialog.java @@ -1,642 +1,643 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.core.dialog; import java.util.ArrayList; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.DBCache; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.WindowProperty; import be.ibridge.kettle.core.database.Catalog; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.database.DatabaseMetaInformation; import be.ibridge.kettle.core.database.Schema; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.test.EditDatabaseTable; import be.ibridge.kettle.trans.step.BaseStepDialog; /** * This dialog represents an explorer type of interface on a given database connection. * It shows the tables defined in the visible schemas or catalogs on that connection. * The interface also allows you to get all kinds of information on those tables. * * @author Matt * @since 18-05-2003 * */ public class DatabaseExplorerDialog extends Dialog { private LogWriter log; private Props props; private DatabaseMeta dbMeta; private DBCache dbcache; private static final String STRING_CATALOG = "Catalogs"; private static final String STRING_SCHEMAS = "Schema's"; private static final String STRING_TABLES = "Tables"; private static final String STRING_VIEWS = "Views"; private static final String STRING_SYNONYMS = "Synonyms"; private Shell shell; private Tree wTree; private TreeItem tiTree; private Button wOK; private Button wRefresh; private Button wCancel; /** This is the return value*/ private String tableName; private boolean justLook; private String selectTable; private ArrayList databases; public DatabaseExplorerDialog(Shell par, Props pr, int style, DatabaseMeta conn, ArrayList databases) { super(par, style); props=pr; log=LogWriter.getInstance(); dbMeta=conn; dbcache = DBCache.getInstance(); this.databases = databases; justLook=false; selectTable=null; } public DatabaseExplorerDialog(Shell par, Props pr, int style, DatabaseMeta conn, ArrayList databases, boolean look) { this(par, pr, style, conn, databases); justLook=look; } public void setSelectedTable(String selectedTable) { // System.out.println("Table to select: "+selectedTable); this.selectTable = selectedTable; } public Object open() { tableName = null; Shell parent = getParent(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); shell.setText("Database Explorer on ["+dbMeta.toString()+"]"); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout (formLayout); // Tree wTree = new Tree(shell, SWT.SINGLE | SWT.BORDER /*| (multiple?SWT.CHECK:SWT.NONE)*/); props.setLook( wTree); if (!getData()) return null; // Buttons wOK = new Button(shell, SWT.PUSH); wOK.setText(" &OK "); wRefresh = new Button(shell, SWT.PUSH); wRefresh.setText(" &Refresh "); if (!justLook) { wCancel = new Button(shell, SWT.PUSH); wCancel.setText(" &Cancel "); } FormData fdTree = new FormData(); int margin = 10; fdTree.left = new FormAttachment(0, 0); // To the right of the label fdTree.top = new FormAttachment(0, 0); fdTree.right = new FormAttachment(100, 0); fdTree.bottom = new FormAttachment(100, -50); wTree.setLayoutData(fdTree); if (!justLook) { BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wRefresh, wCancel}, margin, null); // Add listeners wCancel.addListener(SWT.Selection, new Listener () { public void handleEvent (Event e) { log.logDebug("SelectTableDialog", "CANCEL SelectTableDialog"); dbMeta=null; dispose(); } } ); } else { BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wRefresh }, margin, null); } // Add listeners wOK.addListener(SWT.Selection, new Listener () { public void handleEvent (Event e) { handleOK(); } } ); wRefresh.addListener(SWT.Selection, new Listener () { public void handleEvent (Event e) { getData(); } } ); SelectionAdapter selAdapter=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { openSchema(e); } }; wTree.addSelectionListener(selAdapter); wTree.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { if (e.button == 3) // right click! { setTreeMenu(); } } } ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { dispose(); } } ); WindowProperty winprop = props.getScreen(shell.getText()); if (winprop!=null) winprop.setShell(shell); else { shell.pack(); shell.setSize(320, 480); } shell.open(); Display display = parent.getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return tableName; } private boolean getData() { GetDatabaseInfoProgressDialog gdipd = new GetDatabaseInfoProgressDialog(log, props, shell, dbMeta); DatabaseMetaInformation dmi = gdipd.open(); if (dmi!=null) { // Clear the tree top entry if (tiTree!=null && !tiTree.isDisposed()) tiTree.dispose(); // New entry in the tree tiTree = new TreeItem(wTree, SWT.NONE); tiTree.setText(dbMeta==null?"":dbMeta.getName()); // Show the catalogs... Catalog[] catalogs = dmi.getCatalogs(); if (catalogs!=null) { TreeItem tiCat = new TreeItem(tiTree, SWT.NONE); tiCat.setText(STRING_CATALOG); for (int i=0;i<catalogs.length;i++) { TreeItem newCat = new TreeItem(tiCat, SWT.NONE); newCat.setText(catalogs[i].getCatalogName()); for (int j=0;j<catalogs[i].getItems().length;j++) { String tableName = catalogs[i].getItems()[j]; TreeItem ti = new TreeItem(newCat, SWT.NONE); ti.setText(tableName); } } } // The schema's Schema[] schemas= dmi.getSchemas(); if (schemas!=null) { TreeItem tiSch = new TreeItem(tiTree, SWT.NONE); tiSch.setText(STRING_SCHEMAS); for (int i=0;i<schemas.length;i++) { TreeItem newSch = new TreeItem(tiSch, SWT.NONE); newSch.setText(schemas[i].getSchemaName()); for (int j=0;j<schemas[i].getItems().length;j++) { String tableName = schemas[i].getItems()[j]; TreeItem ti = new TreeItem(newSch, SWT.NONE); ti.setText(tableName); } } } // The tables in general... TreeItem tiTab = null; String tabnames[] = dmi.getTables(); if (tabnames!=null) { tiTab = new TreeItem(tiTree, SWT.NONE); tiTab.setText(STRING_TABLES); tiTab.setExpanded(true); for (int i = 0; i < tabnames.length; i++) { TreeItem newTab = new TreeItem(tiTab, SWT.NONE); newTab.setText(tabnames[i]); } } // The views... TreeItem tiView = null; String views[] = dmi.getViews(); if (views!=null) { tiView = new TreeItem(tiTree, SWT.NONE); tiView.setText(STRING_VIEWS); for (int i = 0; i < views.length; i++) { TreeItem newView = new TreeItem(tiView, SWT.NONE); newView.setText(views[i]); } } // The synonyms TreeItem tiSyn = null; String[] syn = dmi.getSynonyms(); if (syn!=null) { tiSyn = new TreeItem(tiTree, SWT.NONE); tiSyn.setText(STRING_SYNONYMS); for (int i = 0; i < syn.length; i++) { TreeItem newSyn = new TreeItem(tiSyn, SWT.NONE); newSyn.setText(syn[i]); } } // Make sure the selected table is shown... // System.out.println("Selecting table "+k); - if (selectTable!=null) + if (selectTable!=null && selectTable.length()>0) { - TreeItem ti = Const.findTreeItem(tiTab, selectTable); - if (ti==null) Const.findTreeItem(tiView, selectTable); - if (ti==null) Const.findTreeItem(tiTree, selectTable); - if (ti==null) Const.findTreeItem(tiSyn, selectTable); + TreeItem ti = null; + if (ti==null && tiTab!=null) Const.findTreeItem(tiTab, selectTable); + if (ti==null && tiView!=null) Const.findTreeItem(tiView, selectTable); + if (ti==null && tiTree!=null) Const.findTreeItem(tiTree, selectTable); + if (ti==null && tiSyn!=null) Const.findTreeItem(tiSyn, selectTable); if (ti!=null) { // System.out.println("Selection set on "+ti.getText()); wTree.setSelection(new TreeItem[] { ti }); wTree.showSelection(); } selectTable=null; } tiTree.setExpanded(true); } else { return false; } return true; } public void setTreeMenu() { Menu mTree = null; TreeItem ti[]=wTree.getSelection(); if (ti.length==1) { // Get the parent. TreeItem parent = ti[0].getParentItem(); if (parent!=null) { String schemaName = parent.getText(); String tableName = ti[0].getText(); if (ti[0].getItemCount()==0) // No children, only the tables themselves... { String tab = null; if (schemaName.equalsIgnoreCase(STRING_TABLES) || schemaName.equalsIgnoreCase(STRING_VIEWS) || schemaName.equalsIgnoreCase(STRING_SYNONYMS) || ( schemaName!=null && schemaName.length()==0 ) ) { tab = tableName; } else { tab = dbMeta.getSchemaTableCombination(schemaName, tableName); } final String table = tab; mTree = new Menu(shell, SWT.POP_UP); MenuItem miPrev = new MenuItem(mTree, SWT.PUSH); miPrev.setText("&Preview first 100 rows of ["+table+"]"); miPrev.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { previewTable(table, false); }}); MenuItem miPrevN = new MenuItem(mTree, SWT.PUSH); miPrevN.setText("Preview &first ... rows of ["+table+"]"); miPrevN.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { previewTable(table, true); }}); //MenuItem miEdit = new MenuItem(mTree, SWT.PUSH); miEdit.setText("Open ["+table+"] for editing"); //miEdit.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editTable(table); }}); MenuItem miCount = new MenuItem(mTree, SWT.PUSH); miCount.setText("Show size of ["+table+"]"); miCount.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { showCount(table); }}); new MenuItem(mTree, SWT.SEPARATOR); MenuItem miShow = new MenuItem(mTree, SWT.PUSH); miShow.setText("Show layout of ["+table+"]"); miShow.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { showTable(table); }}); MenuItem miDDL = new MenuItem(mTree, SWT.PUSH); miDDL.setText("Generate DDL"); miDDL.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { getDDL(table); }}); MenuItem miDDL2 = new MenuItem(mTree, SWT.PUSH); miDDL2.setText("Generate DDL for other connection"); miDDL2.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { getDDLForOther(table); }}); MenuItem miSQL = new MenuItem(mTree, SWT.PUSH); miSQL.setText("Open SQL for ["+table+"]"); miSQL.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { getSQL(table); }}); } } } wTree.setMenu(mTree); } public void previewTable(String tableName, boolean asklimit) { int limit = 100; if (asklimit) { // Ask how many lines we should preview. String shellText = "Preview limit"; String lineText = "Number of lines to preview (0=all lines)"; EnterNumberDialog end = new EnterNumberDialog(shell, props, limit, shellText, lineText); int samples = end.open(); if (samples>=0) limit=samples; } GetPreviewTableProgressDialog pd = new GetPreviewTableProgressDialog(log, props, shell, dbMeta, tableName, limit); ArrayList rows = pd.open(); if (rows!=null) // otherwise an already shown error... { if (rows.size()>0) { PreviewRowsDialog prd = new PreviewRowsDialog(shell, SWT.NONE, tableName, rows); prd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK); mb.setMessage("This table contains no rows!"); mb.setText("Sorry"); mb.open(); } } } public void editTable(String tableName) { EditDatabaseTable edt = new EditDatabaseTable(shell, SWT.NONE, props, dbMeta, tableName, 20); edt.open(); } public void showTable(String tableName) { String sql = dbMeta.getSQLQueryFields(tableName); GetQueryFieldsProgressDialog pd = new GetQueryFieldsProgressDialog(log, props, shell, dbMeta, sql); Row result = pd.open(); if (result!=null) { StepFieldsDialog sfd = new StepFieldsDialog(shell, SWT.NONE, log, tableName, result, props); sfd.open(); } } public void showCount(String tableName) { GetTableSizeProgressDialog pd = new GetTableSizeProgressDialog(log, props, shell, dbMeta, tableName); Row r = pd.open(); if (r!=null) { String result = "Table ["+tableName+"] has "+r.getValue(0).getInteger()+" rows."; EnterTextDialog etd = new EnterTextDialog(shell, props, "Count", "# rows in "+tableName, result, true); etd.open(); } } public void getDDL(String tableName) { Database db = new Database(dbMeta); try { db.connect(); Row r = db.getTableFields(tableName); String sql = db.getCreateTableStatement(tableName, r, null, false, null, true); SQLEditor se = new SQLEditor(shell, SWT.NONE, dbMeta, dbcache, sql); se.open(); } catch(KettleDatabaseException dbe) { new ErrorDialog(shell, props, "Error", "Couldn't retrieve the table layout.", dbe); } finally { db.disconnect(); } } public void getDDLForOther(String tableName) { if (databases!=null) { Database db = new Database(dbMeta); try { db.connect(); Row r = db.getTableFields(tableName); // Now select the other connection... // Only take non-SAP R/3 connections.... ArrayList dbs = new ArrayList(); for (int i=0;i<databases.size();i++) if (((DatabaseMeta)databases.get(i)).getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_SAPR3) dbs.add(databases.get(i)); String conn[] = new String[dbs.size()]; for (int i=0;i<conn.length;i++) conn[i] = ((DatabaseMeta)dbs.get(i)).getName(); EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, conn, "Target database:", "Select the target database:"); String target = esd.open(); if (target!=null) { DatabaseMeta targetdbi = Const.findDatabase(dbs, target); Database targetdb = new Database(targetdbi); String sql = targetdb.getCreateTableStatement(tableName, r, null, false, null, true); SQLEditor se = new SQLEditor(shell, SWT.NONE, dbMeta, dbcache, sql); se.open(); } } catch(KettleDatabaseException dbe) { new ErrorDialog(shell, props, "Error", "Couldn't generate the DDL", dbe); } finally { db.disconnect(); } } else { MessageBox mb = new MessageBox(shell, SWT.NONE | SWT.ICON_INFORMATION); mb.setMessage("I'm unable to perform this operation as I don't know the other available connections at this point."); mb.setText("Sorry"); mb.open(); } } public void getSQL(String tableName) { SQLEditor sql = new SQLEditor(shell, SWT.NONE, dbMeta, dbcache, "SELECT * FROM "+tableName); sql.open(); } public void dispose() { props.setScreen(new WindowProperty(shell)); shell.dispose(); } public void handleOK() { if (justLook) { dispose(); return; } TreeItem ti[]=wTree.getSelection(); if (ti.length==1) { // Get the parent. TreeItem parent = ti[0].getParentItem(); if (parent!=null) { String schemaName = parent.getText(); String tablePart = ti[0].getText(); String tab = null; if (schemaName.equalsIgnoreCase(STRING_TABLES)) { tab = tablePart; } else { tab = dbMeta.getSchemaTableCombination(schemaName, tablePart); } tableName = tab; dispose(); } } } public void openSchema(SelectionEvent e) { TreeItem sel = (TreeItem)e.item; log.logDebug("SelectTableDialog", "Open :"+sel.getText()); TreeItem up1 = sel.getParentItem(); if (up1 != null) { TreeItem up2 = up1.getParentItem(); if (up2 != null) { TreeItem up3 = up2.getParentItem(); if (up3 != null) { tableName = sel.getText(); if (!justLook) handleOK(); else previewTable(tableName, false); } } } } public String toString() { return this.getClass().getName(); } }
false
true
private boolean getData() { GetDatabaseInfoProgressDialog gdipd = new GetDatabaseInfoProgressDialog(log, props, shell, dbMeta); DatabaseMetaInformation dmi = gdipd.open(); if (dmi!=null) { // Clear the tree top entry if (tiTree!=null && !tiTree.isDisposed()) tiTree.dispose(); // New entry in the tree tiTree = new TreeItem(wTree, SWT.NONE); tiTree.setText(dbMeta==null?"":dbMeta.getName()); // Show the catalogs... Catalog[] catalogs = dmi.getCatalogs(); if (catalogs!=null) { TreeItem tiCat = new TreeItem(tiTree, SWT.NONE); tiCat.setText(STRING_CATALOG); for (int i=0;i<catalogs.length;i++) { TreeItem newCat = new TreeItem(tiCat, SWT.NONE); newCat.setText(catalogs[i].getCatalogName()); for (int j=0;j<catalogs[i].getItems().length;j++) { String tableName = catalogs[i].getItems()[j]; TreeItem ti = new TreeItem(newCat, SWT.NONE); ti.setText(tableName); } } } // The schema's Schema[] schemas= dmi.getSchemas(); if (schemas!=null) { TreeItem tiSch = new TreeItem(tiTree, SWT.NONE); tiSch.setText(STRING_SCHEMAS); for (int i=0;i<schemas.length;i++) { TreeItem newSch = new TreeItem(tiSch, SWT.NONE); newSch.setText(schemas[i].getSchemaName()); for (int j=0;j<schemas[i].getItems().length;j++) { String tableName = schemas[i].getItems()[j]; TreeItem ti = new TreeItem(newSch, SWT.NONE); ti.setText(tableName); } } } // The tables in general... TreeItem tiTab = null; String tabnames[] = dmi.getTables(); if (tabnames!=null) { tiTab = new TreeItem(tiTree, SWT.NONE); tiTab.setText(STRING_TABLES); tiTab.setExpanded(true); for (int i = 0; i < tabnames.length; i++) { TreeItem newTab = new TreeItem(tiTab, SWT.NONE); newTab.setText(tabnames[i]); } } // The views... TreeItem tiView = null; String views[] = dmi.getViews(); if (views!=null) { tiView = new TreeItem(tiTree, SWT.NONE); tiView.setText(STRING_VIEWS); for (int i = 0; i < views.length; i++) { TreeItem newView = new TreeItem(tiView, SWT.NONE); newView.setText(views[i]); } } // The synonyms TreeItem tiSyn = null; String[] syn = dmi.getSynonyms(); if (syn!=null) { tiSyn = new TreeItem(tiTree, SWT.NONE); tiSyn.setText(STRING_SYNONYMS); for (int i = 0; i < syn.length; i++) { TreeItem newSyn = new TreeItem(tiSyn, SWT.NONE); newSyn.setText(syn[i]); } } // Make sure the selected table is shown... // System.out.println("Selecting table "+k); if (selectTable!=null) { TreeItem ti = Const.findTreeItem(tiTab, selectTable); if (ti==null) Const.findTreeItem(tiView, selectTable); if (ti==null) Const.findTreeItem(tiTree, selectTable); if (ti==null) Const.findTreeItem(tiSyn, selectTable); if (ti!=null) { // System.out.println("Selection set on "+ti.getText()); wTree.setSelection(new TreeItem[] { ti }); wTree.showSelection(); } selectTable=null; } tiTree.setExpanded(true); } else { return false; } return true; }
private boolean getData() { GetDatabaseInfoProgressDialog gdipd = new GetDatabaseInfoProgressDialog(log, props, shell, dbMeta); DatabaseMetaInformation dmi = gdipd.open(); if (dmi!=null) { // Clear the tree top entry if (tiTree!=null && !tiTree.isDisposed()) tiTree.dispose(); // New entry in the tree tiTree = new TreeItem(wTree, SWT.NONE); tiTree.setText(dbMeta==null?"":dbMeta.getName()); // Show the catalogs... Catalog[] catalogs = dmi.getCatalogs(); if (catalogs!=null) { TreeItem tiCat = new TreeItem(tiTree, SWT.NONE); tiCat.setText(STRING_CATALOG); for (int i=0;i<catalogs.length;i++) { TreeItem newCat = new TreeItem(tiCat, SWT.NONE); newCat.setText(catalogs[i].getCatalogName()); for (int j=0;j<catalogs[i].getItems().length;j++) { String tableName = catalogs[i].getItems()[j]; TreeItem ti = new TreeItem(newCat, SWT.NONE); ti.setText(tableName); } } } // The schema's Schema[] schemas= dmi.getSchemas(); if (schemas!=null) { TreeItem tiSch = new TreeItem(tiTree, SWT.NONE); tiSch.setText(STRING_SCHEMAS); for (int i=0;i<schemas.length;i++) { TreeItem newSch = new TreeItem(tiSch, SWT.NONE); newSch.setText(schemas[i].getSchemaName()); for (int j=0;j<schemas[i].getItems().length;j++) { String tableName = schemas[i].getItems()[j]; TreeItem ti = new TreeItem(newSch, SWT.NONE); ti.setText(tableName); } } } // The tables in general... TreeItem tiTab = null; String tabnames[] = dmi.getTables(); if (tabnames!=null) { tiTab = new TreeItem(tiTree, SWT.NONE); tiTab.setText(STRING_TABLES); tiTab.setExpanded(true); for (int i = 0; i < tabnames.length; i++) { TreeItem newTab = new TreeItem(tiTab, SWT.NONE); newTab.setText(tabnames[i]); } } // The views... TreeItem tiView = null; String views[] = dmi.getViews(); if (views!=null) { tiView = new TreeItem(tiTree, SWT.NONE); tiView.setText(STRING_VIEWS); for (int i = 0; i < views.length; i++) { TreeItem newView = new TreeItem(tiView, SWT.NONE); newView.setText(views[i]); } } // The synonyms TreeItem tiSyn = null; String[] syn = dmi.getSynonyms(); if (syn!=null) { tiSyn = new TreeItem(tiTree, SWT.NONE); tiSyn.setText(STRING_SYNONYMS); for (int i = 0; i < syn.length; i++) { TreeItem newSyn = new TreeItem(tiSyn, SWT.NONE); newSyn.setText(syn[i]); } } // Make sure the selected table is shown... // System.out.println("Selecting table "+k); if (selectTable!=null && selectTable.length()>0) { TreeItem ti = null; if (ti==null && tiTab!=null) Const.findTreeItem(tiTab, selectTable); if (ti==null && tiView!=null) Const.findTreeItem(tiView, selectTable); if (ti==null && tiTree!=null) Const.findTreeItem(tiTree, selectTable); if (ti==null && tiSyn!=null) Const.findTreeItem(tiSyn, selectTable); if (ti!=null) { // System.out.println("Selection set on "+ti.getText()); wTree.setSelection(new TreeItem[] { ti }); wTree.showSelection(); } selectTable=null; } tiTree.setExpanded(true); } else { return false; } return true; }
diff --git a/src/org/jruby/evaluator/EvaluationState.java b/src/org/jruby/evaluator/EvaluationState.java index bac134ca7..90b4a6f49 100644 --- a/src/org/jruby/evaluator/EvaluationState.java +++ b/src/org/jruby/evaluator/EvaluationState.java @@ -1,1935 +1,1935 @@ /******************************************************************************* * BEGIN LICENSE BLOCK *** Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common 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://www.eclipse.org/legal/cpl-v10.html * * 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) 2006 Charles Oliver Nutter <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in * which case the provisions of the GPL or the LGPL are applicable instead of * those above. If you wish to allow use of your version of this file only under * the terms of either the GPL or the LGPL, and not to allow others to use your * version of this file under the terms of the CPL, indicate your decision by * deleting the provisions above and replace them with the notice and other * provisions required by the GPL or the LGPL. If you do not delete the * provisions above, a recipient may use your version of this file under the * terms of any one of the CPL, the GPL or the LGPL. END LICENSE BLOCK **** ******************************************************************************/ package org.jruby.evaluator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.jruby.IRuby; import org.jruby.MetaClass; import org.jruby.RubyArray; import org.jruby.RubyBignum; import org.jruby.RubyClass; import org.jruby.RubyException; import org.jruby.RubyFloat; import org.jruby.RubyHash; import org.jruby.RubyKernel; import org.jruby.RubyModule; import org.jruby.RubyProc; import org.jruby.RubyRange; import org.jruby.RubyRegexp; import org.jruby.RubyString; import org.jruby.ast.AliasNode; import org.jruby.ast.ArgsCatNode; import org.jruby.ast.ArgsNode; import org.jruby.ast.ArgsPushNode; import org.jruby.ast.ArrayNode; import org.jruby.ast.AttrAssignNode; import org.jruby.ast.BackRefNode; import org.jruby.ast.BeginNode; import org.jruby.ast.BignumNode; import org.jruby.ast.BinaryOperatorNode; import org.jruby.ast.BlockAcceptingNode; import org.jruby.ast.BlockNode; import org.jruby.ast.BlockPassNode; import org.jruby.ast.BreakNode; import org.jruby.ast.CallNode; import org.jruby.ast.CaseNode; import org.jruby.ast.ClassNode; import org.jruby.ast.ClassVarAsgnNode; import org.jruby.ast.ClassVarDeclNode; import org.jruby.ast.ClassVarNode; import org.jruby.ast.Colon2Node; import org.jruby.ast.Colon3Node; import org.jruby.ast.ConstDeclNode; import org.jruby.ast.ConstNode; import org.jruby.ast.DAsgnNode; import org.jruby.ast.DRegexpNode; import org.jruby.ast.DStrNode; import org.jruby.ast.DSymbolNode; import org.jruby.ast.DVarNode; import org.jruby.ast.DXStrNode; import org.jruby.ast.DefinedNode; import org.jruby.ast.DefnNode; import org.jruby.ast.DefsNode; import org.jruby.ast.DotNode; import org.jruby.ast.EnsureNode; import org.jruby.ast.EvStrNode; import org.jruby.ast.FCallNode; import org.jruby.ast.FixnumNode; import org.jruby.ast.FlipNode; import org.jruby.ast.FloatNode; import org.jruby.ast.ForNode; import org.jruby.ast.GlobalAsgnNode; import org.jruby.ast.GlobalVarNode; import org.jruby.ast.HashNode; import org.jruby.ast.IfNode; import org.jruby.ast.InstAsgnNode; import org.jruby.ast.InstVarNode; import org.jruby.ast.IterNode; import org.jruby.ast.ListNode; import org.jruby.ast.LocalAsgnNode; import org.jruby.ast.LocalVarNode; import org.jruby.ast.Match2Node; import org.jruby.ast.Match3Node; import org.jruby.ast.MatchNode; import org.jruby.ast.ModuleNode; import org.jruby.ast.MultipleAsgnNode; import org.jruby.ast.NewlineNode; import org.jruby.ast.NextNode; import org.jruby.ast.Node; import org.jruby.ast.NodeTypes; import org.jruby.ast.NotNode; import org.jruby.ast.NthRefNode; import org.jruby.ast.OpAsgnNode; import org.jruby.ast.OpAsgnOrNode; import org.jruby.ast.OpElementAsgnNode; import org.jruby.ast.OptNNode; import org.jruby.ast.OrNode; import org.jruby.ast.RegexpNode; import org.jruby.ast.RescueBodyNode; import org.jruby.ast.RescueNode; import org.jruby.ast.ReturnNode; import org.jruby.ast.RootNode; import org.jruby.ast.SClassNode; import org.jruby.ast.SValueNode; import org.jruby.ast.SplatNode; import org.jruby.ast.StrNode; import org.jruby.ast.SuperNode; import org.jruby.ast.SymbolNode; import org.jruby.ast.ToAryNode; import org.jruby.ast.UndefNode; import org.jruby.ast.UntilNode; import org.jruby.ast.VAliasNode; import org.jruby.ast.VCallNode; import org.jruby.ast.WhenNode; import org.jruby.ast.WhileNode; import org.jruby.ast.XStrNode; import org.jruby.ast.YieldNode; import org.jruby.ast.types.INameNode; import org.jruby.ast.util.ArgsUtil; import org.jruby.exceptions.JumpException; import org.jruby.exceptions.RaiseException; import org.jruby.exceptions.JumpException.JumpType; import org.jruby.internal.runtime.methods.DefaultMethod; import org.jruby.internal.runtime.methods.WrapperMethod; import org.jruby.lexer.yacc.ISourcePosition; import org.jruby.parser.StaticScope; import org.jruby.runtime.Block; import org.jruby.runtime.CallType; import org.jruby.runtime.DynamicMethod; import org.jruby.runtime.DynamicScope; import org.jruby.runtime.ICallable; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; public class EvaluationState { public static IRubyObject eval(ThreadContext context, Node node, IRubyObject self) { try { return evalInternal(context, node, self); } catch (StackOverflowError sfe) { throw context.getRuntime().newSystemStackError("stack level too deep"); } } private static IRubyObject evalInternal(ThreadContext context, Node node, IRubyObject self) { IRuby runtime = context.getRuntime(); bigloop: do { if (node == null) return runtime.getNil(); switch (node.nodeId) { case NodeTypes.ALIASNODE: { AliasNode iVisited = (AliasNode) node; if (context.getRubyClass() == null) { throw runtime.newTypeError("no class to make alias"); } context.getRubyClass().defineAlias(iVisited.getNewName(), iVisited.getOldName()); context.getRubyClass().callMethod(context, "method_added", runtime.newSymbol(iVisited.getNewName())); return runtime.getNil(); } case NodeTypes.ANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.ARGSCATNODE: { ArgsCatNode iVisited = (ArgsCatNode) node; IRubyObject args = evalInternal(context, iVisited.getFirstNode(), self); IRubyObject secondArgs = splatValue(evalInternal(context, iVisited.getSecondNode(), self)); RubyArray list = args instanceof RubyArray ? (RubyArray) args : runtime.newArray(args); return list.concat(secondArgs); } case NodeTypes.ARGSPUSHNODE: { ArgsPushNode iVisited = (ArgsPushNode) node; RubyArray args = (RubyArray) evalInternal(context, iVisited.getFirstNode(), self).dup(); return args.append(evalInternal(context, iVisited.getSecondNode(), self)); } // case NodeTypes.ARGSNODE: // EvaluateVisitor.argsNodeVisitor.execute(this, node); // break; // case NodeTypes.ARGUMENTNODE: // EvaluateVisitor.argumentNodeVisitor.execute(this, node); // break; case NodeTypes.ARRAYNODE: { ArrayNode iVisited = (ArrayNode) node; IRubyObject[] array = new IRubyObject[iVisited.size()]; int i = 0; for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node next = (Node) iterator.next(); array[i++] = evalInternal(context, next, self); } return runtime.newArray(array); } // case NodeTypes.ASSIGNABLENODE: // EvaluateVisitor.assignableNodeVisitor.execute(this, node); // break; case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); receiver.callMethod(context, iVisited.getName(), args, callType); return args[args.length - 1]; } case NodeTypes.BACKREFNODE: { BackRefNode iVisited = (BackRefNode) node; IRubyObject backref = context.getBackref(); switch (iVisited.getType()) { case '~': return backref; case '&': return RubyRegexp.last_match(backref); case '`': return RubyRegexp.match_pre(backref); case '\'': return RubyRegexp.match_post(backref); case '+': return RubyRegexp.match_last(backref); } break; } case NodeTypes.BEGINNODE: { BeginNode iVisited = (BeginNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.BIGNUMNODE: { BignumNode iVisited = (BignumNode) node; return RubyBignum.newBignum(runtime, iVisited.getValue()); } // case NodeTypes.BINARYOPERATORNODE: // EvaluateVisitor.binaryOperatorNodeVisitor.execute(this, node); // break; // case NodeTypes.BLOCKARGNODE: // EvaluateVisitor.blockArgNodeVisitor.execute(this, node); // break; case NodeTypes.BLOCKNODE: { BlockNode iVisited = (BlockNode) node; IRubyObject result = runtime.getNil(); for (Iterator iter = iVisited.iterator(); iter.hasNext();) { result = evalInternal(context, (Node) iter.next(), self); } return result; } case NodeTypes.BLOCKPASSNODE: { BlockPassNode iVisited = (BlockPassNode) node; IRubyObject proc = evalInternal(context, iVisited.getBodyNode(), self); if (proc.isNil()) { context.setNoBlock(); try { return evalInternal(context, iVisited.getIterNode(), self); } finally { context.clearNoBlock(); } } // If not already a proc then we should try and make it one. if (!(proc instanceof RubyProc)) { proc = proc.convertToType("Proc", "to_proc", false); if (!(proc instanceof RubyProc)) { throw runtime.newTypeError("wrong argument type " + proc.getMetaClass().getName() + " (expected Proc)"); } } // TODO: Add safety check for taintedness Block block = (Block) context.getCurrentBlock(); if (block != null) { IRubyObject blockObject = block.getBlockObject(); // The current block is already associated with the proc. No need to create new // block for it. Just eval! if (blockObject != null && blockObject == proc) { try { context.setBlockAvailable(); return evalInternal(context, iVisited.getIterNode(), self); } finally { context.clearBlockAvailable(); } } } context.preBlockPassEval(((RubyProc) proc).getBlock()); try { return evalInternal(context, iVisited.getIterNode(), self); } finally { context.postBlockPassEval(); } } case NodeTypes.BREAKNODE: { BreakNode iVisited = (BreakNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); JumpException je = new JumpException(JumpException.JumpType.BreakJump); je.setPrimaryData(result); je.setSecondaryData(node); throw je; } case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; IterNode iterNode = iVisited.getIterNode(); IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); // if no block passed, do a simple call if (iterNode == null) { return receiver.callMethod(context, iVisited.getName(), args, callType); } // if block passed, prepare the block and then do the call, handling breaks and retries correctly context.preIterEval(Block.createBlock(context, iterNode.getVarNode(), new DynamicScope(iterNode.getScope(), context.getCurrentScope()), iterNode.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return receiver.callMethod(context, iVisited.getName(), args, callType); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.CASENODE: { CaseNode iVisited = (CaseNode) node; IRubyObject expression = null; if (iVisited.getCaseNode() != null) { expression = evalInternal(context, iVisited.getCaseNode(), self); } context.pollThreadEvents(); IRubyObject result = runtime.getNil(); Node firstWhenNode = iVisited.getFirstWhenNode(); while (firstWhenNode != null) { if (!(firstWhenNode instanceof WhenNode)) { node = firstWhenNode; continue bigloop; } WhenNode whenNode = (WhenNode) firstWhenNode; if (whenNode.getExpressionNodes() instanceof ArrayNode) { for (Iterator iter = ((ArrayNode) whenNode.getExpressionNodes()).iterator(); iter .hasNext();) { Node tag = (Node) iter.next(); context.setPosition(tag.getPosition()); if (isTrace(runtime)) { callTraceFunction(context, "line", self); } // Ruby grammar has nested whens in a case body because of // productions case_body and when_args. if (tag instanceof WhenNode) { RubyArray expressions = (RubyArray) evalInternal(context, ((WhenNode) tag) .getExpressionNodes(), self); for (int j = 0; j < expressions.getLength(); j++) { IRubyObject condition = expressions.entry(j); if ((expression != null && condition.callMethod(context, "===", expression) .isTrue()) || (expression == null && condition.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } continue; } result = evalInternal(context, tag, self); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = whenNode.getBodyNode(); continue bigloop; } } } else { result = evalInternal(context, whenNode.getExpressionNodes(), self); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } context.pollThreadEvents(); firstWhenNode = whenNode.getNextCase(); } return runtime.getNil(); } case NodeTypes.CLASSNODE: { ClassNode iVisited = (ClassNode) node; Node superNode = iVisited.getSuperNode(); RubyClass superClass = superNode == null ? null : (RubyClass) evalInternal(context, superNode, self); Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingClass = getEnclosingModule(context, classNameNode, self); RubyClass rubyClass = enclosingClass.defineOrGetClassUnder(name, superClass); if (context.getWrapper() != null) { rubyClass.extendObject(context.getWrapper()); rubyClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), rubyClass, self); } case NodeTypes.CLASSVARASGNNODE: { ClassVarAsgnNode iVisited = (ClassVarAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); RubyModule rubyClass = (RubyModule) context.peekCRef().getValue(); if (rubyClass == null) { rubyClass = self.getMetaClass(); } else if (rubyClass.isSingleton()) { rubyClass = (RubyModule) rubyClass.getInstanceVariable("__attached__"); } rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARDECLNODE: { ClassVarDeclNode iVisited = (ClassVarDeclNode) node; // FIXME: shouldn't we use cref here? if (context.getRubyClass() == null) { throw runtime.newTypeError("no class/module to define class variable"); } IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); ((RubyModule) context.peekCRef().getValue()).setClassVar(iVisited.getName(), result); return runtime.getNil(); } case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; RubyModule rubyClass = (RubyModule) context.peekCRef().getValue(); if (rubyClass == null) { rubyClass = self.getMetaClass(); } else if (rubyClass.isSingleton()) { rubyClass = (RubyModule)rubyClass.getInstanceVariable("__attached__"); } return rubyClass.getClassVar(iVisited.getName()); } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; Node leftNode = iVisited.getLeftNode(); // TODO: Made this more colon3 friendly because of cpath production // rule in grammar (it is convenient to think of them as the same thing // at a grammar level even though evaluation is). if (leftNode == null) { return runtime.getObject().getConstantFrom(iVisited.getName()); } else { IRubyObject result = evalInternal(context, iVisited.getLeftNode(), self); if (result instanceof RubyModule) { return ((RubyModule) result).getConstantFrom(iVisited.getName()); } else { return result.callMethod(context, iVisited.getName()); } } } case NodeTypes.COLON3NODE: { Colon3Node iVisited = (Colon3Node) node; return runtime.getObject().getConstantFrom(iVisited.getName()); } case NodeTypes.CONSTDECLNODE: { ConstDeclNode iVisited = (ConstDeclNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); IRubyObject module; if (iVisited.getPathNode() != null) { module = evalInternal(context, iVisited.getPathNode(), self); } else { // FIXME: why do we check RubyClass and then use CRef? if (context.getRubyClass() == null) { // TODO: wire into new exception handling mechanism throw runtime.newTypeError("no class/module to define constant"); } module = (RubyModule) context.peekCRef().getValue(); } // FIXME: shouldn't we use the result of this set in setResult? ((RubyModule) module).setConstant(iVisited.getName(), result); return result; } case NodeTypes.CONSTNODE: { ConstNode iVisited = (ConstNode) node; return context.getConstant(iVisited.getName()); } case NodeTypes.DASGNNODE: { DAsgnNode iVisited = (DAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // System.out.println("DSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.DEFINEDNODE: { DefinedNode iVisited = (DefinedNode) node; String definition = getDefinition(context, iVisited.getExpressionNode(), self); if (definition != null) { return runtime.newString(definition); } else { return runtime.getNil(); } } case NodeTypes.DEFNNODE: { DefnNode iVisited = (DefnNode) node; RubyModule containingClass = context.getRubyClass(); if (containingClass == null) { throw runtime.newTypeError("No class to add method."); } String name = iVisited.getName(); if (containingClass == runtime.getObject() && name == "initialize") { runtime.getWarnings().warn("redefining Object#initialize may cause infinite loop"); } Visibility visibility = context.getCurrentVisibility(); if (name == "initialize" || visibility.isModuleFunction()) { visibility = Visibility.PRIVATE; } if (containingClass.isSingleton()) { IRubyObject attachedObject = ((MetaClass) containingClass).getAttachedObject(); if (!attachedObject.singletonMethodsAllowed()) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + attachedObject.getType()); } } DefaultMethod newMethod = new DefaultMethod(containingClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), visibility, context.peekCRef()); containingClass.addMethod(name, newMethod); if (context.getCurrentVisibility().isModuleFunction()) { containingClass.getSingletonClass().addMethod( name, new WrapperMethod(containingClass.getSingletonClass(), newMethod, Visibility.PUBLIC)); containingClass.callMethod(context, "singleton_method_added", runtime.newSymbol(name)); } // 'class << state.self' and 'class << obj' uses defn as opposed to defs if (containingClass.isSingleton()) { ((MetaClass) containingClass).getAttachedObject().callMethod( context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); } else { containingClass.callMethod(context, "method_added", runtime.newSymbol(name)); } return runtime.getNil(); } case NodeTypes.DEFSNODE: { DefsNode iVisited = (DefsNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); RubyClass rubyClass; if (receiver.isNil()) { rubyClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { rubyClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { rubyClass = runtime.getClass("FalseClass"); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure; can't define singleton method."); } if (receiver.isFrozen()) { throw runtime.newFrozenError("object"); } if (!receiver.singletonMethodsAllowed()) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + receiver.getType()); } rubyClass = receiver.getSingletonClass(); } if (runtime.getSafeLevel() >= 4) { - ICallable method = (ICallable) rubyClass.getMethods().get(iVisited.getName()); + Object method = rubyClass.getMethods().get(iVisited.getName()); if (method != null) { throw runtime.newSecurityError("Redefining method prohibited."); } } DefaultMethod newMethod = new DefaultMethod(rubyClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), Visibility.PUBLIC, context.peekCRef()); rubyClass.addMethod(iVisited.getName(), newMethod); receiver.callMethod(context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); return runtime.getNil(); } case NodeTypes.DOTNODE: { DotNode iVisited = (DotNode) node; return RubyRange.newRange(runtime, evalInternal(context, iVisited.getBeginNode(), self), evalInternal(context, iVisited .getEndNode(), self), iVisited.isExclusive()); } case NodeTypes.DREGEXPNODE: { DRegexpNode iVisited = (DRegexpNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } return RubyRegexp.newRegexp(runtime, sb.toString(), iVisited.getOptions(), lang); } case NodeTypes.DSTRNODE: { DStrNode iVisited = (DStrNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return runtime.newString(sb.toString()); } case NodeTypes.DSYMBOLNODE: { DSymbolNode iVisited = (DSymbolNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.getNode().iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return runtime.newSymbol(sb.toString()); } case NodeTypes.DVARNODE: { DVarNode iVisited = (DVarNode) node; // System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject obj = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); // FIXME: null check is removable once we figure out how to assign to unset named block args return obj == null ? runtime.getNil() : obj; } case NodeTypes.DXSTRNODE: { DXStrNode iVisited = (DXStrNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return self.callMethod(context, "`", runtime.newString(sb.toString())); } case NodeTypes.ENSURENODE: { EnsureNode iVisited = (EnsureNode) node; // save entering the try if there's nothing to ensure if (iVisited.getEnsureNode() != null) { IRubyObject result = runtime.getNil(); try { result = evalInternal(context, iVisited.getBodyNode(), self); } finally { evalInternal(context, iVisited.getEnsureNode(), self); } return result; } node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.EVSTRNODE: { EvStrNode iVisited = (EvStrNode) node; node = iVisited.getBody(); continue bigloop; } case NodeTypes.FALSENODE: { context.pollThreadEvents(); return runtime.getFalse(); } case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; IterNode iterNode = iVisited.getIterNode(); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); // if no block passed, do a simple call if (iterNode == null) { return self.callMethod(context, iVisited.getName(), args, CallType.FUNCTIONAL); } // if block passed, prepare the block and then do the call, handling breaks and retries correctly context.preIterEval(Block.createBlock(context, iterNode.getVarNode(), new DynamicScope(iterNode.getScope(), context.getCurrentScope()), iterNode.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return self.callMethod(context, iVisited.getName(), args, CallType.FUNCTIONAL); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.FIXNUMNODE: { FixnumNode iVisited = (FixnumNode) node; return iVisited.getFixnum(runtime); } case NodeTypes.FLIPNODE: { FlipNode iVisited = (FlipNode) node; IRubyObject result = runtime.getNil(); if (iVisited.isExclusive()) { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { result = evalInternal(context, iVisited.getBeginNode(), self).isTrue() ? runtime.getFalse() : runtime.getTrue(); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } else { if (evalInternal(context, iVisited.getEndNode(), self).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } else { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { if (evalInternal(context, iVisited.getBeginNode(), self).isTrue()) { context.getCurrentScope().setValue( iVisited.getIndex(), evalInternal(context, iVisited.getEndNode(), self).isTrue() ? runtime.getFalse() : runtime.getTrue(), iVisited.getDepth()); return runtime.getTrue(); } else { return runtime.getFalse(); } } else { if (evalInternal(context, iVisited.getEndNode(), self).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } } case NodeTypes.FLOATNODE: { FloatNode iVisited = (FloatNode) node; return RubyFloat.newFloat(runtime, iVisited.getValue()); } case NodeTypes.FORNODE: { ForNode iVisited = (ForNode) node; // For nodes do not have to create an addition scope so we just pass null context.preForLoopEval(Block.createBlock(context, iVisited.getVarNode(), null, iVisited.getCallable(), self)); try { while (true) { try { ISourcePosition position = context.getPosition(); context.beginCallArgs(); IRubyObject recv = null; try { recv = evalInternal(context, iVisited.getIterNode(), self); } finally { context.setPosition(position); context.endCallArgs(); } return recv.callMethod(context, "each", IRubyObject.NULL_ARRAY, CallType.NORMAL); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // do nothing, allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postForLoopEval(); } } case NodeTypes.GLOBALASGNNODE: { GlobalAsgnNode iVisited = (GlobalAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); runtime.getGlobalVariables().set(iVisited.getName(), result); return result; } case NodeTypes.GLOBALVARNODE: { GlobalVarNode iVisited = (GlobalVarNode) node; return runtime.getGlobalVariables().get(iVisited.getName()); } case NodeTypes.HASHNODE: { HashNode iVisited = (HashNode) node; Map hash = null; if (iVisited.getListNode() != null) { hash = new HashMap(iVisited.getListNode().size() / 2); for (Iterator iterator = iVisited.getListNode().iterator(); iterator.hasNext();) { // insert all nodes in sequence, hash them in the final instruction // KEY IRubyObject key = evalInternal(context, (Node) iterator.next(), self); IRubyObject value = evalInternal(context, (Node) iterator.next(), self); hash.put(key, value); } } if (hash == null) { return RubyHash.newHash(runtime); } return RubyHash.newHash(runtime, hash, runtime.getNil()); } case NodeTypes.IFNODE: { IfNode iVisited = (IfNode) node; IRubyObject result = evalInternal(context, iVisited.getCondition(), self); if (result.isTrue()) { node = iVisited.getThenBody(); continue bigloop; } else { node = iVisited.getElseBody(); continue bigloop; } } case NodeTypes.INSTASGNNODE: { InstAsgnNode iVisited = (InstAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); self.setInstanceVariable(iVisited.getName(), result); return result; } case NodeTypes.INSTVARNODE: { InstVarNode iVisited = (InstVarNode) node; IRubyObject variable = self.getInstanceVariable(iVisited.getName()); return variable == null ? runtime.getNil() : variable; } // case NodeTypes.ISCOPINGNODE: // EvaluateVisitor.iScopingNodeVisitor.execute(this, node); // break; case NodeTypes.ITERNODE: { IterNode iVisited = (IterNode) node; // new-style handling of blocks, for nodes that support it // don't process the block until it's needed, to avoid nasty iter tricks if (iVisited.getIterNode() instanceof BlockAcceptingNode) { ((BlockAcceptingNode)iVisited.getIterNode()).setIterNode(iVisited); node = iVisited.getIterNode(); continue bigloop; } // otherwise do it the same as the old way context.preIterEval(Block.createBlock(context, iVisited.getVarNode(), new DynamicScope(iVisited.getScope(), context.getCurrentScope()), iVisited.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return evalInternal(context, iVisited.getIterNode(), self); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.LOCALASGNNODE: { LocalAsgnNode iVisited = (LocalAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // System.out.println("LSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.LOCALVARNODE: { LocalVarNode iVisited = (LocalVarNode) node; //System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject result = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); return result == null ? runtime.getNil() : result; } case NodeTypes.MATCH2NODE: { Match2Node iVisited = (Match2Node) node; IRubyObject recv = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = evalInternal(context, iVisited.getValueNode(), self); return ((RubyRegexp) recv).match(value); } case NodeTypes.MATCH3NODE: { Match3Node iVisited = (Match3Node) node; IRubyObject recv = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = evalInternal(context, iVisited.getValueNode(), self); if (value instanceof RubyString) { return ((RubyRegexp) recv).match(value); } else { return value.callMethod(context, "=~", recv); } } case NodeTypes.MATCHNODE: { MatchNode iVisited = (MatchNode) node; return ((RubyRegexp) evalInternal(context, iVisited.getRegexpNode(), self)).match2(); } case NodeTypes.MODULENODE: { ModuleNode iVisited = (ModuleNode) node; Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingModule = getEnclosingModule(context, classNameNode, self); if (enclosingModule == null) { throw runtime.newTypeError("no outer class/module"); } RubyModule module; if (enclosingModule == runtime.getObject()) { module = runtime.getOrCreateModule(name); } else { module = enclosingModule.defineModuleUnder(name); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), module, self); } case NodeTypes.MULTIPLEASGNNODE: { MultipleAsgnNode iVisited = (MultipleAsgnNode) node; return AssignmentVisitor.assign(context, self, iVisited, evalInternal(context, iVisited.getValueNode(), self), false); } case NodeTypes.NEWLINENODE: { NewlineNode iVisited = (NewlineNode) node; // something in here is used to build up ruby stack trace... context.setPosition(iVisited.getPosition()); if (isTrace(runtime)) { callTraceFunction(context, "line", self); } // TODO: do above but not below for additional newline nodes node = iVisited.getNextNode(); continue bigloop; } case NodeTypes.NEXTNODE: { NextNode iVisited = (NextNode) node; context.pollThreadEvents(); IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.NextJump); je.setPrimaryData(result); je.setSecondaryData(iVisited); //state.setCurrentException(je); throw je; } case NodeTypes.NILNODE: return runtime.getNil(); case NodeTypes.NOTNODE: { NotNode iVisited = (NotNode) node; IRubyObject result = evalInternal(context, iVisited.getConditionNode(), self); return result.isTrue() ? runtime.getFalse() : runtime.getTrue(); } case NodeTypes.NTHREFNODE: { NthRefNode iVisited = (NthRefNode) node; return RubyRegexp.nth_match(iVisited.getMatchNumber(), context.getBackref()); } case NodeTypes.OPASGNANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; // add in reverse order IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.OPASGNNODE: { OpAsgnNode iVisited = (OpAsgnNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = receiver.callMethod(context, iVisited.getVariableName()); if (iVisited.getOperatorName() == "||") { if (value.isTrue()) { return value; } value = evalInternal(context, iVisited.getValueNode(), self); } else if (iVisited.getOperatorName() == "&&") { if (!value.isTrue()) { return value; } value = evalInternal(context, iVisited.getValueNode(), self); } else { value = value.callMethod(context, iVisited.getOperatorName(), evalInternal(context, iVisited.getValueNode(), self)); } receiver.callMethod(context, iVisited.getVariableNameAsgn(), value); context.pollThreadEvents(); return value; } case NodeTypes.OPASGNORNODE: { OpAsgnOrNode iVisited = (OpAsgnOrNode) node; String def = getDefinition(context, iVisited.getFirstNode(), self); IRubyObject result = runtime.getNil(); if (def != null) { result = evalInternal(context, iVisited.getFirstNode(), self); } if (!result.isTrue()) { result = evalInternal(context, iVisited.getSecondNode(), self); } return result; } case NodeTypes.OPELEMENTASGNNODE: { OpElementAsgnNode iVisited = (OpElementAsgnNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); IRubyObject firstValue = receiver.callMethod(context, "[]", args); if (iVisited.getOperatorName() == "||") { if (firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(context, iVisited.getValueNode(), self); } else if (iVisited.getOperatorName() == "&&") { if (!firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(context, iVisited.getValueNode(), self); } else { firstValue = firstValue.callMethod(context, iVisited.getOperatorName(), evalInternal(context, iVisited .getValueNode(), self)); } IRubyObject[] expandedArgs = new IRubyObject[args.length + 1]; System.arraycopy(args, 0, expandedArgs, 0, args.length); expandedArgs[expandedArgs.length - 1] = firstValue; return receiver.callMethod(context, "[]=", expandedArgs); } case NodeTypes.OPTNNODE: { OptNNode iVisited = (OptNNode) node; IRubyObject result = runtime.getNil(); while (RubyKernel.gets(runtime.getTopSelf(), IRubyObject.NULL_ARRAY).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(context, iVisited.getBodyNode(), self); break; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: // do nothing, this iteration restarts break; case JumpType.NEXT: // recheck condition break loop; case JumpType.BREAK: // end loop return (IRubyObject) je.getPrimaryData(); default: throw je; } } } } return result; } case NodeTypes.ORNODE: { OrNode iVisited = (OrNode) node; IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) { result = evalInternal(context, iVisited.getSecondNode(), self); } return result; } // case NodeTypes.POSTEXENODE: // EvaluateVisitor.postExeNodeVisitor.execute(this, node); // break; case NodeTypes.REDONODE: { context.pollThreadEvents(); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.RedoJump); je.setSecondaryData(node); throw je; } case NodeTypes.REGEXPNODE: { RegexpNode iVisited = (RegexpNode) node; String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } try { return RubyRegexp.newRegexp(runtime, iVisited.getPattern(), lang); } catch(java.util.regex.PatternSyntaxException e) { throw runtime.newSyntaxError(e.getMessage()); } } case NodeTypes.RESCUEBODYNODE: { RescueBodyNode iVisited = (RescueBodyNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.RESCUENODE: { RescueNode iVisited = (RescueNode)node; RescuedBlock : while (true) { IRubyObject globalExceptionState = runtime.getGlobalVariables().get("$!"); boolean anotherExceptionRaised = false; try { // Execute rescue block IRubyObject result = evalInternal(context, iVisited.getBodyNode(), self); // If no exception is thrown execute else block if (iVisited.getElseNode() != null) { if (iVisited.getRescueNode() == null) { runtime.getWarnings().warn(iVisited.getElseNode().getPosition(), "else without rescue is useless"); } result = evalInternal(context, iVisited.getElseNode(), self); } return result; } catch (RaiseException raiseJump) { RubyException raisedException = raiseJump.getException(); // TODO: Rubicon TestKernel dies without this line. A cursory glance implies we // falsely set $! to nil and this sets it back to something valid. This should // get fixed at the same time we address bug #1296484. runtime.getGlobalVariables().set("$!", raisedException); RescueBodyNode rescueNode = iVisited.getRescueNode(); while (rescueNode != null) { Node exceptionNodes = rescueNode.getExceptionNodes(); ListNode exceptionNodesList; if (exceptionNodes instanceof SplatNode) { exceptionNodesList = (ListNode) evalInternal(context, exceptionNodes, self); } else { exceptionNodesList = (ListNode) exceptionNodes; } if (isRescueHandled(context, raisedException, exceptionNodesList, self)) { try { return evalInternal(context, rescueNode, self); } catch (JumpException je) { if (je.getJumpType() == JumpException.JumpType.RetryJump) { // should be handled in the finally block below //state.runtime.getGlobalVariables().set("$!", state.runtime.getNil()); //state.threadContext.setRaisedException(null); continue RescuedBlock; } else { anotherExceptionRaised = true; throw je; } } } rescueNode = rescueNode.getOptRescueNode(); } // no takers; bubble up throw raiseJump; } finally { // clear exception when handled or retried if (!anotherExceptionRaised) runtime.getGlobalVariables().set("$!", globalExceptionState); } } } case NodeTypes.RETRYNODE: { context.pollThreadEvents(); JumpException je = new JumpException(JumpException.JumpType.RetryJump); throw je; } case NodeTypes.RETURNNODE: { ReturnNode iVisited = (ReturnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); JumpException je = new JumpException(JumpException.JumpType.ReturnJump); je.setPrimaryData(iVisited.getTarget()); je.setSecondaryData(result); je.setTertiaryData(iVisited); throw je; } case NodeTypes.ROOTNODE: { RootNode iVisited = (RootNode) node; DynamicScope scope = iVisited.getScope(); // Serialization killed our dynamic scope. We can just create an empty one // since serialization cannot serialize an eval (which is the only thing // which is capable of having a non-empty dynamic scope). if (scope == null) { scope = new DynamicScope(iVisited.getStaticScope(), null); } // Each root node has a top-level scope that we need to push context.preRootNode(scope); // FIXME: Wire up BEGIN and END nodes try { return eval(context, iVisited.getBodyNode(), self); } finally { context.postRootNode(); } } case NodeTypes.SCLASSNODE: { SClassNode iVisited = (SClassNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); RubyClass singletonClass; if (receiver.isNil()) { singletonClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { singletonClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { singletonClass = runtime.getClass("FalseClass"); } else if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("no virtual class for " + receiver.getMetaClass().getBaseName()); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure: can't extend object."); } singletonClass = receiver.getSingletonClass(); } if (context.getWrapper() != null) { singletonClass.extendObject(context.getWrapper()); singletonClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), singletonClass, self); } case NodeTypes.SELFNODE: return self; case NodeTypes.SPLATNODE: { SplatNode iVisited = (SplatNode) node; return splatValue(evalInternal(context, iVisited.getValue(), self)); } //// case NodeTypes.STARNODE: //// EvaluateVisitor.starNodeVisitor.execute(this, node); //// break; case NodeTypes.STRNODE: { StrNode iVisited = (StrNode) node; return runtime.newString(iVisited.getValue()); } case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; if (context.getFrameLastClass() == null) { String name = context.getFrameLastFunc(); throw runtime.newNameError("Superclass method '" + name + "' disabled.", name); } context.beginCallArgs(); IRubyObject[] args = null; try { args = setupArgs(context, iVisited.getArgsNode(), self); } finally { context.endCallArgs(); } return context.callSuper(args); } case NodeTypes.SVALUENODE: { SValueNode iVisited = (SValueNode) node; return aValueSplat(evalInternal(context, iVisited.getValue(), self)); } case NodeTypes.SYMBOLNODE: { SymbolNode iVisited = (SymbolNode) node; return runtime.newSymbol(iVisited.getName()); } case NodeTypes.TOARYNODE: { ToAryNode iVisited = (ToAryNode) node; return aryToAry(evalInternal(context, iVisited.getValue(), self)); } case NodeTypes.TRUENODE: { context.pollThreadEvents(); return runtime.getTrue(); } case NodeTypes.UNDEFNODE: { UndefNode iVisited = (UndefNode) node; if (context.getRubyClass() == null) { throw runtime .newTypeError("No class to undef method '" + iVisited.getName() + "'."); } context.getRubyClass().undef(iVisited.getName()); return runtime.getNil(); } case NodeTypes.UNTILNODE: { UntilNode iVisited = (UntilNode) node; IRubyObject result = runtime.getNil(); while (!(result = evalInternal(context, iVisited.getConditionNode(), self)).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(context, iVisited.getBodyNode(), self); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: return (IRubyObject) je.getPrimaryData(); default: throw je; } } } } return result; } case NodeTypes.VALIASNODE: { VAliasNode iVisited = (VAliasNode) node; runtime.getGlobalVariables().alias(iVisited.getNewName(), iVisited.getOldName()); return runtime.getNil(); } case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; return self.callMethod(context, iVisited.getName(), IRubyObject.NULL_ARRAY, CallType.VARIABLE); } case NodeTypes.WHENNODE: assert false; return null; case NodeTypes.WHILENODE: { WhileNode iVisited = (WhileNode) node; IRubyObject result = runtime.getNil(); boolean firstTest = iVisited.evaluateAtStart(); while (!firstTest || (result = evalInternal(context, iVisited.getConditionNode(), self)).isTrue()) { firstTest = true; loop: while (true) { // Used for the 'redo' command try { evalInternal(context, iVisited.getBodyNode(), self); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: return result; default: throw je; } } } } return result; } case NodeTypes.XSTRNODE: { XStrNode iVisited = (XStrNode) node; return self.callMethod(context, "`", runtime.newString(iVisited.getValue())); } case NodeTypes.YIELDNODE: { YieldNode iVisited = (YieldNode) node; IRubyObject result = evalInternal(context, iVisited.getArgsNode(), self); if (iVisited.getArgsNode() == null) { result = null; } return context.yieldCurrentBlock(result, null, null, iVisited.getCheckState()); } case NodeTypes.ZARRAYNODE: { return runtime.newArray(); } case NodeTypes.ZSUPERNODE: { if (context.getFrameLastClass() == null) { String name = context.getFrameLastFunc(); throw runtime.newNameError("superclass method '" + name + "' disabled", name); } return context.callSuper(context.getFrameArgs(), true); } } } while (true); } private static String getArgumentDefinition(ThreadContext context, Node node, String type, IRubyObject self) { if (node == null) return type; if (node instanceof ArrayNode) { for (Iterator iter = ((ArrayNode)node).iterator(); iter.hasNext(); ) { if (getDefinitionInner(context, (Node)iter.next(), self) == null) return null; } } else if (getDefinitionInner(context, node, self) == null) { return null; } return type; } private static String getDefinition(ThreadContext context, Node node, IRubyObject self) { try { context.setWithinDefined(true); return getDefinitionInner(context, node, self); } finally { context.setWithinDefined(false); } } private static String getDefinitionInner(ThreadContext context, Node node, IRubyObject self) { if (node == null) return "expression"; switch(node.nodeId) { case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; if (getDefinitionInner(context, iVisited.getReceiverNode(), self) != null) { try { IRubyObject receiver = eval(context, iVisited.getReceiverNode(), self); RubyClass metaClass = receiver.getMetaClass(); DynamicMethod method = metaClass.searchMethod(iVisited.getName()); Visibility visibility = method.getVisibility(); if (!visibility.isPrivate() && (!visibility.isProtected() || self.isKindOf(metaClass.getRealClass()))) { if (metaClass.isMethodBound(iVisited.getName(), false)) { return getArgumentDefinition(context, iVisited.getArgsNode(), "assignment", self); } } } catch (JumpException excptn) { } } return null; } case NodeTypes.BACKREFNODE: return "$" + ((BackRefNode) node).getType(); case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; if (getDefinitionInner(context, iVisited.getReceiverNode(), self) != null) { try { IRubyObject receiver = eval(context, iVisited.getReceiverNode(), self); RubyClass metaClass = receiver.getMetaClass(); DynamicMethod method = metaClass.searchMethod(iVisited.getName()); Visibility visibility = method.getVisibility(); if (!visibility.isPrivate() && (!visibility.isProtected() || self.isKindOf(metaClass.getRealClass()))) { if (metaClass.isMethodBound(iVisited.getName(), false)) { return getArgumentDefinition(context, iVisited.getArgsNode(), "method", self); } } } catch (JumpException excptn) { } } return null; } case NodeTypes.CLASSVARASGNNODE: case NodeTypes.CLASSVARDECLNODE: case NodeTypes.CONSTDECLNODE: case NodeTypes.DASGNNODE: case NodeTypes.GLOBALASGNNODE: case NodeTypes.LOCALASGNNODE: case NodeTypes.MULTIPLEASGNNODE: case NodeTypes.OPASGNNODE: case NodeTypes.OPELEMENTASGNNODE: return "assignment"; case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; if (context.getRubyClass() == null && self.getMetaClass().isClassVarDefined(iVisited.getName())) { return "class_variable"; } else if (!context.getRubyClass().isSingleton() && context.getRubyClass().isClassVarDefined(iVisited.getName())) { return "class_variable"; } RubyModule module = (RubyModule) context.getRubyClass().getInstanceVariable("__attached__"); if (module != null && module.isClassVarDefined(iVisited.getName())) return "class_variable"; return null; } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; try { IRubyObject left = EvaluationState.eval(context, iVisited.getLeftNode(), self); if (left instanceof RubyModule && ((RubyModule) left).getConstantAt(iVisited.getName()) != null) { return "constant"; } else if (left.getMetaClass().isMethodBound(iVisited.getName(), true)) { return "method"; } } catch (JumpException excptn) {} return null; } case NodeTypes.CONSTNODE: if (context.getConstantDefined(((ConstNode) node).getName())) { return "constant"; } return null; case NodeTypes.DVARNODE: return "local-variable(in-block)"; case NodeTypes.FALSENODE: return "false"; case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; if (self.getMetaClass().isMethodBound(iVisited.getName(), false)) { return getArgumentDefinition(context, iVisited.getArgsNode(), "method", self); } return null; } case NodeTypes.GLOBALVARNODE: if (context.getRuntime().getGlobalVariables().isDefined(((GlobalVarNode) node).getName())) { return "global-variable"; } return null; case NodeTypes.INSTVARNODE: if (self.getInstanceVariable(((InstVarNode) node).getName()) != null) { return "instance-variable"; } return null; case NodeTypes.LOCALVARNODE: return "local-variable"; case NodeTypes.MATCH2NODE: case NodeTypes.MATCH3NODE: return "method"; case NodeTypes.NILNODE: return "nil"; case NodeTypes.NTHREFNODE: return "$" + ((NthRefNode) node).getMatchNumber(); case NodeTypes.SELFNODE: return "state.getSelf()"; case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; String lastMethod = context.getFrameLastFunc(); RubyModule lastClass = context.getFrameLastClass(); if (lastMethod != null && lastClass != null && lastClass.getSuperClass().isMethodBound(lastMethod, false)) { return getArgumentDefinition(context, iVisited.getArgsNode(), "super", self); } return null; } case NodeTypes.TRUENODE: return "true"; case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; if (self.getMetaClass().isMethodBound(iVisited.getName(), false)) { return "method"; } return null; } case NodeTypes.YIELDNODE: return context.isBlockGiven() ? "yield" : null; case NodeTypes.ZSUPERNODE: { String lastMethod = context.getFrameLastFunc(); RubyModule lastClass = context.getFrameLastClass(); if (lastMethod != null && lastClass != null && lastClass.getSuperClass().isMethodBound(lastMethod, false)) { return "super"; } return null; } default: try { EvaluationState.eval(context, node, self); return "expression"; } catch (JumpException jumpExcptn) {} } return null; } private static IRubyObject aryToAry(IRubyObject value) { if (value instanceof RubyArray) { return value; } if (value.respondsTo("to_ary")) { return value.convertToType("Array", "to_ary", false); } return value.getRuntime().newArray(value); } /** Evaluates the body in a class or module definition statement. * */ private static IRubyObject evalClassDefinitionBody(ThreadContext context, StaticScope scope, Node bodyNode, RubyModule type, IRubyObject self) { IRuby runtime = context.getRuntime(); context.preClassEval(scope, type); try { if (isTrace(runtime)) { callTraceFunction(context, "class", type); } return evalInternal(context, bodyNode, type); } finally { context.postClassEval(); if (isTrace(runtime)) { callTraceFunction(context, "end", null); } } } /** * Helper method. * * test if a trace function is avaiable. * */ private static boolean isTrace(IRuby runtime) { return runtime.getTraceFunction() != null; } private static void callTraceFunction(ThreadContext context, String event, IRubyObject zelf) { IRuby runtime = context.getRuntime(); String name = context.getFrameLastFunc(); RubyModule type = context.getFrameLastClass(); runtime.callTraceFunction(context, event, context.getPosition(), zelf, name, type); } private static IRubyObject splatValue(IRubyObject value) { if (value.isNil()) { return value.getRuntime().newArray(value); } return arrayValue(value); } private static IRubyObject aValueSplat(IRubyObject value) { IRuby runtime = value.getRuntime(); if (!(value instanceof RubyArray) || ((RubyArray) value).length().getLongValue() == 0) { return runtime.getNil(); } RubyArray array = (RubyArray) value; return array.getLength() == 1 ? array.first(IRubyObject.NULL_ARRAY) : array; } private static RubyArray arrayValue(IRubyObject value) { IRubyObject newValue = value.convertToType("Array", "to_ary", false); if (newValue.isNil()) { IRuby runtime = value.getRuntime(); // Object#to_a is obsolete. We match Ruby's hack until to_a goes away. Then we can // remove this hack too. if (value.getType().searchMethod("to_a").getImplementationClass() != runtime .getKernel()) { newValue = value.convertToType("Array", "to_a", false); if (newValue.getType() != runtime.getClass("Array")) { throw runtime.newTypeError("`to_a' did not return Array"); } } else { newValue = runtime.newArray(value); } } return (RubyArray) newValue; } private static IRubyObject[] setupArgs(ThreadContext context, Node node, IRubyObject self) { if (node == null) return IRubyObject.NULL_ARRAY; if (node instanceof ArrayNode) { ArrayNode argsArrayNode = (ArrayNode) node; ISourcePosition position = context.getPosition(); int size = argsArrayNode.size(); IRubyObject[] argsArray = new IRubyObject[size]; for (int i = 0; i < size; i++) { argsArray[i] = evalInternal(context, argsArrayNode.get(i), self); } context.setPosition(position); return argsArray; } return ArgsUtil.arrayify(evalInternal(context, node, self)); } private static RubyModule getEnclosingModule(ThreadContext context, Node node, IRubyObject self) { RubyModule enclosingModule = null; if (node instanceof Colon2Node) { IRubyObject result = evalInternal(context, ((Colon2Node) node).getLeftNode(), self); if (result != null && !result.isNil()) { enclosingModule = (RubyModule) result; } } else if (node instanceof Colon3Node) { enclosingModule = context.getRuntime().getObject(); } if (enclosingModule == null) { enclosingModule = (RubyModule) context.peekCRef().getValue(); } return enclosingModule; } private static boolean isRescueHandled(ThreadContext context, RubyException currentException, ListNode exceptionNodes, IRubyObject self) { IRuby runtime = context.getRuntime(); if (exceptionNodes == null) { return currentException.isKindOf(runtime.getClass("StandardError")); } context.beginCallArgs(); IRubyObject[] args = null; try { args = setupArgs(context, exceptionNodes, self); } finally { context.endCallArgs(); } for (int i = 0; i < args.length; i++) { if (!args[i].isKindOf(runtime.getClass("Module"))) { throw runtime.newTypeError("class or module required for rescue clause"); } if (args[i].callMethod(context, "===", currentException).isTrue()) return true; } return false; } }
true
true
private static IRubyObject evalInternal(ThreadContext context, Node node, IRubyObject self) { IRuby runtime = context.getRuntime(); bigloop: do { if (node == null) return runtime.getNil(); switch (node.nodeId) { case NodeTypes.ALIASNODE: { AliasNode iVisited = (AliasNode) node; if (context.getRubyClass() == null) { throw runtime.newTypeError("no class to make alias"); } context.getRubyClass().defineAlias(iVisited.getNewName(), iVisited.getOldName()); context.getRubyClass().callMethod(context, "method_added", runtime.newSymbol(iVisited.getNewName())); return runtime.getNil(); } case NodeTypes.ANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.ARGSCATNODE: { ArgsCatNode iVisited = (ArgsCatNode) node; IRubyObject args = evalInternal(context, iVisited.getFirstNode(), self); IRubyObject secondArgs = splatValue(evalInternal(context, iVisited.getSecondNode(), self)); RubyArray list = args instanceof RubyArray ? (RubyArray) args : runtime.newArray(args); return list.concat(secondArgs); } case NodeTypes.ARGSPUSHNODE: { ArgsPushNode iVisited = (ArgsPushNode) node; RubyArray args = (RubyArray) evalInternal(context, iVisited.getFirstNode(), self).dup(); return args.append(evalInternal(context, iVisited.getSecondNode(), self)); } // case NodeTypes.ARGSNODE: // EvaluateVisitor.argsNodeVisitor.execute(this, node); // break; // case NodeTypes.ARGUMENTNODE: // EvaluateVisitor.argumentNodeVisitor.execute(this, node); // break; case NodeTypes.ARRAYNODE: { ArrayNode iVisited = (ArrayNode) node; IRubyObject[] array = new IRubyObject[iVisited.size()]; int i = 0; for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node next = (Node) iterator.next(); array[i++] = evalInternal(context, next, self); } return runtime.newArray(array); } // case NodeTypes.ASSIGNABLENODE: // EvaluateVisitor.assignableNodeVisitor.execute(this, node); // break; case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); receiver.callMethod(context, iVisited.getName(), args, callType); return args[args.length - 1]; } case NodeTypes.BACKREFNODE: { BackRefNode iVisited = (BackRefNode) node; IRubyObject backref = context.getBackref(); switch (iVisited.getType()) { case '~': return backref; case '&': return RubyRegexp.last_match(backref); case '`': return RubyRegexp.match_pre(backref); case '\'': return RubyRegexp.match_post(backref); case '+': return RubyRegexp.match_last(backref); } break; } case NodeTypes.BEGINNODE: { BeginNode iVisited = (BeginNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.BIGNUMNODE: { BignumNode iVisited = (BignumNode) node; return RubyBignum.newBignum(runtime, iVisited.getValue()); } // case NodeTypes.BINARYOPERATORNODE: // EvaluateVisitor.binaryOperatorNodeVisitor.execute(this, node); // break; // case NodeTypes.BLOCKARGNODE: // EvaluateVisitor.blockArgNodeVisitor.execute(this, node); // break; case NodeTypes.BLOCKNODE: { BlockNode iVisited = (BlockNode) node; IRubyObject result = runtime.getNil(); for (Iterator iter = iVisited.iterator(); iter.hasNext();) { result = evalInternal(context, (Node) iter.next(), self); } return result; } case NodeTypes.BLOCKPASSNODE: { BlockPassNode iVisited = (BlockPassNode) node; IRubyObject proc = evalInternal(context, iVisited.getBodyNode(), self); if (proc.isNil()) { context.setNoBlock(); try { return evalInternal(context, iVisited.getIterNode(), self); } finally { context.clearNoBlock(); } } // If not already a proc then we should try and make it one. if (!(proc instanceof RubyProc)) { proc = proc.convertToType("Proc", "to_proc", false); if (!(proc instanceof RubyProc)) { throw runtime.newTypeError("wrong argument type " + proc.getMetaClass().getName() + " (expected Proc)"); } } // TODO: Add safety check for taintedness Block block = (Block) context.getCurrentBlock(); if (block != null) { IRubyObject blockObject = block.getBlockObject(); // The current block is already associated with the proc. No need to create new // block for it. Just eval! if (blockObject != null && blockObject == proc) { try { context.setBlockAvailable(); return evalInternal(context, iVisited.getIterNode(), self); } finally { context.clearBlockAvailable(); } } } context.preBlockPassEval(((RubyProc) proc).getBlock()); try { return evalInternal(context, iVisited.getIterNode(), self); } finally { context.postBlockPassEval(); } } case NodeTypes.BREAKNODE: { BreakNode iVisited = (BreakNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); JumpException je = new JumpException(JumpException.JumpType.BreakJump); je.setPrimaryData(result); je.setSecondaryData(node); throw je; } case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; IterNode iterNode = iVisited.getIterNode(); IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); // if no block passed, do a simple call if (iterNode == null) { return receiver.callMethod(context, iVisited.getName(), args, callType); } // if block passed, prepare the block and then do the call, handling breaks and retries correctly context.preIterEval(Block.createBlock(context, iterNode.getVarNode(), new DynamicScope(iterNode.getScope(), context.getCurrentScope()), iterNode.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return receiver.callMethod(context, iVisited.getName(), args, callType); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.CASENODE: { CaseNode iVisited = (CaseNode) node; IRubyObject expression = null; if (iVisited.getCaseNode() != null) { expression = evalInternal(context, iVisited.getCaseNode(), self); } context.pollThreadEvents(); IRubyObject result = runtime.getNil(); Node firstWhenNode = iVisited.getFirstWhenNode(); while (firstWhenNode != null) { if (!(firstWhenNode instanceof WhenNode)) { node = firstWhenNode; continue bigloop; } WhenNode whenNode = (WhenNode) firstWhenNode; if (whenNode.getExpressionNodes() instanceof ArrayNode) { for (Iterator iter = ((ArrayNode) whenNode.getExpressionNodes()).iterator(); iter .hasNext();) { Node tag = (Node) iter.next(); context.setPosition(tag.getPosition()); if (isTrace(runtime)) { callTraceFunction(context, "line", self); } // Ruby grammar has nested whens in a case body because of // productions case_body and when_args. if (tag instanceof WhenNode) { RubyArray expressions = (RubyArray) evalInternal(context, ((WhenNode) tag) .getExpressionNodes(), self); for (int j = 0; j < expressions.getLength(); j++) { IRubyObject condition = expressions.entry(j); if ((expression != null && condition.callMethod(context, "===", expression) .isTrue()) || (expression == null && condition.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } continue; } result = evalInternal(context, tag, self); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = whenNode.getBodyNode(); continue bigloop; } } } else { result = evalInternal(context, whenNode.getExpressionNodes(), self); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } context.pollThreadEvents(); firstWhenNode = whenNode.getNextCase(); } return runtime.getNil(); } case NodeTypes.CLASSNODE: { ClassNode iVisited = (ClassNode) node; Node superNode = iVisited.getSuperNode(); RubyClass superClass = superNode == null ? null : (RubyClass) evalInternal(context, superNode, self); Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingClass = getEnclosingModule(context, classNameNode, self); RubyClass rubyClass = enclosingClass.defineOrGetClassUnder(name, superClass); if (context.getWrapper() != null) { rubyClass.extendObject(context.getWrapper()); rubyClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), rubyClass, self); } case NodeTypes.CLASSVARASGNNODE: { ClassVarAsgnNode iVisited = (ClassVarAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); RubyModule rubyClass = (RubyModule) context.peekCRef().getValue(); if (rubyClass == null) { rubyClass = self.getMetaClass(); } else if (rubyClass.isSingleton()) { rubyClass = (RubyModule) rubyClass.getInstanceVariable("__attached__"); } rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARDECLNODE: { ClassVarDeclNode iVisited = (ClassVarDeclNode) node; // FIXME: shouldn't we use cref here? if (context.getRubyClass() == null) { throw runtime.newTypeError("no class/module to define class variable"); } IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); ((RubyModule) context.peekCRef().getValue()).setClassVar(iVisited.getName(), result); return runtime.getNil(); } case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; RubyModule rubyClass = (RubyModule) context.peekCRef().getValue(); if (rubyClass == null) { rubyClass = self.getMetaClass(); } else if (rubyClass.isSingleton()) { rubyClass = (RubyModule)rubyClass.getInstanceVariable("__attached__"); } return rubyClass.getClassVar(iVisited.getName()); } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; Node leftNode = iVisited.getLeftNode(); // TODO: Made this more colon3 friendly because of cpath production // rule in grammar (it is convenient to think of them as the same thing // at a grammar level even though evaluation is). if (leftNode == null) { return runtime.getObject().getConstantFrom(iVisited.getName()); } else { IRubyObject result = evalInternal(context, iVisited.getLeftNode(), self); if (result instanceof RubyModule) { return ((RubyModule) result).getConstantFrom(iVisited.getName()); } else { return result.callMethod(context, iVisited.getName()); } } } case NodeTypes.COLON3NODE: { Colon3Node iVisited = (Colon3Node) node; return runtime.getObject().getConstantFrom(iVisited.getName()); } case NodeTypes.CONSTDECLNODE: { ConstDeclNode iVisited = (ConstDeclNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); IRubyObject module; if (iVisited.getPathNode() != null) { module = evalInternal(context, iVisited.getPathNode(), self); } else { // FIXME: why do we check RubyClass and then use CRef? if (context.getRubyClass() == null) { // TODO: wire into new exception handling mechanism throw runtime.newTypeError("no class/module to define constant"); } module = (RubyModule) context.peekCRef().getValue(); } // FIXME: shouldn't we use the result of this set in setResult? ((RubyModule) module).setConstant(iVisited.getName(), result); return result; } case NodeTypes.CONSTNODE: { ConstNode iVisited = (ConstNode) node; return context.getConstant(iVisited.getName()); } case NodeTypes.DASGNNODE: { DAsgnNode iVisited = (DAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // System.out.println("DSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.DEFINEDNODE: { DefinedNode iVisited = (DefinedNode) node; String definition = getDefinition(context, iVisited.getExpressionNode(), self); if (definition != null) { return runtime.newString(definition); } else { return runtime.getNil(); } } case NodeTypes.DEFNNODE: { DefnNode iVisited = (DefnNode) node; RubyModule containingClass = context.getRubyClass(); if (containingClass == null) { throw runtime.newTypeError("No class to add method."); } String name = iVisited.getName(); if (containingClass == runtime.getObject() && name == "initialize") { runtime.getWarnings().warn("redefining Object#initialize may cause infinite loop"); } Visibility visibility = context.getCurrentVisibility(); if (name == "initialize" || visibility.isModuleFunction()) { visibility = Visibility.PRIVATE; } if (containingClass.isSingleton()) { IRubyObject attachedObject = ((MetaClass) containingClass).getAttachedObject(); if (!attachedObject.singletonMethodsAllowed()) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + attachedObject.getType()); } } DefaultMethod newMethod = new DefaultMethod(containingClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), visibility, context.peekCRef()); containingClass.addMethod(name, newMethod); if (context.getCurrentVisibility().isModuleFunction()) { containingClass.getSingletonClass().addMethod( name, new WrapperMethod(containingClass.getSingletonClass(), newMethod, Visibility.PUBLIC)); containingClass.callMethod(context, "singleton_method_added", runtime.newSymbol(name)); } // 'class << state.self' and 'class << obj' uses defn as opposed to defs if (containingClass.isSingleton()) { ((MetaClass) containingClass).getAttachedObject().callMethod( context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); } else { containingClass.callMethod(context, "method_added", runtime.newSymbol(name)); } return runtime.getNil(); } case NodeTypes.DEFSNODE: { DefsNode iVisited = (DefsNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); RubyClass rubyClass; if (receiver.isNil()) { rubyClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { rubyClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { rubyClass = runtime.getClass("FalseClass"); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure; can't define singleton method."); } if (receiver.isFrozen()) { throw runtime.newFrozenError("object"); } if (!receiver.singletonMethodsAllowed()) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + receiver.getType()); } rubyClass = receiver.getSingletonClass(); } if (runtime.getSafeLevel() >= 4) { ICallable method = (ICallable) rubyClass.getMethods().get(iVisited.getName()); if (method != null) { throw runtime.newSecurityError("Redefining method prohibited."); } } DefaultMethod newMethod = new DefaultMethod(rubyClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), Visibility.PUBLIC, context.peekCRef()); rubyClass.addMethod(iVisited.getName(), newMethod); receiver.callMethod(context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); return runtime.getNil(); } case NodeTypes.DOTNODE: { DotNode iVisited = (DotNode) node; return RubyRange.newRange(runtime, evalInternal(context, iVisited.getBeginNode(), self), evalInternal(context, iVisited .getEndNode(), self), iVisited.isExclusive()); } case NodeTypes.DREGEXPNODE: { DRegexpNode iVisited = (DRegexpNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } return RubyRegexp.newRegexp(runtime, sb.toString(), iVisited.getOptions(), lang); } case NodeTypes.DSTRNODE: { DStrNode iVisited = (DStrNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return runtime.newString(sb.toString()); } case NodeTypes.DSYMBOLNODE: { DSymbolNode iVisited = (DSymbolNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.getNode().iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return runtime.newSymbol(sb.toString()); } case NodeTypes.DVARNODE: { DVarNode iVisited = (DVarNode) node; // System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject obj = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); // FIXME: null check is removable once we figure out how to assign to unset named block args return obj == null ? runtime.getNil() : obj; } case NodeTypes.DXSTRNODE: { DXStrNode iVisited = (DXStrNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return self.callMethod(context, "`", runtime.newString(sb.toString())); } case NodeTypes.ENSURENODE: { EnsureNode iVisited = (EnsureNode) node; // save entering the try if there's nothing to ensure if (iVisited.getEnsureNode() != null) { IRubyObject result = runtime.getNil(); try { result = evalInternal(context, iVisited.getBodyNode(), self); } finally { evalInternal(context, iVisited.getEnsureNode(), self); } return result; } node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.EVSTRNODE: { EvStrNode iVisited = (EvStrNode) node; node = iVisited.getBody(); continue bigloop; } case NodeTypes.FALSENODE: { context.pollThreadEvents(); return runtime.getFalse(); } case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; IterNode iterNode = iVisited.getIterNode(); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); // if no block passed, do a simple call if (iterNode == null) { return self.callMethod(context, iVisited.getName(), args, CallType.FUNCTIONAL); } // if block passed, prepare the block and then do the call, handling breaks and retries correctly context.preIterEval(Block.createBlock(context, iterNode.getVarNode(), new DynamicScope(iterNode.getScope(), context.getCurrentScope()), iterNode.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return self.callMethod(context, iVisited.getName(), args, CallType.FUNCTIONAL); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.FIXNUMNODE: { FixnumNode iVisited = (FixnumNode) node; return iVisited.getFixnum(runtime); } case NodeTypes.FLIPNODE: { FlipNode iVisited = (FlipNode) node; IRubyObject result = runtime.getNil(); if (iVisited.isExclusive()) { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { result = evalInternal(context, iVisited.getBeginNode(), self).isTrue() ? runtime.getFalse() : runtime.getTrue(); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } else { if (evalInternal(context, iVisited.getEndNode(), self).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } else { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { if (evalInternal(context, iVisited.getBeginNode(), self).isTrue()) { context.getCurrentScope().setValue( iVisited.getIndex(), evalInternal(context, iVisited.getEndNode(), self).isTrue() ? runtime.getFalse() : runtime.getTrue(), iVisited.getDepth()); return runtime.getTrue(); } else { return runtime.getFalse(); } } else { if (evalInternal(context, iVisited.getEndNode(), self).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } } case NodeTypes.FLOATNODE: { FloatNode iVisited = (FloatNode) node; return RubyFloat.newFloat(runtime, iVisited.getValue()); } case NodeTypes.FORNODE: { ForNode iVisited = (ForNode) node; // For nodes do not have to create an addition scope so we just pass null context.preForLoopEval(Block.createBlock(context, iVisited.getVarNode(), null, iVisited.getCallable(), self)); try { while (true) { try { ISourcePosition position = context.getPosition(); context.beginCallArgs(); IRubyObject recv = null; try { recv = evalInternal(context, iVisited.getIterNode(), self); } finally { context.setPosition(position); context.endCallArgs(); } return recv.callMethod(context, "each", IRubyObject.NULL_ARRAY, CallType.NORMAL); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // do nothing, allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postForLoopEval(); } } case NodeTypes.GLOBALASGNNODE: { GlobalAsgnNode iVisited = (GlobalAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); runtime.getGlobalVariables().set(iVisited.getName(), result); return result; } case NodeTypes.GLOBALVARNODE: { GlobalVarNode iVisited = (GlobalVarNode) node; return runtime.getGlobalVariables().get(iVisited.getName()); } case NodeTypes.HASHNODE: { HashNode iVisited = (HashNode) node; Map hash = null; if (iVisited.getListNode() != null) { hash = new HashMap(iVisited.getListNode().size() / 2); for (Iterator iterator = iVisited.getListNode().iterator(); iterator.hasNext();) { // insert all nodes in sequence, hash them in the final instruction // KEY IRubyObject key = evalInternal(context, (Node) iterator.next(), self); IRubyObject value = evalInternal(context, (Node) iterator.next(), self); hash.put(key, value); } } if (hash == null) { return RubyHash.newHash(runtime); } return RubyHash.newHash(runtime, hash, runtime.getNil()); } case NodeTypes.IFNODE: { IfNode iVisited = (IfNode) node; IRubyObject result = evalInternal(context, iVisited.getCondition(), self); if (result.isTrue()) { node = iVisited.getThenBody(); continue bigloop; } else { node = iVisited.getElseBody(); continue bigloop; } } case NodeTypes.INSTASGNNODE: { InstAsgnNode iVisited = (InstAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); self.setInstanceVariable(iVisited.getName(), result); return result; } case NodeTypes.INSTVARNODE: { InstVarNode iVisited = (InstVarNode) node; IRubyObject variable = self.getInstanceVariable(iVisited.getName()); return variable == null ? runtime.getNil() : variable; } // case NodeTypes.ISCOPINGNODE: // EvaluateVisitor.iScopingNodeVisitor.execute(this, node); // break; case NodeTypes.ITERNODE: { IterNode iVisited = (IterNode) node; // new-style handling of blocks, for nodes that support it // don't process the block until it's needed, to avoid nasty iter tricks if (iVisited.getIterNode() instanceof BlockAcceptingNode) { ((BlockAcceptingNode)iVisited.getIterNode()).setIterNode(iVisited); node = iVisited.getIterNode(); continue bigloop; } // otherwise do it the same as the old way context.preIterEval(Block.createBlock(context, iVisited.getVarNode(), new DynamicScope(iVisited.getScope(), context.getCurrentScope()), iVisited.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return evalInternal(context, iVisited.getIterNode(), self); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.LOCALASGNNODE: { LocalAsgnNode iVisited = (LocalAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // System.out.println("LSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.LOCALVARNODE: { LocalVarNode iVisited = (LocalVarNode) node; //System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject result = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); return result == null ? runtime.getNil() : result; } case NodeTypes.MATCH2NODE: { Match2Node iVisited = (Match2Node) node; IRubyObject recv = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = evalInternal(context, iVisited.getValueNode(), self); return ((RubyRegexp) recv).match(value); } case NodeTypes.MATCH3NODE: { Match3Node iVisited = (Match3Node) node; IRubyObject recv = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = evalInternal(context, iVisited.getValueNode(), self); if (value instanceof RubyString) { return ((RubyRegexp) recv).match(value); } else { return value.callMethod(context, "=~", recv); } } case NodeTypes.MATCHNODE: { MatchNode iVisited = (MatchNode) node; return ((RubyRegexp) evalInternal(context, iVisited.getRegexpNode(), self)).match2(); } case NodeTypes.MODULENODE: { ModuleNode iVisited = (ModuleNode) node; Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingModule = getEnclosingModule(context, classNameNode, self); if (enclosingModule == null) { throw runtime.newTypeError("no outer class/module"); } RubyModule module; if (enclosingModule == runtime.getObject()) { module = runtime.getOrCreateModule(name); } else { module = enclosingModule.defineModuleUnder(name); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), module, self); } case NodeTypes.MULTIPLEASGNNODE: { MultipleAsgnNode iVisited = (MultipleAsgnNode) node; return AssignmentVisitor.assign(context, self, iVisited, evalInternal(context, iVisited.getValueNode(), self), false); } case NodeTypes.NEWLINENODE: { NewlineNode iVisited = (NewlineNode) node; // something in here is used to build up ruby stack trace... context.setPosition(iVisited.getPosition()); if (isTrace(runtime)) { callTraceFunction(context, "line", self); } // TODO: do above but not below for additional newline nodes node = iVisited.getNextNode(); continue bigloop; } case NodeTypes.NEXTNODE: { NextNode iVisited = (NextNode) node; context.pollThreadEvents(); IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.NextJump); je.setPrimaryData(result); je.setSecondaryData(iVisited); //state.setCurrentException(je); throw je; } case NodeTypes.NILNODE: return runtime.getNil(); case NodeTypes.NOTNODE: { NotNode iVisited = (NotNode) node; IRubyObject result = evalInternal(context, iVisited.getConditionNode(), self); return result.isTrue() ? runtime.getFalse() : runtime.getTrue(); } case NodeTypes.NTHREFNODE: { NthRefNode iVisited = (NthRefNode) node; return RubyRegexp.nth_match(iVisited.getMatchNumber(), context.getBackref()); } case NodeTypes.OPASGNANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; // add in reverse order IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.OPASGNNODE: { OpAsgnNode iVisited = (OpAsgnNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = receiver.callMethod(context, iVisited.getVariableName()); if (iVisited.getOperatorName() == "||") { if (value.isTrue()) { return value; } value = evalInternal(context, iVisited.getValueNode(), self); } else if (iVisited.getOperatorName() == "&&") { if (!value.isTrue()) { return value; } value = evalInternal(context, iVisited.getValueNode(), self); } else { value = value.callMethod(context, iVisited.getOperatorName(), evalInternal(context, iVisited.getValueNode(), self)); } receiver.callMethod(context, iVisited.getVariableNameAsgn(), value); context.pollThreadEvents(); return value; } case NodeTypes.OPASGNORNODE: { OpAsgnOrNode iVisited = (OpAsgnOrNode) node; String def = getDefinition(context, iVisited.getFirstNode(), self); IRubyObject result = runtime.getNil(); if (def != null) { result = evalInternal(context, iVisited.getFirstNode(), self); } if (!result.isTrue()) { result = evalInternal(context, iVisited.getSecondNode(), self); } return result; } case NodeTypes.OPELEMENTASGNNODE: { OpElementAsgnNode iVisited = (OpElementAsgnNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); IRubyObject firstValue = receiver.callMethod(context, "[]", args); if (iVisited.getOperatorName() == "||") { if (firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(context, iVisited.getValueNode(), self); } else if (iVisited.getOperatorName() == "&&") { if (!firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(context, iVisited.getValueNode(), self); } else { firstValue = firstValue.callMethod(context, iVisited.getOperatorName(), evalInternal(context, iVisited .getValueNode(), self)); } IRubyObject[] expandedArgs = new IRubyObject[args.length + 1]; System.arraycopy(args, 0, expandedArgs, 0, args.length); expandedArgs[expandedArgs.length - 1] = firstValue; return receiver.callMethod(context, "[]=", expandedArgs); } case NodeTypes.OPTNNODE: { OptNNode iVisited = (OptNNode) node; IRubyObject result = runtime.getNil(); while (RubyKernel.gets(runtime.getTopSelf(), IRubyObject.NULL_ARRAY).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(context, iVisited.getBodyNode(), self); break; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: // do nothing, this iteration restarts break; case JumpType.NEXT: // recheck condition break loop; case JumpType.BREAK: // end loop return (IRubyObject) je.getPrimaryData(); default: throw je; } } } } return result; } case NodeTypes.ORNODE: { OrNode iVisited = (OrNode) node; IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) { result = evalInternal(context, iVisited.getSecondNode(), self); } return result; } // case NodeTypes.POSTEXENODE: // EvaluateVisitor.postExeNodeVisitor.execute(this, node); // break; case NodeTypes.REDONODE: { context.pollThreadEvents(); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.RedoJump); je.setSecondaryData(node); throw je; } case NodeTypes.REGEXPNODE: { RegexpNode iVisited = (RegexpNode) node; String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } try { return RubyRegexp.newRegexp(runtime, iVisited.getPattern(), lang); } catch(java.util.regex.PatternSyntaxException e) { throw runtime.newSyntaxError(e.getMessage()); } } case NodeTypes.RESCUEBODYNODE: { RescueBodyNode iVisited = (RescueBodyNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.RESCUENODE: { RescueNode iVisited = (RescueNode)node; RescuedBlock : while (true) { IRubyObject globalExceptionState = runtime.getGlobalVariables().get("$!"); boolean anotherExceptionRaised = false; try { // Execute rescue block IRubyObject result = evalInternal(context, iVisited.getBodyNode(), self); // If no exception is thrown execute else block if (iVisited.getElseNode() != null) { if (iVisited.getRescueNode() == null) { runtime.getWarnings().warn(iVisited.getElseNode().getPosition(), "else without rescue is useless"); } result = evalInternal(context, iVisited.getElseNode(), self); } return result; } catch (RaiseException raiseJump) { RubyException raisedException = raiseJump.getException(); // TODO: Rubicon TestKernel dies without this line. A cursory glance implies we // falsely set $! to nil and this sets it back to something valid. This should // get fixed at the same time we address bug #1296484. runtime.getGlobalVariables().set("$!", raisedException); RescueBodyNode rescueNode = iVisited.getRescueNode(); while (rescueNode != null) { Node exceptionNodes = rescueNode.getExceptionNodes(); ListNode exceptionNodesList; if (exceptionNodes instanceof SplatNode) { exceptionNodesList = (ListNode) evalInternal(context, exceptionNodes, self); } else { exceptionNodesList = (ListNode) exceptionNodes; } if (isRescueHandled(context, raisedException, exceptionNodesList, self)) { try { return evalInternal(context, rescueNode, self); } catch (JumpException je) { if (je.getJumpType() == JumpException.JumpType.RetryJump) { // should be handled in the finally block below //state.runtime.getGlobalVariables().set("$!", state.runtime.getNil()); //state.threadContext.setRaisedException(null); continue RescuedBlock; } else { anotherExceptionRaised = true; throw je; } } } rescueNode = rescueNode.getOptRescueNode(); } // no takers; bubble up throw raiseJump; } finally { // clear exception when handled or retried if (!anotherExceptionRaised) runtime.getGlobalVariables().set("$!", globalExceptionState); } } } case NodeTypes.RETRYNODE: { context.pollThreadEvents(); JumpException je = new JumpException(JumpException.JumpType.RetryJump); throw je; } case NodeTypes.RETURNNODE: { ReturnNode iVisited = (ReturnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); JumpException je = new JumpException(JumpException.JumpType.ReturnJump); je.setPrimaryData(iVisited.getTarget()); je.setSecondaryData(result); je.setTertiaryData(iVisited); throw je; } case NodeTypes.ROOTNODE: { RootNode iVisited = (RootNode) node; DynamicScope scope = iVisited.getScope(); // Serialization killed our dynamic scope. We can just create an empty one // since serialization cannot serialize an eval (which is the only thing // which is capable of having a non-empty dynamic scope). if (scope == null) { scope = new DynamicScope(iVisited.getStaticScope(), null); } // Each root node has a top-level scope that we need to push context.preRootNode(scope); // FIXME: Wire up BEGIN and END nodes try { return eval(context, iVisited.getBodyNode(), self); } finally { context.postRootNode(); } } case NodeTypes.SCLASSNODE: { SClassNode iVisited = (SClassNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); RubyClass singletonClass; if (receiver.isNil()) { singletonClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { singletonClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { singletonClass = runtime.getClass("FalseClass"); } else if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("no virtual class for " + receiver.getMetaClass().getBaseName()); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure: can't extend object."); } singletonClass = receiver.getSingletonClass(); } if (context.getWrapper() != null) { singletonClass.extendObject(context.getWrapper()); singletonClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), singletonClass, self); } case NodeTypes.SELFNODE: return self; case NodeTypes.SPLATNODE: { SplatNode iVisited = (SplatNode) node; return splatValue(evalInternal(context, iVisited.getValue(), self)); } //// case NodeTypes.STARNODE: //// EvaluateVisitor.starNodeVisitor.execute(this, node); //// break; case NodeTypes.STRNODE: { StrNode iVisited = (StrNode) node; return runtime.newString(iVisited.getValue()); } case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; if (context.getFrameLastClass() == null) { String name = context.getFrameLastFunc(); throw runtime.newNameError("Superclass method '" + name + "' disabled.", name); } context.beginCallArgs(); IRubyObject[] args = null; try { args = setupArgs(context, iVisited.getArgsNode(), self); } finally { context.endCallArgs(); } return context.callSuper(args); } case NodeTypes.SVALUENODE: { SValueNode iVisited = (SValueNode) node; return aValueSplat(evalInternal(context, iVisited.getValue(), self)); } case NodeTypes.SYMBOLNODE: { SymbolNode iVisited = (SymbolNode) node; return runtime.newSymbol(iVisited.getName()); } case NodeTypes.TOARYNODE: { ToAryNode iVisited = (ToAryNode) node; return aryToAry(evalInternal(context, iVisited.getValue(), self)); } case NodeTypes.TRUENODE: { context.pollThreadEvents(); return runtime.getTrue(); } case NodeTypes.UNDEFNODE: { UndefNode iVisited = (UndefNode) node; if (context.getRubyClass() == null) { throw runtime .newTypeError("No class to undef method '" + iVisited.getName() + "'."); } context.getRubyClass().undef(iVisited.getName()); return runtime.getNil(); } case NodeTypes.UNTILNODE: { UntilNode iVisited = (UntilNode) node; IRubyObject result = runtime.getNil(); while (!(result = evalInternal(context, iVisited.getConditionNode(), self)).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(context, iVisited.getBodyNode(), self); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: return (IRubyObject) je.getPrimaryData(); default: throw je; } } } } return result; } case NodeTypes.VALIASNODE: { VAliasNode iVisited = (VAliasNode) node; runtime.getGlobalVariables().alias(iVisited.getNewName(), iVisited.getOldName()); return runtime.getNil(); } case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; return self.callMethod(context, iVisited.getName(), IRubyObject.NULL_ARRAY, CallType.VARIABLE); } case NodeTypes.WHENNODE: assert false; return null; case NodeTypes.WHILENODE: { WhileNode iVisited = (WhileNode) node; IRubyObject result = runtime.getNil(); boolean firstTest = iVisited.evaluateAtStart(); while (!firstTest || (result = evalInternal(context, iVisited.getConditionNode(), self)).isTrue()) { firstTest = true; loop: while (true) { // Used for the 'redo' command try { evalInternal(context, iVisited.getBodyNode(), self); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: return result; default: throw je; } } } } return result; } case NodeTypes.XSTRNODE: { XStrNode iVisited = (XStrNode) node; return self.callMethod(context, "`", runtime.newString(iVisited.getValue())); } case NodeTypes.YIELDNODE: { YieldNode iVisited = (YieldNode) node; IRubyObject result = evalInternal(context, iVisited.getArgsNode(), self); if (iVisited.getArgsNode() == null) { result = null; } return context.yieldCurrentBlock(result, null, null, iVisited.getCheckState()); } case NodeTypes.ZARRAYNODE: { return runtime.newArray(); } case NodeTypes.ZSUPERNODE: { if (context.getFrameLastClass() == null) { String name = context.getFrameLastFunc(); throw runtime.newNameError("superclass method '" + name + "' disabled", name); } return context.callSuper(context.getFrameArgs(), true); } } } while (true); }
private static IRubyObject evalInternal(ThreadContext context, Node node, IRubyObject self) { IRuby runtime = context.getRuntime(); bigloop: do { if (node == null) return runtime.getNil(); switch (node.nodeId) { case NodeTypes.ALIASNODE: { AliasNode iVisited = (AliasNode) node; if (context.getRubyClass() == null) { throw runtime.newTypeError("no class to make alias"); } context.getRubyClass().defineAlias(iVisited.getNewName(), iVisited.getOldName()); context.getRubyClass().callMethod(context, "method_added", runtime.newSymbol(iVisited.getNewName())); return runtime.getNil(); } case NodeTypes.ANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.ARGSCATNODE: { ArgsCatNode iVisited = (ArgsCatNode) node; IRubyObject args = evalInternal(context, iVisited.getFirstNode(), self); IRubyObject secondArgs = splatValue(evalInternal(context, iVisited.getSecondNode(), self)); RubyArray list = args instanceof RubyArray ? (RubyArray) args : runtime.newArray(args); return list.concat(secondArgs); } case NodeTypes.ARGSPUSHNODE: { ArgsPushNode iVisited = (ArgsPushNode) node; RubyArray args = (RubyArray) evalInternal(context, iVisited.getFirstNode(), self).dup(); return args.append(evalInternal(context, iVisited.getSecondNode(), self)); } // case NodeTypes.ARGSNODE: // EvaluateVisitor.argsNodeVisitor.execute(this, node); // break; // case NodeTypes.ARGUMENTNODE: // EvaluateVisitor.argumentNodeVisitor.execute(this, node); // break; case NodeTypes.ARRAYNODE: { ArrayNode iVisited = (ArrayNode) node; IRubyObject[] array = new IRubyObject[iVisited.size()]; int i = 0; for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node next = (Node) iterator.next(); array[i++] = evalInternal(context, next, self); } return runtime.newArray(array); } // case NodeTypes.ASSIGNABLENODE: // EvaluateVisitor.assignableNodeVisitor.execute(this, node); // break; case NodeTypes.ATTRASSIGNNODE: { AttrAssignNode iVisited = (AttrAssignNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); receiver.callMethod(context, iVisited.getName(), args, callType); return args[args.length - 1]; } case NodeTypes.BACKREFNODE: { BackRefNode iVisited = (BackRefNode) node; IRubyObject backref = context.getBackref(); switch (iVisited.getType()) { case '~': return backref; case '&': return RubyRegexp.last_match(backref); case '`': return RubyRegexp.match_pre(backref); case '\'': return RubyRegexp.match_post(backref); case '+': return RubyRegexp.match_last(backref); } break; } case NodeTypes.BEGINNODE: { BeginNode iVisited = (BeginNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.BIGNUMNODE: { BignumNode iVisited = (BignumNode) node; return RubyBignum.newBignum(runtime, iVisited.getValue()); } // case NodeTypes.BINARYOPERATORNODE: // EvaluateVisitor.binaryOperatorNodeVisitor.execute(this, node); // break; // case NodeTypes.BLOCKARGNODE: // EvaluateVisitor.blockArgNodeVisitor.execute(this, node); // break; case NodeTypes.BLOCKNODE: { BlockNode iVisited = (BlockNode) node; IRubyObject result = runtime.getNil(); for (Iterator iter = iVisited.iterator(); iter.hasNext();) { result = evalInternal(context, (Node) iter.next(), self); } return result; } case NodeTypes.BLOCKPASSNODE: { BlockPassNode iVisited = (BlockPassNode) node; IRubyObject proc = evalInternal(context, iVisited.getBodyNode(), self); if (proc.isNil()) { context.setNoBlock(); try { return evalInternal(context, iVisited.getIterNode(), self); } finally { context.clearNoBlock(); } } // If not already a proc then we should try and make it one. if (!(proc instanceof RubyProc)) { proc = proc.convertToType("Proc", "to_proc", false); if (!(proc instanceof RubyProc)) { throw runtime.newTypeError("wrong argument type " + proc.getMetaClass().getName() + " (expected Proc)"); } } // TODO: Add safety check for taintedness Block block = (Block) context.getCurrentBlock(); if (block != null) { IRubyObject blockObject = block.getBlockObject(); // The current block is already associated with the proc. No need to create new // block for it. Just eval! if (blockObject != null && blockObject == proc) { try { context.setBlockAvailable(); return evalInternal(context, iVisited.getIterNode(), self); } finally { context.clearBlockAvailable(); } } } context.preBlockPassEval(((RubyProc) proc).getBlock()); try { return evalInternal(context, iVisited.getIterNode(), self); } finally { context.postBlockPassEval(); } } case NodeTypes.BREAKNODE: { BreakNode iVisited = (BreakNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); JumpException je = new JumpException(JumpException.JumpType.BreakJump); je.setPrimaryData(result); je.setSecondaryData(node); throw je; } case NodeTypes.CALLNODE: { CallNode iVisited = (CallNode) node; IterNode iterNode = iVisited.getIterNode(); IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); assert receiver.getMetaClass() != null : receiver.getClass().getName(); // If reciever is self then we do the call the same way as vcall CallType callType = (receiver == self ? CallType.VARIABLE : CallType.NORMAL); // if no block passed, do a simple call if (iterNode == null) { return receiver.callMethod(context, iVisited.getName(), args, callType); } // if block passed, prepare the block and then do the call, handling breaks and retries correctly context.preIterEval(Block.createBlock(context, iterNode.getVarNode(), new DynamicScope(iterNode.getScope(), context.getCurrentScope()), iterNode.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return receiver.callMethod(context, iVisited.getName(), args, callType); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.CASENODE: { CaseNode iVisited = (CaseNode) node; IRubyObject expression = null; if (iVisited.getCaseNode() != null) { expression = evalInternal(context, iVisited.getCaseNode(), self); } context.pollThreadEvents(); IRubyObject result = runtime.getNil(); Node firstWhenNode = iVisited.getFirstWhenNode(); while (firstWhenNode != null) { if (!(firstWhenNode instanceof WhenNode)) { node = firstWhenNode; continue bigloop; } WhenNode whenNode = (WhenNode) firstWhenNode; if (whenNode.getExpressionNodes() instanceof ArrayNode) { for (Iterator iter = ((ArrayNode) whenNode.getExpressionNodes()).iterator(); iter .hasNext();) { Node tag = (Node) iter.next(); context.setPosition(tag.getPosition()); if (isTrace(runtime)) { callTraceFunction(context, "line", self); } // Ruby grammar has nested whens in a case body because of // productions case_body and when_args. if (tag instanceof WhenNode) { RubyArray expressions = (RubyArray) evalInternal(context, ((WhenNode) tag) .getExpressionNodes(), self); for (int j = 0; j < expressions.getLength(); j++) { IRubyObject condition = expressions.entry(j); if ((expression != null && condition.callMethod(context, "===", expression) .isTrue()) || (expression == null && condition.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } continue; } result = evalInternal(context, tag, self); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = whenNode.getBodyNode(); continue bigloop; } } } else { result = evalInternal(context, whenNode.getExpressionNodes(), self); if ((expression != null && result.callMethod(context, "===", expression).isTrue()) || (expression == null && result.isTrue())) { node = ((WhenNode) firstWhenNode).getBodyNode(); continue bigloop; } } context.pollThreadEvents(); firstWhenNode = whenNode.getNextCase(); } return runtime.getNil(); } case NodeTypes.CLASSNODE: { ClassNode iVisited = (ClassNode) node; Node superNode = iVisited.getSuperNode(); RubyClass superClass = superNode == null ? null : (RubyClass) evalInternal(context, superNode, self); Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingClass = getEnclosingModule(context, classNameNode, self); RubyClass rubyClass = enclosingClass.defineOrGetClassUnder(name, superClass); if (context.getWrapper() != null) { rubyClass.extendObject(context.getWrapper()); rubyClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), rubyClass, self); } case NodeTypes.CLASSVARASGNNODE: { ClassVarAsgnNode iVisited = (ClassVarAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); RubyModule rubyClass = (RubyModule) context.peekCRef().getValue(); if (rubyClass == null) { rubyClass = self.getMetaClass(); } else if (rubyClass.isSingleton()) { rubyClass = (RubyModule) rubyClass.getInstanceVariable("__attached__"); } rubyClass.setClassVar(iVisited.getName(), result); return result; } case NodeTypes.CLASSVARDECLNODE: { ClassVarDeclNode iVisited = (ClassVarDeclNode) node; // FIXME: shouldn't we use cref here? if (context.getRubyClass() == null) { throw runtime.newTypeError("no class/module to define class variable"); } IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); ((RubyModule) context.peekCRef().getValue()).setClassVar(iVisited.getName(), result); return runtime.getNil(); } case NodeTypes.CLASSVARNODE: { ClassVarNode iVisited = (ClassVarNode) node; RubyModule rubyClass = (RubyModule) context.peekCRef().getValue(); if (rubyClass == null) { rubyClass = self.getMetaClass(); } else if (rubyClass.isSingleton()) { rubyClass = (RubyModule)rubyClass.getInstanceVariable("__attached__"); } return rubyClass.getClassVar(iVisited.getName()); } case NodeTypes.COLON2NODE: { Colon2Node iVisited = (Colon2Node) node; Node leftNode = iVisited.getLeftNode(); // TODO: Made this more colon3 friendly because of cpath production // rule in grammar (it is convenient to think of them as the same thing // at a grammar level even though evaluation is). if (leftNode == null) { return runtime.getObject().getConstantFrom(iVisited.getName()); } else { IRubyObject result = evalInternal(context, iVisited.getLeftNode(), self); if (result instanceof RubyModule) { return ((RubyModule) result).getConstantFrom(iVisited.getName()); } else { return result.callMethod(context, iVisited.getName()); } } } case NodeTypes.COLON3NODE: { Colon3Node iVisited = (Colon3Node) node; return runtime.getObject().getConstantFrom(iVisited.getName()); } case NodeTypes.CONSTDECLNODE: { ConstDeclNode iVisited = (ConstDeclNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); IRubyObject module; if (iVisited.getPathNode() != null) { module = evalInternal(context, iVisited.getPathNode(), self); } else { // FIXME: why do we check RubyClass and then use CRef? if (context.getRubyClass() == null) { // TODO: wire into new exception handling mechanism throw runtime.newTypeError("no class/module to define constant"); } module = (RubyModule) context.peekCRef().getValue(); } // FIXME: shouldn't we use the result of this set in setResult? ((RubyModule) module).setConstant(iVisited.getName(), result); return result; } case NodeTypes.CONSTNODE: { ConstNode iVisited = (ConstNode) node; return context.getConstant(iVisited.getName()); } case NodeTypes.DASGNNODE: { DAsgnNode iVisited = (DAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // System.out.println("DSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.DEFINEDNODE: { DefinedNode iVisited = (DefinedNode) node; String definition = getDefinition(context, iVisited.getExpressionNode(), self); if (definition != null) { return runtime.newString(definition); } else { return runtime.getNil(); } } case NodeTypes.DEFNNODE: { DefnNode iVisited = (DefnNode) node; RubyModule containingClass = context.getRubyClass(); if (containingClass == null) { throw runtime.newTypeError("No class to add method."); } String name = iVisited.getName(); if (containingClass == runtime.getObject() && name == "initialize") { runtime.getWarnings().warn("redefining Object#initialize may cause infinite loop"); } Visibility visibility = context.getCurrentVisibility(); if (name == "initialize" || visibility.isModuleFunction()) { visibility = Visibility.PRIVATE; } if (containingClass.isSingleton()) { IRubyObject attachedObject = ((MetaClass) containingClass).getAttachedObject(); if (!attachedObject.singletonMethodsAllowed()) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + attachedObject.getType()); } } DefaultMethod newMethod = new DefaultMethod(containingClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), visibility, context.peekCRef()); containingClass.addMethod(name, newMethod); if (context.getCurrentVisibility().isModuleFunction()) { containingClass.getSingletonClass().addMethod( name, new WrapperMethod(containingClass.getSingletonClass(), newMethod, Visibility.PUBLIC)); containingClass.callMethod(context, "singleton_method_added", runtime.newSymbol(name)); } // 'class << state.self' and 'class << obj' uses defn as opposed to defs if (containingClass.isSingleton()) { ((MetaClass) containingClass).getAttachedObject().callMethod( context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); } else { containingClass.callMethod(context, "method_added", runtime.newSymbol(name)); } return runtime.getNil(); } case NodeTypes.DEFSNODE: { DefsNode iVisited = (DefsNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); RubyClass rubyClass; if (receiver.isNil()) { rubyClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { rubyClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { rubyClass = runtime.getClass("FalseClass"); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure; can't define singleton method."); } if (receiver.isFrozen()) { throw runtime.newFrozenError("object"); } if (!receiver.singletonMethodsAllowed()) { throw runtime.newTypeError("can't define singleton method \"" + iVisited.getName() + "\" for " + receiver.getType()); } rubyClass = receiver.getSingletonClass(); } if (runtime.getSafeLevel() >= 4) { Object method = rubyClass.getMethods().get(iVisited.getName()); if (method != null) { throw runtime.newSecurityError("Redefining method prohibited."); } } DefaultMethod newMethod = new DefaultMethod(rubyClass, iVisited.getScope(), iVisited.getBodyNode(), (ArgsNode) iVisited.getArgsNode(), Visibility.PUBLIC, context.peekCRef()); rubyClass.addMethod(iVisited.getName(), newMethod); receiver.callMethod(context, "singleton_method_added", runtime.newSymbol(iVisited.getName())); return runtime.getNil(); } case NodeTypes.DOTNODE: { DotNode iVisited = (DotNode) node; return RubyRange.newRange(runtime, evalInternal(context, iVisited.getBeginNode(), self), evalInternal(context, iVisited .getEndNode(), self), iVisited.isExclusive()); } case NodeTypes.DREGEXPNODE: { DRegexpNode iVisited = (DRegexpNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } return RubyRegexp.newRegexp(runtime, sb.toString(), iVisited.getOptions(), lang); } case NodeTypes.DSTRNODE: { DStrNode iVisited = (DStrNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return runtime.newString(sb.toString()); } case NodeTypes.DSYMBOLNODE: { DSymbolNode iVisited = (DSymbolNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.getNode().iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return runtime.newSymbol(sb.toString()); } case NodeTypes.DVARNODE: { DVarNode iVisited = (DVarNode) node; // System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject obj = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); // FIXME: null check is removable once we figure out how to assign to unset named block args return obj == null ? runtime.getNil() : obj; } case NodeTypes.DXSTRNODE: { DXStrNode iVisited = (DXStrNode) node; StringBuffer sb = new StringBuffer(); for (Iterator iterator = iVisited.iterator(); iterator.hasNext();) { Node iterNode = (Node) iterator.next(); sb.append(evalInternal(context, iterNode, self).toString()); } return self.callMethod(context, "`", runtime.newString(sb.toString())); } case NodeTypes.ENSURENODE: { EnsureNode iVisited = (EnsureNode) node; // save entering the try if there's nothing to ensure if (iVisited.getEnsureNode() != null) { IRubyObject result = runtime.getNil(); try { result = evalInternal(context, iVisited.getBodyNode(), self); } finally { evalInternal(context, iVisited.getEnsureNode(), self); } return result; } node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.EVSTRNODE: { EvStrNode iVisited = (EvStrNode) node; node = iVisited.getBody(); continue bigloop; } case NodeTypes.FALSENODE: { context.pollThreadEvents(); return runtime.getFalse(); } case NodeTypes.FCALLNODE: { FCallNode iVisited = (FCallNode) node; IterNode iterNode = iVisited.getIterNode(); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); // if no block passed, do a simple call if (iterNode == null) { return self.callMethod(context, iVisited.getName(), args, CallType.FUNCTIONAL); } // if block passed, prepare the block and then do the call, handling breaks and retries correctly context.preIterEval(Block.createBlock(context, iterNode.getVarNode(), new DynamicScope(iterNode.getScope(), context.getCurrentScope()), iterNode.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return self.callMethod(context, iVisited.getName(), args, CallType.FUNCTIONAL); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.FIXNUMNODE: { FixnumNode iVisited = (FixnumNode) node; return iVisited.getFixnum(runtime); } case NodeTypes.FLIPNODE: { FlipNode iVisited = (FlipNode) node; IRubyObject result = runtime.getNil(); if (iVisited.isExclusive()) { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { result = evalInternal(context, iVisited.getBeginNode(), self).isTrue() ? runtime.getFalse() : runtime.getTrue(); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } else { if (evalInternal(context, iVisited.getEndNode(), self).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } else { if (!context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()).isTrue()) { if (evalInternal(context, iVisited.getBeginNode(), self).isTrue()) { context.getCurrentScope().setValue( iVisited.getIndex(), evalInternal(context, iVisited.getEndNode(), self).isTrue() ? runtime.getFalse() : runtime.getTrue(), iVisited.getDepth()); return runtime.getTrue(); } else { return runtime.getFalse(); } } else { if (evalInternal(context, iVisited.getEndNode(), self).isTrue()) { context.getCurrentScope().setValue(iVisited.getIndex(), runtime.getFalse(), iVisited.getDepth()); } return runtime.getTrue(); } } } case NodeTypes.FLOATNODE: { FloatNode iVisited = (FloatNode) node; return RubyFloat.newFloat(runtime, iVisited.getValue()); } case NodeTypes.FORNODE: { ForNode iVisited = (ForNode) node; // For nodes do not have to create an addition scope so we just pass null context.preForLoopEval(Block.createBlock(context, iVisited.getVarNode(), null, iVisited.getCallable(), self)); try { while (true) { try { ISourcePosition position = context.getPosition(); context.beginCallArgs(); IRubyObject recv = null; try { recv = evalInternal(context, iVisited.getIterNode(), self); } finally { context.setPosition(position); context.endCallArgs(); } return recv.callMethod(context, "each", IRubyObject.NULL_ARRAY, CallType.NORMAL); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // do nothing, allow loop to retry break; default: throw je; } } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postForLoopEval(); } } case NodeTypes.GLOBALASGNNODE: { GlobalAsgnNode iVisited = (GlobalAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); runtime.getGlobalVariables().set(iVisited.getName(), result); return result; } case NodeTypes.GLOBALVARNODE: { GlobalVarNode iVisited = (GlobalVarNode) node; return runtime.getGlobalVariables().get(iVisited.getName()); } case NodeTypes.HASHNODE: { HashNode iVisited = (HashNode) node; Map hash = null; if (iVisited.getListNode() != null) { hash = new HashMap(iVisited.getListNode().size() / 2); for (Iterator iterator = iVisited.getListNode().iterator(); iterator.hasNext();) { // insert all nodes in sequence, hash them in the final instruction // KEY IRubyObject key = evalInternal(context, (Node) iterator.next(), self); IRubyObject value = evalInternal(context, (Node) iterator.next(), self); hash.put(key, value); } } if (hash == null) { return RubyHash.newHash(runtime); } return RubyHash.newHash(runtime, hash, runtime.getNil()); } case NodeTypes.IFNODE: { IfNode iVisited = (IfNode) node; IRubyObject result = evalInternal(context, iVisited.getCondition(), self); if (result.isTrue()) { node = iVisited.getThenBody(); continue bigloop; } else { node = iVisited.getElseBody(); continue bigloop; } } case NodeTypes.INSTASGNNODE: { InstAsgnNode iVisited = (InstAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); self.setInstanceVariable(iVisited.getName(), result); return result; } case NodeTypes.INSTVARNODE: { InstVarNode iVisited = (InstVarNode) node; IRubyObject variable = self.getInstanceVariable(iVisited.getName()); return variable == null ? runtime.getNil() : variable; } // case NodeTypes.ISCOPINGNODE: // EvaluateVisitor.iScopingNodeVisitor.execute(this, node); // break; case NodeTypes.ITERNODE: { IterNode iVisited = (IterNode) node; // new-style handling of blocks, for nodes that support it // don't process the block until it's needed, to avoid nasty iter tricks if (iVisited.getIterNode() instanceof BlockAcceptingNode) { ((BlockAcceptingNode)iVisited.getIterNode()).setIterNode(iVisited); node = iVisited.getIterNode(); continue bigloop; } // otherwise do it the same as the old way context.preIterEval(Block.createBlock(context, iVisited.getVarNode(), new DynamicScope(iVisited.getScope(), context.getCurrentScope()), iVisited.getCallable(), self)); try { while (true) { try { context.setBlockAvailable(); return evalInternal(context, iVisited.getIterNode(), self); } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.RETRY: // allow loop to retry break; default: throw je; } } finally { context.clearBlockAvailable(); } } } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.BREAK: IRubyObject breakValue = (IRubyObject) je.getPrimaryData(); return breakValue == null ? runtime.getNil() : breakValue; default: throw je; } } finally { context.postIterEval(); } } case NodeTypes.LOCALASGNNODE: { LocalAsgnNode iVisited = (LocalAsgnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // System.out.println("LSetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth() + " and set " + result); context.getCurrentScope().setValue(iVisited.getIndex(), result, iVisited.getDepth()); return result; } case NodeTypes.LOCALVARNODE: { LocalVarNode iVisited = (LocalVarNode) node; //System.out.println("DGetting: " + iVisited.getName() + " at index " + iVisited.getIndex() + " and at depth " + iVisited.getDepth()); IRubyObject result = context.getCurrentScope().getValue(iVisited.getIndex(), iVisited.getDepth()); return result == null ? runtime.getNil() : result; } case NodeTypes.MATCH2NODE: { Match2Node iVisited = (Match2Node) node; IRubyObject recv = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = evalInternal(context, iVisited.getValueNode(), self); return ((RubyRegexp) recv).match(value); } case NodeTypes.MATCH3NODE: { Match3Node iVisited = (Match3Node) node; IRubyObject recv = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = evalInternal(context, iVisited.getValueNode(), self); if (value instanceof RubyString) { return ((RubyRegexp) recv).match(value); } else { return value.callMethod(context, "=~", recv); } } case NodeTypes.MATCHNODE: { MatchNode iVisited = (MatchNode) node; return ((RubyRegexp) evalInternal(context, iVisited.getRegexpNode(), self)).match2(); } case NodeTypes.MODULENODE: { ModuleNode iVisited = (ModuleNode) node; Node classNameNode = iVisited.getCPath(); String name = ((INameNode) classNameNode).getName(); RubyModule enclosingModule = getEnclosingModule(context, classNameNode, self); if (enclosingModule == null) { throw runtime.newTypeError("no outer class/module"); } RubyModule module; if (enclosingModule == runtime.getObject()) { module = runtime.getOrCreateModule(name); } else { module = enclosingModule.defineModuleUnder(name); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), module, self); } case NodeTypes.MULTIPLEASGNNODE: { MultipleAsgnNode iVisited = (MultipleAsgnNode) node; return AssignmentVisitor.assign(context, self, iVisited, evalInternal(context, iVisited.getValueNode(), self), false); } case NodeTypes.NEWLINENODE: { NewlineNode iVisited = (NewlineNode) node; // something in here is used to build up ruby stack trace... context.setPosition(iVisited.getPosition()); if (isTrace(runtime)) { callTraceFunction(context, "line", self); } // TODO: do above but not below for additional newline nodes node = iVisited.getNextNode(); continue bigloop; } case NodeTypes.NEXTNODE: { NextNode iVisited = (NextNode) node; context.pollThreadEvents(); IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.NextJump); je.setPrimaryData(result); je.setSecondaryData(iVisited); //state.setCurrentException(je); throw je; } case NodeTypes.NILNODE: return runtime.getNil(); case NodeTypes.NOTNODE: { NotNode iVisited = (NotNode) node; IRubyObject result = evalInternal(context, iVisited.getConditionNode(), self); return result.isTrue() ? runtime.getFalse() : runtime.getTrue(); } case NodeTypes.NTHREFNODE: { NthRefNode iVisited = (NthRefNode) node; return RubyRegexp.nth_match(iVisited.getMatchNumber(), context.getBackref()); } case NodeTypes.OPASGNANDNODE: { BinaryOperatorNode iVisited = (BinaryOperatorNode) node; // add in reverse order IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) return result; node = iVisited.getSecondNode(); continue bigloop; } case NodeTypes.OPASGNNODE: { OpAsgnNode iVisited = (OpAsgnNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject value = receiver.callMethod(context, iVisited.getVariableName()); if (iVisited.getOperatorName() == "||") { if (value.isTrue()) { return value; } value = evalInternal(context, iVisited.getValueNode(), self); } else if (iVisited.getOperatorName() == "&&") { if (!value.isTrue()) { return value; } value = evalInternal(context, iVisited.getValueNode(), self); } else { value = value.callMethod(context, iVisited.getOperatorName(), evalInternal(context, iVisited.getValueNode(), self)); } receiver.callMethod(context, iVisited.getVariableNameAsgn(), value); context.pollThreadEvents(); return value; } case NodeTypes.OPASGNORNODE: { OpAsgnOrNode iVisited = (OpAsgnOrNode) node; String def = getDefinition(context, iVisited.getFirstNode(), self); IRubyObject result = runtime.getNil(); if (def != null) { result = evalInternal(context, iVisited.getFirstNode(), self); } if (!result.isTrue()) { result = evalInternal(context, iVisited.getSecondNode(), self); } return result; } case NodeTypes.OPELEMENTASGNNODE: { OpElementAsgnNode iVisited = (OpElementAsgnNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); IRubyObject[] args = setupArgs(context, iVisited.getArgsNode(), self); IRubyObject firstValue = receiver.callMethod(context, "[]", args); if (iVisited.getOperatorName() == "||") { if (firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(context, iVisited.getValueNode(), self); } else if (iVisited.getOperatorName() == "&&") { if (!firstValue.isTrue()) { return firstValue; } firstValue = evalInternal(context, iVisited.getValueNode(), self); } else { firstValue = firstValue.callMethod(context, iVisited.getOperatorName(), evalInternal(context, iVisited .getValueNode(), self)); } IRubyObject[] expandedArgs = new IRubyObject[args.length + 1]; System.arraycopy(args, 0, expandedArgs, 0, args.length); expandedArgs[expandedArgs.length - 1] = firstValue; return receiver.callMethod(context, "[]=", expandedArgs); } case NodeTypes.OPTNNODE: { OptNNode iVisited = (OptNNode) node; IRubyObject result = runtime.getNil(); while (RubyKernel.gets(runtime.getTopSelf(), IRubyObject.NULL_ARRAY).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(context, iVisited.getBodyNode(), self); break; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: // do nothing, this iteration restarts break; case JumpType.NEXT: // recheck condition break loop; case JumpType.BREAK: // end loop return (IRubyObject) je.getPrimaryData(); default: throw je; } } } } return result; } case NodeTypes.ORNODE: { OrNode iVisited = (OrNode) node; IRubyObject result = evalInternal(context, iVisited.getFirstNode(), self); if (!result.isTrue()) { result = evalInternal(context, iVisited.getSecondNode(), self); } return result; } // case NodeTypes.POSTEXENODE: // EvaluateVisitor.postExeNodeVisitor.execute(this, node); // break; case NodeTypes.REDONODE: { context.pollThreadEvents(); // now used as an interpreter event JumpException je = new JumpException(JumpException.JumpType.RedoJump); je.setSecondaryData(node); throw je; } case NodeTypes.REGEXPNODE: { RegexpNode iVisited = (RegexpNode) node; String lang = null; int opts = iVisited.getOptions(); if((opts & 16) != 0) { // param n lang = "n"; } else if((opts & 48) != 0) { // param s lang = "s"; } else if((opts & 64) != 0) { // param s lang = "u"; } try { return RubyRegexp.newRegexp(runtime, iVisited.getPattern(), lang); } catch(java.util.regex.PatternSyntaxException e) { throw runtime.newSyntaxError(e.getMessage()); } } case NodeTypes.RESCUEBODYNODE: { RescueBodyNode iVisited = (RescueBodyNode) node; node = iVisited.getBodyNode(); continue bigloop; } case NodeTypes.RESCUENODE: { RescueNode iVisited = (RescueNode)node; RescuedBlock : while (true) { IRubyObject globalExceptionState = runtime.getGlobalVariables().get("$!"); boolean anotherExceptionRaised = false; try { // Execute rescue block IRubyObject result = evalInternal(context, iVisited.getBodyNode(), self); // If no exception is thrown execute else block if (iVisited.getElseNode() != null) { if (iVisited.getRescueNode() == null) { runtime.getWarnings().warn(iVisited.getElseNode().getPosition(), "else without rescue is useless"); } result = evalInternal(context, iVisited.getElseNode(), self); } return result; } catch (RaiseException raiseJump) { RubyException raisedException = raiseJump.getException(); // TODO: Rubicon TestKernel dies without this line. A cursory glance implies we // falsely set $! to nil and this sets it back to something valid. This should // get fixed at the same time we address bug #1296484. runtime.getGlobalVariables().set("$!", raisedException); RescueBodyNode rescueNode = iVisited.getRescueNode(); while (rescueNode != null) { Node exceptionNodes = rescueNode.getExceptionNodes(); ListNode exceptionNodesList; if (exceptionNodes instanceof SplatNode) { exceptionNodesList = (ListNode) evalInternal(context, exceptionNodes, self); } else { exceptionNodesList = (ListNode) exceptionNodes; } if (isRescueHandled(context, raisedException, exceptionNodesList, self)) { try { return evalInternal(context, rescueNode, self); } catch (JumpException je) { if (je.getJumpType() == JumpException.JumpType.RetryJump) { // should be handled in the finally block below //state.runtime.getGlobalVariables().set("$!", state.runtime.getNil()); //state.threadContext.setRaisedException(null); continue RescuedBlock; } else { anotherExceptionRaised = true; throw je; } } } rescueNode = rescueNode.getOptRescueNode(); } // no takers; bubble up throw raiseJump; } finally { // clear exception when handled or retried if (!anotherExceptionRaised) runtime.getGlobalVariables().set("$!", globalExceptionState); } } } case NodeTypes.RETRYNODE: { context.pollThreadEvents(); JumpException je = new JumpException(JumpException.JumpType.RetryJump); throw je; } case NodeTypes.RETURNNODE: { ReturnNode iVisited = (ReturnNode) node; IRubyObject result = evalInternal(context, iVisited.getValueNode(), self); JumpException je = new JumpException(JumpException.JumpType.ReturnJump); je.setPrimaryData(iVisited.getTarget()); je.setSecondaryData(result); je.setTertiaryData(iVisited); throw je; } case NodeTypes.ROOTNODE: { RootNode iVisited = (RootNode) node; DynamicScope scope = iVisited.getScope(); // Serialization killed our dynamic scope. We can just create an empty one // since serialization cannot serialize an eval (which is the only thing // which is capable of having a non-empty dynamic scope). if (scope == null) { scope = new DynamicScope(iVisited.getStaticScope(), null); } // Each root node has a top-level scope that we need to push context.preRootNode(scope); // FIXME: Wire up BEGIN and END nodes try { return eval(context, iVisited.getBodyNode(), self); } finally { context.postRootNode(); } } case NodeTypes.SCLASSNODE: { SClassNode iVisited = (SClassNode) node; IRubyObject receiver = evalInternal(context, iVisited.getReceiverNode(), self); RubyClass singletonClass; if (receiver.isNil()) { singletonClass = runtime.getNilClass(); } else if (receiver == runtime.getTrue()) { singletonClass = runtime.getClass("TrueClass"); } else if (receiver == runtime.getFalse()) { singletonClass = runtime.getClass("FalseClass"); } else if (receiver.getMetaClass() == runtime.getFixnum() || receiver.getMetaClass() == runtime.getClass("Symbol")) { throw runtime.newTypeError("no virtual class for " + receiver.getMetaClass().getBaseName()); } else { if (runtime.getSafeLevel() >= 4 && !receiver.isTaint()) { throw runtime.newSecurityError("Insecure: can't extend object."); } singletonClass = receiver.getSingletonClass(); } if (context.getWrapper() != null) { singletonClass.extendObject(context.getWrapper()); singletonClass.includeModule(context.getWrapper()); } return evalClassDefinitionBody(context, iVisited.getScope(), iVisited.getBodyNode(), singletonClass, self); } case NodeTypes.SELFNODE: return self; case NodeTypes.SPLATNODE: { SplatNode iVisited = (SplatNode) node; return splatValue(evalInternal(context, iVisited.getValue(), self)); } //// case NodeTypes.STARNODE: //// EvaluateVisitor.starNodeVisitor.execute(this, node); //// break; case NodeTypes.STRNODE: { StrNode iVisited = (StrNode) node; return runtime.newString(iVisited.getValue()); } case NodeTypes.SUPERNODE: { SuperNode iVisited = (SuperNode) node; if (context.getFrameLastClass() == null) { String name = context.getFrameLastFunc(); throw runtime.newNameError("Superclass method '" + name + "' disabled.", name); } context.beginCallArgs(); IRubyObject[] args = null; try { args = setupArgs(context, iVisited.getArgsNode(), self); } finally { context.endCallArgs(); } return context.callSuper(args); } case NodeTypes.SVALUENODE: { SValueNode iVisited = (SValueNode) node; return aValueSplat(evalInternal(context, iVisited.getValue(), self)); } case NodeTypes.SYMBOLNODE: { SymbolNode iVisited = (SymbolNode) node; return runtime.newSymbol(iVisited.getName()); } case NodeTypes.TOARYNODE: { ToAryNode iVisited = (ToAryNode) node; return aryToAry(evalInternal(context, iVisited.getValue(), self)); } case NodeTypes.TRUENODE: { context.pollThreadEvents(); return runtime.getTrue(); } case NodeTypes.UNDEFNODE: { UndefNode iVisited = (UndefNode) node; if (context.getRubyClass() == null) { throw runtime .newTypeError("No class to undef method '" + iVisited.getName() + "'."); } context.getRubyClass().undef(iVisited.getName()); return runtime.getNil(); } case NodeTypes.UNTILNODE: { UntilNode iVisited = (UntilNode) node; IRubyObject result = runtime.getNil(); while (!(result = evalInternal(context, iVisited.getConditionNode(), self)).isTrue()) { loop: while (true) { // Used for the 'redo' command try { result = evalInternal(context, iVisited.getBodyNode(), self); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: return (IRubyObject) je.getPrimaryData(); default: throw je; } } } } return result; } case NodeTypes.VALIASNODE: { VAliasNode iVisited = (VAliasNode) node; runtime.getGlobalVariables().alias(iVisited.getNewName(), iVisited.getOldName()); return runtime.getNil(); } case NodeTypes.VCALLNODE: { VCallNode iVisited = (VCallNode) node; return self.callMethod(context, iVisited.getName(), IRubyObject.NULL_ARRAY, CallType.VARIABLE); } case NodeTypes.WHENNODE: assert false; return null; case NodeTypes.WHILENODE: { WhileNode iVisited = (WhileNode) node; IRubyObject result = runtime.getNil(); boolean firstTest = iVisited.evaluateAtStart(); while (!firstTest || (result = evalInternal(context, iVisited.getConditionNode(), self)).isTrue()) { firstTest = true; loop: while (true) { // Used for the 'redo' command try { evalInternal(context, iVisited.getBodyNode(), self); break loop; } catch (JumpException je) { switch (je.getJumpType().getTypeId()) { case JumpType.REDO: continue; case JumpType.NEXT: break loop; case JumpType.BREAK: return result; default: throw je; } } } } return result; } case NodeTypes.XSTRNODE: { XStrNode iVisited = (XStrNode) node; return self.callMethod(context, "`", runtime.newString(iVisited.getValue())); } case NodeTypes.YIELDNODE: { YieldNode iVisited = (YieldNode) node; IRubyObject result = evalInternal(context, iVisited.getArgsNode(), self); if (iVisited.getArgsNode() == null) { result = null; } return context.yieldCurrentBlock(result, null, null, iVisited.getCheckState()); } case NodeTypes.ZARRAYNODE: { return runtime.newArray(); } case NodeTypes.ZSUPERNODE: { if (context.getFrameLastClass() == null) { String name = context.getFrameLastFunc(); throw runtime.newNameError("superclass method '" + name + "' disabled", name); } return context.callSuper(context.getFrameArgs(), true); } } } while (true); }
diff --git a/oozie/src/main/java/org/apache/ivory/workflow/engine/OozieHouseKeepingService.java b/oozie/src/main/java/org/apache/ivory/workflow/engine/OozieHouseKeepingService.java index 748a1f6d..5db190fb 100644 --- a/oozie/src/main/java/org/apache/ivory/workflow/engine/OozieHouseKeepingService.java +++ b/oozie/src/main/java/org/apache/ivory/workflow/engine/OozieHouseKeepingService.java @@ -1,77 +1,77 @@ /* * 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.ivory.workflow.engine; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.ivory.IvoryException; import org.apache.ivory.entity.ClusterHelper; import org.apache.ivory.entity.v0.Entity; import org.apache.ivory.entity.v0.cluster.Cluster; import org.apache.log4j.Logger; import java.io.IOException; public class OozieHouseKeepingService implements WorkflowEngineActionListener { private static Logger LOG = Logger.getLogger(OozieHouseKeepingService.class); @Override public void beforeSchedule(Cluster cluster, Entity entity) throws IvoryException { } @Override public void afterSchedule(Cluster cluster, Entity entity) throws IvoryException { } @Override public void beforeDelete(Cluster cluster, Entity entity) throws IvoryException { } @Override public void afterDelete(Cluster cluster, Entity entity) throws IvoryException { Path workflowFolder = new Path(ClusterHelper.getCompleteLocation(cluster, "staging"), entity.getStagingPath()).getParent(); try { FileSystem fs = workflowFolder.getFileSystem(new Configuration()); LOG.info("Deleting workflow " + workflowFolder); - if (!fs.delete(workflowFolder, true)) { + if (fs.exists(workflowFolder) && !fs.delete(workflowFolder, true)) { throw new IvoryException("Unable to cleanup workflow xml; " + "delete failed " + workflowFolder); } } catch (IOException e) { throw new IvoryException("Unable to cleanup workflow xml", e); } } @Override public void beforeSuspend(Cluster cluster, Entity entity) throws IvoryException { } @Override public void afterSuspend(Cluster cluster, Entity entity) throws IvoryException { } @Override public void beforeResume(Cluster cluster, Entity entity) throws IvoryException { } @Override public void afterResume(Cluster cluster, Entity entity) throws IvoryException { } }
true
true
public void afterDelete(Cluster cluster, Entity entity) throws IvoryException { Path workflowFolder = new Path(ClusterHelper.getCompleteLocation(cluster, "staging"), entity.getStagingPath()).getParent(); try { FileSystem fs = workflowFolder.getFileSystem(new Configuration()); LOG.info("Deleting workflow " + workflowFolder); if (!fs.delete(workflowFolder, true)) { throw new IvoryException("Unable to cleanup workflow xml; " + "delete failed " + workflowFolder); } } catch (IOException e) { throw new IvoryException("Unable to cleanup workflow xml", e); } }
public void afterDelete(Cluster cluster, Entity entity) throws IvoryException { Path workflowFolder = new Path(ClusterHelper.getCompleteLocation(cluster, "staging"), entity.getStagingPath()).getParent(); try { FileSystem fs = workflowFolder.getFileSystem(new Configuration()); LOG.info("Deleting workflow " + workflowFolder); if (fs.exists(workflowFolder) && !fs.delete(workflowFolder, true)) { throw new IvoryException("Unable to cleanup workflow xml; " + "delete failed " + workflowFolder); } } catch (IOException e) { throw new IvoryException("Unable to cleanup workflow xml", e); } }
diff --git a/pmd-netbeans/src/pmd/config/ui/PmdOptionsComponent.java b/pmd-netbeans/src/pmd/config/ui/PmdOptionsComponent.java index a35971a65..592f1a979 100644 --- a/pmd-netbeans/src/pmd/config/ui/PmdOptionsComponent.java +++ b/pmd-netbeans/src/pmd/config/ui/PmdOptionsComponent.java @@ -1,263 +1,264 @@ /* * Copyright (c) 2002-2006, the pmd-netbeans team * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package pmd.config.ui; import java.awt.Component; import java.awt.Dialog; import java.util.Properties; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.util.NbBundle; import pmd.config.CustomRuleSetSettings; /** * * @author radim */ public class PmdOptionsComponent extends javax.swing.JPanel { PmdOptionsController controller; private RulesConfig rules; private CustomRuleSetSettings rulesets; /** Creates new form PmdOptionsComponent */ public PmdOptionsComponent(PmdOptionsController c) { controller = c; initComponents(); } void setEnableScan (boolean es) { jCheckBox1.setSelected(es); jTextField1.setEnabled(es); } boolean isEnableScan () { return jCheckBox1.isSelected(); } void setScanInterval (int i) { jTextField1.setText(Integer.toString(i)); } int getScanInterval () { return Integer.parseInt(jTextField1.getText()); } void setRules(RulesConfig rules) { this.rules = rules; } RulesConfig getRules () { return rules; } void setRulesets(CustomRuleSetSettings customRuleSetSettings) { rulesets = customRuleSetSettings; } CustomRuleSetSettings getRulesets () { return rulesets; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jCheckBox1 = new javax.swing.JCheckBox(); jTextField1 = new javax.swing.JTextField(); jPanelRules = new javax.swing.JPanel(); jLblRules = new javax.swing.JLabel(); jBtnRules = new javax.swing.JButton(); jPanelRulesets = new javax.swing.JPanel(); jLblRulesets = new javax.swing.JLabel(); jBtnRulesets = new javax.swing.JButton(); - jLabel1.setText("Scan interval:"); + jLabel1.setLabelFor(jTextField1); + org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_ScanInterval")); - jCheckBox1.setText("Enable scan"); + org.openide.awt.Mnemonics.setLocalizedText(jCheckBox1, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_EnableScan")); jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0)); jCheckBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBox1ActionPerformed(evt); } }); jTextField1.setColumns(3); jTextField1.setText("0"); jPanelRules.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesPanel"))); - jLblRules.setText(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesText")); + org.openide.awt.Mnemonics.setLocalizedText(jLblRules, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesText")); - jBtnRules.setText(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesBtn")); + org.openide.awt.Mnemonics.setLocalizedText(jBtnRules, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesBtn")); jBtnRules.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnRulesActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelRulesLayout = new org.jdesktop.layout.GroupLayout(jPanelRules); jPanelRules.setLayout(jPanelRulesLayout); jPanelRulesLayout.setHorizontalGroup( jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelRulesLayout.createSequentialGroup() .addContainerGap() .add(jLblRules) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 59, Short.MAX_VALUE) .add(jBtnRules) .addContainerGap()) ); jPanelRulesLayout.setVerticalGroup( jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelRulesLayout.createSequentialGroup() .add(jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jBtnRules) .add(jLblRules)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelRulesets.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetsPanel"))); - jLblRulesets.setText("<html>Use this button to specify additional rulesets<br>and customize their properties."); + org.openide.awt.Mnemonics.setLocalizedText(jLblRulesets, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetsText")); - jBtnRulesets.setText(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetBtn")); + org.openide.awt.Mnemonics.setLocalizedText(jBtnRulesets, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetBtn")); jBtnRulesets.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnRulesetsActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelRulesetsLayout = new org.jdesktop.layout.GroupLayout(jPanelRulesets); jPanelRulesets.setLayout(jPanelRulesetsLayout); jPanelRulesetsLayout.setHorizontalGroup( jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelRulesetsLayout.createSequentialGroup() .addContainerGap() .add(jLblRulesets) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jBtnRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 146, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanelRulesetsLayout.setVerticalGroup( jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelRulesetsLayout.createSequentialGroup() .add(jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jBtnRulesets) .add(jLblRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jCheckBox1) .add(layout.createSequentialGroup() .addContainerGap() .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap(332, Short.MAX_VALUE)) .add(jPanelRules, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanelRulesets, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jCheckBox1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelRules, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(8, 8, 8) .add(jPanelRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) - .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap(16, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void jBtnRulesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnRulesActionPerformed RuleEditor editor = new RuleEditor(); editor.setValue (rules); Component customEditor = editor.getCustomEditor (); DialogDescriptor dd = new DialogDescriptor ( customEditor, NbBundle.getMessage(PmdOptionsComponent.class, "Rules_Editor_Title") ); Dialog dialog = DialogDisplayer.getDefault ().createDialog (dd); dialog.setVisible (true); if (dd.getValue () == NotifyDescriptor.OK_OPTION) { rules = (RulesConfig) editor.getValue (); controller.dataChanged(); } }//GEN-LAST:event_jBtnRulesActionPerformed private void jBtnRulesetsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnRulesetsActionPerformed RuleSetChooserEditor editor = new RuleSetChooserEditor(); editor.setValue (rulesets); Component customEditor = editor.getCustomEditor (); DialogDescriptor dd = new DialogDescriptor ( customEditor, NbBundle.getMessage(PmdOptionsComponent.class, "Rulesets_Editor_Title") ); Dialog dialog = DialogDisplayer.getDefault ().createDialog (dd); dialog.setVisible (true); if (dd.getValue () == NotifyDescriptor.OK_OPTION) { rulesets = (CustomRuleSetSettings) editor.getValue (); controller.dataChanged(); } }//GEN-LAST:event_jBtnRulesetsActionPerformed private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed jTextField1.setEnabled(jCheckBox1.isSelected()); controller.dataChanged(); }//GEN-LAST:event_jCheckBox1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jBtnRules; private javax.swing.JButton jBtnRulesets; private javax.swing.JCheckBox jCheckBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLblRules; private javax.swing.JLabel jLblRulesets; private javax.swing.JPanel jPanelRules; private javax.swing.JPanel jPanelRulesets; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { jLabel1 = new javax.swing.JLabel(); jCheckBox1 = new javax.swing.JCheckBox(); jTextField1 = new javax.swing.JTextField(); jPanelRules = new javax.swing.JPanel(); jLblRules = new javax.swing.JLabel(); jBtnRules = new javax.swing.JButton(); jPanelRulesets = new javax.swing.JPanel(); jLblRulesets = new javax.swing.JLabel(); jBtnRulesets = new javax.swing.JButton(); jLabel1.setText("Scan interval:"); jCheckBox1.setText("Enable scan"); jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0)); jCheckBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBox1ActionPerformed(evt); } }); jTextField1.setColumns(3); jTextField1.setText("0"); jPanelRules.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesPanel"))); jLblRules.setText(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesText")); jBtnRules.setText(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesBtn")); jBtnRules.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnRulesActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelRulesLayout = new org.jdesktop.layout.GroupLayout(jPanelRules); jPanelRules.setLayout(jPanelRulesLayout); jPanelRulesLayout.setHorizontalGroup( jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelRulesLayout.createSequentialGroup() .addContainerGap() .add(jLblRules) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 59, Short.MAX_VALUE) .add(jBtnRules) .addContainerGap()) ); jPanelRulesLayout.setVerticalGroup( jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelRulesLayout.createSequentialGroup() .add(jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jBtnRules) .add(jLblRules)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelRulesets.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetsPanel"))); jLblRulesets.setText("<html>Use this button to specify additional rulesets<br>and customize their properties."); jBtnRulesets.setText(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetBtn")); jBtnRulesets.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnRulesetsActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelRulesetsLayout = new org.jdesktop.layout.GroupLayout(jPanelRulesets); jPanelRulesets.setLayout(jPanelRulesetsLayout); jPanelRulesetsLayout.setHorizontalGroup( jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelRulesetsLayout.createSequentialGroup() .addContainerGap() .add(jLblRulesets) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jBtnRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 146, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanelRulesetsLayout.setVerticalGroup( jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelRulesetsLayout.createSequentialGroup() .add(jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jBtnRulesets) .add(jLblRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jCheckBox1) .add(layout.createSequentialGroup() .addContainerGap() .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap(332, Short.MAX_VALUE)) .add(jPanelRules, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanelRulesets, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jCheckBox1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelRules, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(8, 8, 8) .add(jPanelRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jLabel1 = new javax.swing.JLabel(); jCheckBox1 = new javax.swing.JCheckBox(); jTextField1 = new javax.swing.JTextField(); jPanelRules = new javax.swing.JPanel(); jLblRules = new javax.swing.JLabel(); jBtnRules = new javax.swing.JButton(); jPanelRulesets = new javax.swing.JPanel(); jLblRulesets = new javax.swing.JLabel(); jBtnRulesets = new javax.swing.JButton(); jLabel1.setLabelFor(jTextField1); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_ScanInterval")); org.openide.awt.Mnemonics.setLocalizedText(jCheckBox1, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_EnableScan")); jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0)); jCheckBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCheckBox1ActionPerformed(evt); } }); jTextField1.setColumns(3); jTextField1.setText("0"); jPanelRules.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesPanel"))); org.openide.awt.Mnemonics.setLocalizedText(jLblRules, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesText")); org.openide.awt.Mnemonics.setLocalizedText(jBtnRules, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesBtn")); jBtnRules.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnRulesActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelRulesLayout = new org.jdesktop.layout.GroupLayout(jPanelRules); jPanelRules.setLayout(jPanelRulesLayout); jPanelRulesLayout.setHorizontalGroup( jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelRulesLayout.createSequentialGroup() .addContainerGap() .add(jLblRules) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 59, Short.MAX_VALUE) .add(jBtnRules) .addContainerGap()) ); jPanelRulesLayout.setVerticalGroup( jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelRulesLayout.createSequentialGroup() .add(jPanelRulesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jBtnRules) .add(jLblRules)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanelRulesets.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetsPanel"))); org.openide.awt.Mnemonics.setLocalizedText(jLblRulesets, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetsText")); org.openide.awt.Mnemonics.setLocalizedText(jBtnRulesets, org.openide.util.NbBundle.getMessage(PmdOptionsComponent.class, "LBL_RulesetBtn")); jBtnRulesets.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jBtnRulesetsActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelRulesetsLayout = new org.jdesktop.layout.GroupLayout(jPanelRulesets); jPanelRulesets.setLayout(jPanelRulesetsLayout); jPanelRulesetsLayout.setHorizontalGroup( jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelRulesetsLayout.createSequentialGroup() .addContainerGap() .add(jLblRulesets) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jBtnRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 146, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanelRulesetsLayout.setVerticalGroup( jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelRulesetsLayout.createSequentialGroup() .add(jPanelRulesetsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jBtnRulesets) .add(jLblRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 42, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jCheckBox1) .add(layout.createSequentialGroup() .addContainerGap() .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addContainerGap(332, Short.MAX_VALUE)) .add(jPanelRules, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(jPanelRulesets, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jCheckBox1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel1) .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelRules, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(8, 8, 8) .add(jPanelRulesets, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(16, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RecoverTask.java b/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RecoverTask.java index f55cac0..65126b7 100644 --- a/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RecoverTask.java +++ b/geronimo-transaction/src/main/java/org/apache/geronimo/transaction/manager/RecoverTask.java @@ -1,63 +1,65 @@ /* * 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.geronimo.transaction.manager; import java.util.TimerTask; import javax.transaction.SystemException; import javax.transaction.xa.XAException; /** * @version $Rev$ $Date$ */ public class RecoverTask implements Runnable { private final RetryScheduler retryScheduler; private final NamedXAResourceFactory namedXAResourceFactory; private final Recovery recovery; private final RecoverableTransactionManager recoverableTransactionManager; private int count = 0; public RecoverTask(RetryScheduler retryScheduler, NamedXAResourceFactory namedXAResourceFactory, Recovery recovery, RecoverableTransactionManager recoverableTransactionManager) { this.retryScheduler = retryScheduler; this.namedXAResourceFactory = namedXAResourceFactory; this.recovery = recovery; this.recoverableTransactionManager = recoverableTransactionManager; } // @Override public void run() { try { NamedXAResource namedXAResource = namedXAResourceFactory.getNamedXAResource(); - try { - recovery.recoverResourceManager(namedXAResource); - } finally { - namedXAResourceFactory.returnNamedXAResource(namedXAResource); + if (namedXAResource != null) { + try { + recovery.recoverResourceManager(namedXAResource); + } finally { + namedXAResourceFactory.returnNamedXAResource(namedXAResource); + } } return; } catch (XAException e) { recoverableTransactionManager.recoveryError(e); } catch (SystemException e) { recoverableTransactionManager.recoveryError(e); } retryScheduler.retry(this, count++); } }
true
true
public void run() { try { NamedXAResource namedXAResource = namedXAResourceFactory.getNamedXAResource(); try { recovery.recoverResourceManager(namedXAResource); } finally { namedXAResourceFactory.returnNamedXAResource(namedXAResource); } return; } catch (XAException e) { recoverableTransactionManager.recoveryError(e); } catch (SystemException e) { recoverableTransactionManager.recoveryError(e); } retryScheduler.retry(this, count++); }
public void run() { try { NamedXAResource namedXAResource = namedXAResourceFactory.getNamedXAResource(); if (namedXAResource != null) { try { recovery.recoverResourceManager(namedXAResource); } finally { namedXAResourceFactory.returnNamedXAResource(namedXAResource); } } return; } catch (XAException e) { recoverableTransactionManager.recoveryError(e); } catch (SystemException e) { recoverableTransactionManager.recoveryError(e); } retryScheduler.retry(this, count++); }
diff --git a/java/gadgets/src/test/java/org/apache/shindig/gadgets/rewrite/CachingContentRewriterRegistryTest.java b/java/gadgets/src/test/java/org/apache/shindig/gadgets/rewrite/CachingContentRewriterRegistryTest.java index 35bf450e5..e8ae39f59 100644 --- a/java/gadgets/src/test/java/org/apache/shindig/gadgets/rewrite/CachingContentRewriterRegistryTest.java +++ b/java/gadgets/src/test/java/org/apache/shindig/gadgets/rewrite/CachingContentRewriterRegistryTest.java @@ -1,243 +1,243 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.apache.shindig.gadgets.rewrite; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.apache.shindig.common.ContainerConfig; import org.apache.shindig.common.cache.Cache; import org.apache.shindig.common.cache.CacheProvider; import org.apache.shindig.common.uri.Uri; import org.apache.shindig.gadgets.Gadget; import org.apache.shindig.gadgets.GadgetContext; import org.apache.shindig.gadgets.JsLibrary; import org.apache.shindig.gadgets.MutableContent; import org.apache.shindig.gadgets.http.HttpRequest; import org.apache.shindig.gadgets.http.HttpResponse; import org.apache.shindig.gadgets.spec.GadgetSpec; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.easymock.classextension.EasyMock; import org.easymock.classextension.IMocksControl; import org.junit.Test; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; public class CachingContentRewriterRegistryTest { private final List<CaptureRewriter> rewriters = Lists.newArrayList(new CaptureRewriter(), new ModifyingCaptureContentRewriter()); private final List<ContentRewriter> contentRewriters = Lists.<ContentRewriter>newArrayList(rewriters); private final FakeCacheProvider provider = new FakeCacheProvider(); private final ContentRewriterRegistry registry = new CachingContentRewriterRegistry(contentRewriters, null, provider, 100); private final IMocksControl control = EasyMock.createNiceControl(); private final ContainerConfig config = control.createMock(ContainerConfig.class); @Test public void gadgetGetsCached() throws Exception { String body = "Hello, world"; String xml = "<Module><ModulePrefs title=''/><Content>" + body + "</Content></Module>"; GadgetSpec spec = new GadgetSpec(URI.create("#"), xml); GadgetContext context = new GadgetContext(); Gadget gadget = new Gadget(context, spec, new ArrayList<JsLibrary>(), config, null); control.replay(); registry.rewriteGadget(gadget); // TODO: We're not actually testing the TTL of the entries here. assertEquals(1, provider.readCount); assertEquals(1, provider.writeCount); } @Test public void gadgetFetchedFromCache() throws Exception { String body = "Hello, world"; String xml = "<Module><ModulePrefs title=''/><Content>" + body + "</Content></Module>"; GadgetSpec spec = new GadgetSpec(URI.create("#"), xml); GadgetContext context = new GadgetContext(); control.replay(); // We have to re-create Gadget objects because they get mutated directly, which is really // inconsistent with the behavior of rewriteHttpResponse. Gadget gadget = new Gadget(context, spec, new ArrayList<JsLibrary>(), config, null); registry.rewriteGadget(gadget); gadget = new Gadget(context, spec, new ArrayList<JsLibrary>(), config, null); registry.rewriteGadget(gadget); gadget = new Gadget(context, spec, new ArrayList<JsLibrary>(), config, null); registry.rewriteGadget(gadget); // TODO: We're not actually testing the TTL of the entries here. assertEquals(3, provider.readCount); assertEquals(1, provider.writeCount); } @Test public void noCacheGadgetDoesNotGetCached() throws Exception { String body = "Hello, world"; String xml = "<Module><ModulePrefs title=''/><Content>" + body + "</Content></Module>"; GadgetSpec spec = new GadgetSpec(URI.create("#"), xml); GadgetContext context = new GadgetContext() { @Override public boolean getIgnoreCache() { return true; } }; Gadget gadget = new Gadget(context, spec, new ArrayList<JsLibrary>(), config, null); control.replay(); registry.rewriteGadget(gadget); assertTrue("Rewriting not performed on uncacheable content.", rewriters.get(0).viewWasRewritten()); assertEquals(0, provider.readCount); assertEquals(0, provider.writeCount); } @Test public void httpResponseGetsCached() throws Exception { String body = "Hello, world"; HttpRequest request = new HttpRequest(Uri.parse("#")); HttpResponse response = new HttpResponse(body); registry.rewriteHttpResponse(request, response); assertEquals(1, provider.readCount); assertEquals(1, provider.writeCount); } @Test public void httpResponseFetchedFromCache() throws Exception { String body = "Hello, world"; HttpRequest request = new HttpRequest(Uri.parse("#")); HttpResponse response = new HttpResponse(body); registry.rewriteHttpResponse(request, response); registry.rewriteHttpResponse(request, response); registry.rewriteHttpResponse(request, response); assertEquals(3, provider.readCount); assertEquals(1, provider.writeCount); } @Test public void noCacheHttpResponseDoesNotGetCached() throws Exception { String body = "Hello, world"; HttpRequest request = new HttpRequest(Uri.parse("#")).setIgnoreCache(true); HttpResponse response = new HttpResponse(body); registry.rewriteHttpResponse(request, response); assertTrue("Rewriting not performed on uncacheable content.", rewriters.get(0).responseWasRewritten()); assertEquals(0, provider.readCount); assertEquals(0, provider.writeCount); } @Test public void changingRewritersBustsCache() { // What we're testing here is actually impossible (you can't swap the registry on a running // application), but there's a good chance that implementations will be using a shared cache, // which persists across server restarts / reconfigurations. This verifies that the entries in // the cache will be invalidated if the rewriters change. // Just HTTP here; we'll assume this code is common between both methods. String body = "Hello, world"; HttpRequest request = new HttpRequest(Uri.parse("#")); HttpResponse response = new HttpResponse(body); registry.rewriteHttpResponse(request, response); assertEquals(1, provider.readCount); assertEquals(1, provider.writeCount); // The new registry is created using one additional rewriter, but the same cache. - rewriters.add(new CaptureRewriter()); + contentRewriters.add(new CaptureRewriter()); ContentRewriterRegistry newRegistry = new CachingContentRewriterRegistry(contentRewriters, null, provider, 100); newRegistry.rewriteHttpResponse(request, response); assertEquals(2, provider.readCount); assertEquals(2, provider.writeCount); assertFalse("Cache was written using identical keys.", provider.keys.get(0).equals(provider.keys.get(1))); } private static class FakeCacheProvider implements CacheProvider { private final Map<String, Object> entries = Maps.newHashMap(); private final List<String> keys = Lists.newLinkedList(); private int readCount = 0; private int writeCount = 0; private final Cache<String, Object> cache = new Cache<String, Object>() { public void addElement(String key, Object value) { entries.put(key, value); keys.add(key); writeCount++; } public Object getElement(String key) { readCount++; return entries.get(key); } public Object removeElement(String key) { return entries.remove(key); } }; public <K, V> Cache<K, V> createCache(int capacity, String name) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") public <K, V> Cache<K, V> createCache(int capacity) { return (Cache<K, V>)cache; } } private static class ModifyingCaptureContentRewriter extends CaptureRewriter { @Override public RewriterResults rewrite(HttpRequest request, HttpResponse original, MutableContent content) { super.rewrite(request, original, content); content.setContent(content.getContent() + "-modified"); return RewriterResults.cacheableIndefinitely(); } @Override public RewriterResults rewrite(Gadget gadget) { super.rewrite(gadget); gadget.setContent(gadget.getContent() + "-modified"); return RewriterResults.cacheableIndefinitely(); } } }
true
true
public void changingRewritersBustsCache() { // What we're testing here is actually impossible (you can't swap the registry on a running // application), but there's a good chance that implementations will be using a shared cache, // which persists across server restarts / reconfigurations. This verifies that the entries in // the cache will be invalidated if the rewriters change. // Just HTTP here; we'll assume this code is common between both methods. String body = "Hello, world"; HttpRequest request = new HttpRequest(Uri.parse("#")); HttpResponse response = new HttpResponse(body); registry.rewriteHttpResponse(request, response); assertEquals(1, provider.readCount); assertEquals(1, provider.writeCount); // The new registry is created using one additional rewriter, but the same cache. rewriters.add(new CaptureRewriter()); ContentRewriterRegistry newRegistry = new CachingContentRewriterRegistry(contentRewriters, null, provider, 100); newRegistry.rewriteHttpResponse(request, response); assertEquals(2, provider.readCount); assertEquals(2, provider.writeCount); assertFalse("Cache was written using identical keys.", provider.keys.get(0).equals(provider.keys.get(1))); }
public void changingRewritersBustsCache() { // What we're testing here is actually impossible (you can't swap the registry on a running // application), but there's a good chance that implementations will be using a shared cache, // which persists across server restarts / reconfigurations. This verifies that the entries in // the cache will be invalidated if the rewriters change. // Just HTTP here; we'll assume this code is common between both methods. String body = "Hello, world"; HttpRequest request = new HttpRequest(Uri.parse("#")); HttpResponse response = new HttpResponse(body); registry.rewriteHttpResponse(request, response); assertEquals(1, provider.readCount); assertEquals(1, provider.writeCount); // The new registry is created using one additional rewriter, but the same cache. contentRewriters.add(new CaptureRewriter()); ContentRewriterRegistry newRegistry = new CachingContentRewriterRegistry(contentRewriters, null, provider, 100); newRegistry.rewriteHttpResponse(request, response); assertEquals(2, provider.readCount); assertEquals(2, provider.writeCount); assertFalse("Cache was written using identical keys.", provider.keys.get(0).equals(provider.keys.get(1))); }
diff --git a/src/Scaled.java b/src/Scaled.java index b7b6b3f..788f4b1 100644 --- a/src/Scaled.java +++ b/src/Scaled.java @@ -1,88 +1,90 @@ /** * as this class uses the scale-method which all classes that implement Pict * have definied, the generic type of the class must extend Pict * * Scaled extends Repeated as it has the addtional requirement that it's type * must have a .scale()-method and the global scale is always 1.0 * * * ASSERTIONS (Zusicherungen): * - same as repeated * - type-parameter must implement pict * * @author OOP Gruppe 187 * */ public class Scaled<P extends Pict> extends Repeated<P> { /** * constructor which takes an array of pictograms; only used to make * debugging easier * * @param data * array with all the values */ public Scaled(P data[][]) { super(data); } /** * scales the size of each box by calling their scale-method * * @param factor */ public void scale(double factor) { assert (0.1 <= factor && factor <= 10.0) : "invalid factor"; if (factor < 0.1 || factor > 10.0) { throw new IllegalArgumentException("illegal factor"); } Object[][] data = getData(); // scale objects for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[0].length; j++) { ((Pict) data[i][j]).scale(factor); } } } /** * returns a string-list of all boxes * * @return string-representation */ public String toString() { StringBuilder ret = new StringBuilder(); Object[][] data = getData(); int maxWidth = PictHelper.getMaxWidth(data); int maxHeight = PictHelper.getMaxHeight(data); String currentLine; int currentWidth; for (int i = 0; i < data.length; i++) { for (int k = 0; k < maxHeight; k++) { for (int j = 0; j < data[0].length; j++) { currentLine = PictHelper.getLine(data[i][j].toString(), k); currentWidth = PictHelper.getWidth(currentLine); ret.append(currentLine); for (int l = currentWidth; l < maxWidth - 1; l++) { ret.append(" "); } } - if(k != maxHeight - 1) { + if(k == maxHeight - 1 && i == data.length - 1) { + // skip last \n + } else { ret.append("\n"); } } } return ret.toString(); } }
true
true
public String toString() { StringBuilder ret = new StringBuilder(); Object[][] data = getData(); int maxWidth = PictHelper.getMaxWidth(data); int maxHeight = PictHelper.getMaxHeight(data); String currentLine; int currentWidth; for (int i = 0; i < data.length; i++) { for (int k = 0; k < maxHeight; k++) { for (int j = 0; j < data[0].length; j++) { currentLine = PictHelper.getLine(data[i][j].toString(), k); currentWidth = PictHelper.getWidth(currentLine); ret.append(currentLine); for (int l = currentWidth; l < maxWidth - 1; l++) { ret.append(" "); } } if(k != maxHeight - 1) { ret.append("\n"); } } } return ret.toString(); }
public String toString() { StringBuilder ret = new StringBuilder(); Object[][] data = getData(); int maxWidth = PictHelper.getMaxWidth(data); int maxHeight = PictHelper.getMaxHeight(data); String currentLine; int currentWidth; for (int i = 0; i < data.length; i++) { for (int k = 0; k < maxHeight; k++) { for (int j = 0; j < data[0].length; j++) { currentLine = PictHelper.getLine(data[i][j].toString(), k); currentWidth = PictHelper.getWidth(currentLine); ret.append(currentLine); for (int l = currentWidth; l < maxWidth - 1; l++) { ret.append(" "); } } if(k == maxHeight - 1 && i == data.length - 1) { // skip last \n } else { ret.append("\n"); } } } return ret.toString(); }
diff --git a/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java b/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java index 36a668b5..d714aa5b 100644 --- a/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java +++ b/src/com/jidesoft/plaf/basic/BasicJideTabbedPaneUI.java @@ -1,8675 +1,8675 @@ /* @(#)BasicJideTabbedPaneUI.java * * Copyright 2002 JIDE Software Inc. All rights reserved. */ package com.jidesoft.plaf.basic; import com.jidesoft.plaf.JideTabbedPaneUI; import com.jidesoft.plaf.UIDefaultsLookup; import com.jidesoft.popup.JidePopup; import com.jidesoft.swing.JideSwingUtilities; import com.jidesoft.swing.JideTabbedPane; import com.jidesoft.swing.Sticky; import com.jidesoft.utils.PortingUtils; import com.jidesoft.utils.SecurityUtils; import com.jidesoft.utils.SystemInfo; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.plaf.*; import javax.swing.plaf.basic.BasicGraphicsUtils; import javax.swing.plaf.basic.BasicHTML; import javax.swing.text.View; import java.awt.*; import java.awt.dnd.*; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Hashtable; import java.util.Locale; import java.util.Vector; /** * A basic L&f implementation of JideTabbedPaneUI */ public class BasicJideTabbedPaneUI extends JideTabbedPaneUI implements SwingConstants, DocumentListener { // pixels protected int _tabRectPadding;// distance from tab rect to icon/text protected int _closeButtonMarginHorizon; // when tab is on top or bottom, and each tab has close button, the gap around the close button protected int _closeButtonMarginVertical;// when tab is on left or right, and each tab has close button, the gap around the close button protected int _textMarginVertical;// tab area and text area gap protected int _noIconMargin;// gap around text area when there is no icon protected int _iconMargin;// distance from icon to tab rect start x protected int _textPadding;// distance from text to tab rect start protected int _buttonSize;// scroll button size protected int _buttonMargin;// scroll button margin protected int _fitStyleBoundSize;// margin for the whole tab area protected int _fitStyleFirstTabMargin;// the first tab position protected int _fitStyleIconMinWidth;// minimum width to display icon protected int _fitStyleTextMinWidth;// minimum width to display text protected int _compressedStyleNoIconRectSize;// tab size when there is no icon and tab not selected protected int _compressedStyleIconMargin;// margin around icon protected int _compressedStyleCloseButtonMarginHorizon;// the close button margin on the left or right when the tab is on the top or bottom protected int _compressedStyleCloseButtonMarginVertical;// the close button margin on the top or bottom when the tab is on the left or right protected int _fixedStyleRectSize;// tab rect size protected int _closeButtonMargin;// margin around close button protected int _gripLeftMargin;// left margin protected int _closeButtonMarginSize;// margin around the close button protected int _closeButtonLeftMargin;// the close button gap when the tab is on the left protected int _closeButtonRightMargin;// the close button gap when the tab is on the right protected Component _tabLeadingComponent = null; protected Component _tabTrailingComponent = null; protected JideTabbedPane _tabPane; protected Color _tabBackground; protected Color _background; protected Color _highlight; protected Color _lightHighlight; protected Color _shadow; protected Color _darkShadow; protected Color _focus; protected Color _inactiveTabForeground; protected Color _activeTabForeground; protected Color _tabListBackground; protected Color _selectedColor; protected int _textIconGap; protected int _tabRunOverlay; protected boolean _showIconOnTab; protected boolean _showCloseButtonOnTab; protected int _closeButtonAlignment = SwingConstants.TRAILING; protected Insets _tabInsets; protected Insets _selectedTabPadInsets; protected Insets _tabAreaInsets; protected boolean _ignoreContentBorderInsetsIfNoTabs; // Transient variables (recalculated each time TabbedPane is layed out) protected int _tabRuns[] = new int[10]; protected int _runCount = 0; protected int _selectedRun = -1; protected Rectangle _rects[] = new Rectangle[0]; protected int _maxTabHeight; protected int _maxTabWidth; protected int _gripperWidth = 6; protected int _gripperHeight = 6; // Listeners protected ChangeListener _tabChangeListener; protected FocusListener _tabFocusListener; protected PropertyChangeListener _propertyChangeListener; protected MouseListener _mouseListener; protected MouseMotionListener _mousemotionListener; protected MouseWheelListener _mouseWheelListener; // PENDING(api): See comment for ContainerHandler private ContainerListener _containerListener; private ComponentListener _componentListener; // Private instance data private Insets _currentTabInsets = new Insets(0, 0, 0, 0); private Insets _currentPadInsets = new Insets(0, 0, 0, 0); private Insets _currentTabAreaInsets = new Insets(2, 4, 0, 4); private Insets _currentContentBorderInsets = new Insets(3, 0, 0, 0); private Component visibleComponent; // PENDING(api): See comment for ContainerHandler private Vector htmlViews; private Hashtable _mnemonicToIndexMap; /** * InputMap used for mnemonics. Only non-null if the JTabbedPane has mnemonics associated with * it. Lazily created in initMnemonics. */ private InputMap _mnemonicInputMap; // For use when tabLayoutPolicy = SCROLL_TAB_LAYOUT public ScrollableTabSupport _tabScroller; /** * A rectangle used for general layout calculations in order to avoid constructing many new * Rectangles on the fly. */ protected transient Rectangle _calcRect = new Rectangle(0, 0, 0, 0); /** * Number of tabs. When the count differs, the mnemonics are updated. */ // PENDING: This wouldn't be necessary if JTabbedPane had a better // way of notifying listeners when the count changed. private int _tabCount; protected TabCloseButton[] _closeButtons; // UI creation private ThemePainter _painter; private Painter _gripperPainter; private DropTargetListener _dropListener; public DropTarget _dt; // the left margin of the first tab according to the style public final static int DEFAULT_LEFT_MARGIN = 0; public final static int OFFICE2003_LEFT_MARGIN = 18; public final static int EXCEL_LEFT_MARGIN = 6; protected int _rectSizeExtend = 0;//when the style is eclipse, //we should extend the size of the rects for hold the title protected Polygon tabRegion = null; protected Color _selectColor1 = null; protected Color _selectColor2 = null; protected Color _selectColor3 = null; protected Color _unselectColor1 = null; protected Color _unselectColor2 = null; protected Color _unselectColor3 = null; protected Color _officeTabBorderColor; protected Color _defaultTabBorderShadowColor; protected boolean _mouseEnter = false; protected int _indexMouseOver = -1; protected boolean _alwaysShowLineBorder = false; protected boolean _showFocusIndicator = false; public static ComponentUI createUI(JComponent c) { return new BasicJideTabbedPaneUI(); } // UI Installation/De-installation @Override public void installUI(JComponent c) { if (c == null) { return; } _tabPane = (JideTabbedPane) c; if (_tabPane.isTabShown() && _tabPane.getTabLeadingComponent() != null) { _tabLeadingComponent = _tabPane.getTabLeadingComponent(); } if (_tabPane.isTabShown() && _tabPane.getTabTrailingComponent() != null) { _tabTrailingComponent = _tabPane.getTabTrailingComponent(); } c.setLayout(createLayoutManager()); installComponents(); installDefaults(); installColorTheme(); installListeners(); installKeyboardActions(); } public void installColorTheme() { switch (getTabShape()) { case JideTabbedPane.SHAPE_EXCEL: _selectColor1 = _darkShadow; _selectColor2 = _lightHighlight; _selectColor3 = _shadow; _unselectColor1 = _darkShadow; _unselectColor2 = _lightHighlight; _unselectColor3 = _shadow; break; case JideTabbedPane.SHAPE_WINDOWS: case JideTabbedPane.SHAPE_WINDOWS_SELECTED: _selectColor1 = _lightHighlight; _selectColor2 = _shadow; _selectColor3 = _defaultTabBorderShadowColor; _unselectColor1 = _selectColor1; _unselectColor2 = _selectColor2; _unselectColor3 = _selectColor3; break; case JideTabbedPane.SHAPE_VSNET: _selectColor1 = _shadow; _selectColor2 = _shadow; _unselectColor1 = _selectColor1; break; case JideTabbedPane.SHAPE_ROUNDED_VSNET: _selectColor1 = _shadow; _selectColor2 = _selectColor1; _unselectColor1 = _selectColor1; break; case JideTabbedPane.SHAPE_FLAT: _selectColor1 = _shadow; _unselectColor1 = _selectColor1; break; case JideTabbedPane.SHAPE_ROUNDED_FLAT: _selectColor1 = _shadow; _selectColor2 = _shadow; _unselectColor1 = _selectColor1; _unselectColor2 = _selectColor2; break; case JideTabbedPane.SHAPE_BOX: _selectColor1 = _shadow; _selectColor2 = _lightHighlight; _unselectColor1 = getPainter().getControlShadow(); _unselectColor2 = _lightHighlight; break; case JideTabbedPane.SHAPE_OFFICE2003: default: _selectColor1 = _shadow; _selectColor2 = _lightHighlight; _unselectColor1 = _shadow; _unselectColor2 = null; _unselectColor3 = null; } } @Override public void uninstallUI(JComponent c) { uninstallKeyboardActions(); uninstallListeners(); uninstallColorTheme(); uninstallDefaults(); uninstallComponents(); c.setLayout(null); _tabTrailingComponent = null; _tabLeadingComponent = null; _tabPane = null; } public void uninstallColorTheme() { _selectColor1 = null; _selectColor2 = null; _selectColor3 = null; _unselectColor1 = null; _unselectColor2 = null; _unselectColor3 = null; } /** * Invoked by <code>installUI</code> to create a layout manager object to manage the * <code>JTabbedPane</code>. * * @return a layout manager object * * @see TabbedPaneLayout * @see JTabbedPane#getTabLayoutPolicy */ protected LayoutManager createLayoutManager() { if (_tabPane.getTabLayoutPolicy() == JideTabbedPane.SCROLL_TAB_LAYOUT) { return new TabbedPaneScrollLayout(); } else { /* WRAP_TAB_LAYOUT */ return new TabbedPaneLayout(); } } /* In an attempt to preserve backward compatibility for programs * which have extended VsnetJideTabbedPaneUI to do their own layout, the * UI uses the installed layoutManager (and not tabLayoutPolicy) to * determine if scrollTabLayout is enabled. */ protected boolean scrollableTabLayoutEnabled() { return (_tabPane.getLayout() instanceof TabbedPaneScrollLayout); } /** * Creates and installs any required subcomponents for the JTabbedPane. Invoked by installUI. */ protected void installComponents() { if (scrollableTabLayoutEnabled()) { if (_tabScroller == null) { _tabScroller = new ScrollableTabSupport(_tabPane.getTabPlacement()); _tabPane.add(_tabScroller.viewport); _tabPane.add(_tabScroller.scrollForwardButton); _tabPane.add(_tabScroller.scrollBackwardButton); _tabPane.add(_tabScroller.listButton); _tabPane.add(_tabScroller.closeButton); if (_tabLeadingComponent != null) { _tabPane.add(_tabLeadingComponent); } if (_tabTrailingComponent != null) { _tabPane.add(_tabTrailingComponent); } } } } /** * Removes any installed subcomponents from the JTabbedPane. Invoked by uninstallUI. */ protected void uninstallComponents() { if (scrollableTabLayoutEnabled()) { _tabPane.remove(_tabScroller.viewport); _tabPane.remove(_tabScroller.scrollForwardButton); _tabPane.remove(_tabScroller.scrollBackwardButton); _tabPane.remove(_tabScroller.listButton); _tabPane.remove(_tabScroller.closeButton); if (_tabLeadingComponent != null) { _tabPane.remove(_tabLeadingComponent); } if (_tabTrailingComponent != null) { _tabPane.remove(_tabTrailingComponent); } _tabScroller = null; } } protected void installDefaults() { _painter = (ThemePainter) UIDefaultsLookup.get("Theme.painter"); _gripperPainter = (Painter) UIDefaultsLookup.get("JideTabbedPane.gripperPainter"); LookAndFeel.installColorsAndFont(_tabPane, "JideTabbedPane.background", "JideTabbedPane.foreground", "JideTabbedPane.font"); LookAndFeel.installBorder(_tabPane, "JideTabbedPane.border"); Font f = _tabPane.getSelectedTabFont(); if (f == null || f instanceof UIResource) { _tabPane.setSelectedTabFont(UIDefaultsLookup.getFont("JideTabbedPane.selectedTabFont")); } _highlight = UIDefaultsLookup.getColor("JideTabbedPane.light"); _lightHighlight = UIDefaultsLookup.getColor("JideTabbedPane.highlight"); _shadow = UIDefaultsLookup.getColor("JideTabbedPane.shadow"); _darkShadow = UIDefaultsLookup.getColor("JideTabbedPane.darkShadow"); _focus = UIDefaultsLookup.getColor("TabbedPane.focus"); if (getTabShape() == JideTabbedPane.SHAPE_BOX) { _background = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"); _tabBackground = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"); _inactiveTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.foreground"); // text is black _activeTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.foreground"); // text is black _selectedColor = _lightHighlight; } else { _background = UIDefaultsLookup.getColor("JideTabbedPane.background"); _tabBackground = UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground"); _inactiveTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.unselectedTabTextForeground"); _activeTabForeground = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabTextForeground"); _selectedColor = UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground"); } _tabListBackground = UIDefaultsLookup.getColor("JideTabbedPane.tabListBackground"); _textIconGap = UIDefaultsLookup.getInt("JideTabbedPane.textIconGap"); _tabInsets = UIDefaultsLookup.getInsets("JideTabbedPane.tabInsets"); _selectedTabPadInsets = UIDefaultsLookup.getInsets("TabbedPane.selectedTabPadInsets"); _tabAreaInsets = UIDefaultsLookup.getInsets("JideTabbedPane.tabAreaInsets"); Insets insets = _tabPane.getContentBorderInsets(); if (insets == null || insets instanceof UIResource) { _tabPane.setContentBorderInsets(UIDefaultsLookup.getInsets("JideTabbedPane.contentBorderInsets")); } _ignoreContentBorderInsetsIfNoTabs = UIDefaultsLookup.getBoolean("JideTabbedPane.ignoreContentBorderInsetsIfNoTabs"); _tabRunOverlay = UIDefaultsLookup.getInt("JideTabbedPane.tabRunOverlay"); _showIconOnTab = UIDefaultsLookup.getBoolean("JideTabbedPane.showIconOnTab"); _showCloseButtonOnTab = UIDefaultsLookup.getBoolean("JideTabbedPane.showCloseButtonOnTab"); _closeButtonAlignment = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonAlignment"); _gripperWidth = UIDefaultsLookup.getInt("Gripper.size"); _tabRectPadding = UIDefaultsLookup.getInt("JideTabbedPane.tabRectPadding"); _closeButtonMarginHorizon = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginHorizonal"); _closeButtonMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginVertical"); _textMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.textMarginVertical"); _noIconMargin = UIDefaultsLookup.getInt("JideTabbedPane.noIconMargin"); _iconMargin = UIDefaultsLookup.getInt("JideTabbedPane.iconMargin"); _textPadding = UIDefaultsLookup.getInt("JideTabbedPane.textPadding"); _buttonSize = UIDefaultsLookup.getInt("JideTabbedPane.buttonSize"); _buttonMargin = UIDefaultsLookup.getInt("JideTabbedPane.buttonMargin"); _fitStyleBoundSize = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleBoundSize"); _fitStyleFirstTabMargin = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleFirstTabMargin"); _fitStyleIconMinWidth = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleIconMinWidth"); _fitStyleTextMinWidth = UIDefaultsLookup.getInt("JideTabbedPane.fitStyleTextMinWidth"); _compressedStyleNoIconRectSize = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleNoIconRectSize"); _compressedStyleIconMargin = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleIconMargin"); _compressedStyleCloseButtonMarginHorizon = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleCloseButtonMarginHorizontal"); _compressedStyleCloseButtonMarginVertical = UIDefaultsLookup.getInt("JideTabbedPane.compressedStyleCloseButtonMarginVertical"); _fixedStyleRectSize = UIDefaultsLookup.getInt("JideTabbedPane.fixedStyleRectSize"); _closeButtonMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMargin"); _gripLeftMargin = UIDefaultsLookup.getInt("JideTabbedPane.gripLeftMargin"); _closeButtonMarginSize = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonMarginSize"); _closeButtonLeftMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonLeftMargin"); _closeButtonRightMargin = UIDefaultsLookup.getInt("JideTabbedPane.closeButtonRightMargin"); _defaultTabBorderShadowColor = UIDefaultsLookup.getColor("JideTabbedPane.defaultTabBorderShadowColor"); _alwaysShowLineBorder = UIDefaultsLookup.getBoolean("JideTabbedPane.alwaysShowLineBorder"); _showFocusIndicator = UIDefaultsLookup.getBoolean("JideTabbedPane.showFocusIndicator"); } protected void uninstallDefaults() { _painter = null; _gripperPainter = null; _highlight = null; _lightHighlight = null; _shadow = null; _darkShadow = null; _focus = null; _inactiveTabForeground = null; _selectedColor = null; _tabInsets = null; _selectedTabPadInsets = null; _tabAreaInsets = null; _defaultTabBorderShadowColor = null; } protected void installListeners() { if (_propertyChangeListener == null) { _propertyChangeListener = createPropertyChangeListener(); _tabPane.addPropertyChangeListener(_propertyChangeListener); } if (_tabChangeListener == null) { _tabChangeListener = createChangeListener(); _tabPane.addChangeListener(_tabChangeListener); } if (_tabFocusListener == null) { _tabFocusListener = createFocusListener(); _tabPane.addFocusListener(_tabFocusListener); } if (_mouseListener == null) { _mouseListener = createMouseListener(); _tabPane.addMouseListener(_mouseListener); } if (_mousemotionListener == null) { _mousemotionListener = createMouseMotionListener(); _tabPane.addMouseMotionListener(_mousemotionListener); } if (_mouseWheelListener == null) { _mouseWheelListener = createMouseWheelListener(); _tabPane.addMouseWheelListener(_mouseWheelListener); } // PENDING(api) : See comment for ContainerHandler if (_containerListener == null) { _containerListener = new ContainerHandler(); _tabPane.addContainerListener(_containerListener); if (_tabPane.getTabCount() > 0) { htmlViews = createHTMLVector(); } } if (_componentListener == null) { _componentListener = new ComponentHandler(); _tabPane.addComponentListener(_componentListener); } if (!_tabPane.isDragOverDisabled()) { if (_dropListener == null) { _dropListener = createDropListener(); _dt = new DropTarget(getTabPanel(), _dropListener); } } } protected DropListener createDropListener() { return new DropListener(); } protected void uninstallListeners() { // PENDING(api): See comment for ContainerHandler if (_containerListener != null) { _tabPane.removeContainerListener(_containerListener); _containerListener = null; if (htmlViews != null) { htmlViews.removeAllElements(); htmlViews = null; } } if (_componentListener != null) { _tabPane.removeComponentListener(_componentListener); _componentListener = null; } if (_tabChangeListener != null) { _tabPane.removeChangeListener(_tabChangeListener); _tabChangeListener = null; } if (_tabFocusListener != null) { _tabPane.removeFocusListener(_tabFocusListener); _tabFocusListener = null; } if (_mouseListener != null) { _tabPane.removeMouseListener(_mouseListener); _mouseListener = null; } if (_mousemotionListener != null) { _tabPane.removeMouseMotionListener(_mousemotionListener); _mousemotionListener = null; } if (_mouseWheelListener != null) { _tabPane.removeMouseWheelListener(_mouseWheelListener); _mouseWheelListener = null; } if (_propertyChangeListener != null) { _tabPane.removePropertyChangeListener(_propertyChangeListener); _propertyChangeListener = null; } if (_dt != null && _dropListener != null) { _dt.removeDropTargetListener(_dropListener); _dropListener = null; _dt = null; getTabPanel().setDropTarget(null); } } protected ChangeListener createChangeListener() { return new TabSelectionHandler(); } protected FocusListener createFocusListener() { return new TabFocusListener(); } protected PropertyChangeListener createPropertyChangeListener() { return new PropertyChangeHandler(); } protected void installKeyboardActions() { InputMap km = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km); km = getInputMap(JComponent.WHEN_FOCUSED); SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_FOCUSED, km); ActionMap am = getActionMap(); SwingUtilities.replaceUIActionMap(_tabPane, am); ensureCloseButtonCreated(); if (scrollableTabLayoutEnabled()) { _tabScroller.scrollForwardButton.setAction(am.get("scrollTabsForwardAction")); _tabScroller.scrollBackwardButton.setAction(am.get("scrollTabsBackwardAction")); _tabScroller.listButton.setAction(am.get("scrollTabsListAction")); _tabScroller.closeButton.setAction(am.get("closeTabAction")); } } InputMap getInputMap(int condition) { if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) { return (InputMap) UIDefaultsLookup.get("JideTabbedPane.ancestorInputMap"); } else if (condition == JComponent.WHEN_FOCUSED) { return (InputMap) UIDefaultsLookup.get("JideTabbedPane.focusInputMap"); } return null; } ActionMap getActionMap() { ActionMap map = (ActionMap) UIDefaultsLookup.get("JideTabbedPane.actionMap"); if (map == null) { map = createActionMap(); if (map != null) { UIManager.getLookAndFeelDefaults().put("JideTabbedPane.actionMap", map); } } return map; } ActionMap createActionMap() { ActionMap map = new ActionMapUIResource(); map.put("navigateNext", new NextAction()); map.put("navigatePrevious", new PreviousAction()); map.put("navigateRight", new RightAction()); map.put("navigateLeft", new LeftAction()); map.put("navigateUp", new UpAction()); map.put("navigateDown", new DownAction()); map.put("navigatePageUp", new PageUpAction()); map.put("navigatePageDown", new PageDownAction()); map.put("requestFocus", new RequestFocusAction()); map.put("requestFocusForVisibleComponent", new RequestFocusForVisibleAction()); map.put("setSelectedIndex", new SetSelectedIndexAction()); map.put("scrollTabsForwardAction", new ScrollTabsForwardAction()); map.put("scrollTabsBackwardAction", new ScrollTabsBackwardAction()); map.put("scrollTabsListAction", new ScrollTabsListAction()); map.put("closeTabAction", new CloseTabAction()); return map; } protected void uninstallKeyboardActions() { SwingUtilities.replaceUIActionMap(_tabPane, null); SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null); SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_FOCUSED, null); if (_closeButtons != null) { for (int i = 0; i < _closeButtons.length; i++) { _closeButtons[i] = null; } _closeButtons = null; } } /** * Reloads the mnemonics. This should be invoked when a memonic changes, when the title of a * mnemonic changes, or when tabs are added/removed. */ private void updateMnemonics() { resetMnemonics(); for (int counter = _tabPane.getTabCount() - 1; counter >= 0; counter--) { int mnemonic = _tabPane.getMnemonicAt(counter); if (mnemonic > 0) { addMnemonic(counter, mnemonic); } } } /** * Resets the mnemonics bindings to an empty state. */ private void resetMnemonics() { if (_mnemonicToIndexMap != null) { _mnemonicToIndexMap.clear(); _mnemonicInputMap.clear(); } } /** * Adds the specified mnemonic at the specified index. */ private void addMnemonic(int index, int mnemonic) { if (_mnemonicToIndexMap == null) { initMnemonics(); } _mnemonicInputMap.put(KeyStroke.getKeyStroke(mnemonic, Event.ALT_MASK), "setSelectedIndex"); _mnemonicToIndexMap.put(mnemonic, index); } /** * Installs the state needed for mnemonics. */ private void initMnemonics() { _mnemonicToIndexMap = new Hashtable(); _mnemonicInputMap = new InputMapUIResource(); _mnemonicInputMap.setParent(SwingUtilities.getUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)); SwingUtilities.replaceUIInputMap(_tabPane, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, _mnemonicInputMap); } // Geometry @Override public Dimension getPreferredSize(JComponent c) { // Default to LayoutManager's preferredLayoutSize return null; } @Override public Dimension getMinimumSize(JComponent c) { // Default to LayoutManager's minimumLayoutSize return null; } @Override public Dimension getMaximumSize(JComponent c) { // Default to LayoutManager's maximumLayoutSize return null; } // UI Rendering @Override public void paint(Graphics g, JComponent c) { int tc = _tabPane.getTabCount(); paintBackground(g, c); if (tc == 0) { return; } if (_tabCount != tc) { _tabCount = tc; updateMnemonics(); } int selectedIndex = _tabPane.getSelectedIndex(); int tabPlacement = _tabPane.getTabPlacement(); ensureCurrentLayout(); // Paint tab area // If scrollable tabs are enabled, the tab area will be // painted by the scrollable tab panel instead. // if (!scrollableTabLayoutEnabled()) { // WRAP_TAB_LAYOUT paintTabArea(g, tabPlacement, selectedIndex, c); } // Paint content border // if (_tabPane.isTabShown()) paintContentBorder(g, tabPlacement, selectedIndex); } public void paintBackground(Graphics g, Component c) { if (_tabPane.isOpaque()) { int width = c.getWidth(); int height = c.getHeight(); g.setColor(_background); g.fillRect(0, 0, width, height); } } /** * Paints the tabs in the tab area. Invoked by paint(). The graphics parameter must be a valid * <code>Graphics</code> object. Tab placement may be either: <code>JTabbedPane.TOP</code>, * <code>JTabbedPane.BOTTOM</code>, <code>JTabbedPane.LEFT</code>, or * <code>JTabbedPane.RIGHT</code>. The selected index must be a valid tabbed pane tab index (0 * to tab count - 1, inclusive) or -1 if no tab is currently selected. The handling of invalid * parameters is unspecified. * * @param g the graphics object to use for rendering * @param tabPlacement the placement for the tabs within the JTabbedPane * @param selectedIndex the tab index of the selected component */ protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex, Component c) { if (!PAINT_TABAREA) { return; } int tabCount = _tabPane.getTabCount(); Rectangle iconRect = new Rectangle(), textRect = new Rectangle(); // getClip bounds sometime fails, it is safer to go against the components width and height Rectangle tempR = g.getClipBounds(); Rectangle clipRect = new Rectangle(tempR.x, tempR.y, c.getWidth(), c.getHeight()); paintTabAreaBackground(g, clipRect, tabPlacement); // Paint tabRuns of tabs from back to front for (int i = _runCount - 1; i >= 0; i--) { int start = _tabRuns[i]; int next = _tabRuns[(i == _runCount - 1) ? 0 : i + 1]; int end = (next != 0 ? next - 1 : tabCount - 1); for (int j = start; j <= end; j++) { if (_rects[j].intersects(clipRect) && j != selectedIndex) { paintTab(g, tabPlacement, _rects, j, iconRect, textRect); } } } // Paint selected tab if its in the front run // since it may overlap other tabs if (selectedIndex >= 0 && getRunForTab(tabCount, selectedIndex) == 0) { if (_rects[selectedIndex].intersects(clipRect)) { paintTab(g, tabPlacement, _rects, selectedIndex, iconRect, textRect); } } } protected void paintTabAreaBackground(Graphics g, Rectangle rect, int tabPlacement) { if (_tabPane.isOpaque()) { if (getTabShape() == JideTabbedPane.SHAPE_BOX) { g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground")); } else { g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground")); } g.fillRect(rect.x, rect.y, rect.width, rect.height); } } protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect) { if (!PAINT_TAB) { return; } Rectangle tabRect = rects[tabIndex]; int selectedIndex = _tabPane.getSelectedIndex(); boolean isSelected = selectedIndex == tabIndex; Graphics2D g2 = null; Polygon cropShape = null; Shape save = null; int cropx = 0; int cropy = 0; paintTabBackground(g, tabPlacement, tabIndex, tabRect.x, tabRect.y, tabRect.width, tabRect.height, isSelected); Object savedHints = JideSwingUtilities.setupShapeAntialiasing(g); paintTabBorder(g, tabPlacement, tabIndex, tabRect.x, tabRect.y, tabRect.width, tabRect.height, isSelected); JideSwingUtilities.restoreShapeAntialiasing(g, savedHints); Icon icon = _tabPane.getIconForTab(tabIndex); Rectangle tempTabRect = new Rectangle(tabRect); if (_tabPane.isShowGripper()) { tempTabRect.x += _gripperWidth; tempTabRect.width -= _gripperWidth; Rectangle gripperRect = new Rectangle(tabRect); gripperRect.x += _gripLeftMargin; gripperRect.width = _gripperWidth; if (_gripperPainter != null) { _gripperPainter.paint(_tabPane, g, gripperRect, SwingConstants.HORIZONTAL, isSelected ? ThemePainter.STATE_SELECTED : ThemePainter.STATE_DEFAULT); } else { getPainter().paintGripper(_tabPane, g, gripperRect, SwingConstants.HORIZONTAL, isSelected ? ThemePainter.STATE_SELECTED : ThemePainter.STATE_DEFAULT); } } if (isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex) && (!_tabPane.isShowCloseButtonOnSelectedTab() || isSelected)) { if (tabPlacement == TOP || tabPlacement == BOTTOM) { int buttonWidth = _closeButtons[tabIndex].getPreferredSize().width + _closeButtonLeftMargin + _closeButtonRightMargin; if (_closeButtonAlignment == SwingConstants.LEADING) { tempTabRect.x += buttonWidth; tempTabRect.width -= buttonWidth; } else { tempTabRect.width -= buttonWidth; } } else { int buttonHeight = _closeButtons[tabIndex].getPreferredSize().height + _closeButtonLeftMargin + _closeButtonRightMargin; if (_closeButtonAlignment == SwingConstants.LEADING) { tempTabRect.y += buttonHeight; tempTabRect.height -= buttonHeight; } else { tempTabRect.height -= buttonHeight; } } } String title = _tabPane.getDisplayTitleAt(tabIndex); Font font = null; if (isSelected && _tabPane.getSelectedTabFont() != null) { font = _tabPane.getSelectedTabFont(); } else { font = _tabPane.getFont(); } if (isSelected && _tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) { font = font.deriveFont(Font.BOLD); } FontMetrics metrics = g.getFontMetrics(font); layoutLabel(tabPlacement, metrics, tabIndex, title, icon, tempTabRect, iconRect, textRect, isSelected); paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected); paintIcon(g, tabPlacement, tabIndex, icon, iconRect, isSelected); paintFocusIndicator(g, tabPlacement, rects, tabIndex, iconRect, textRect, isSelected); if (cropShape != null) { paintCroppedTabEdge(g, tabPlacement, tabIndex, isSelected, cropx, cropy); g2.setClip(save); } } /* This method will create and return a polygon shape for the given tab rectangle * which has been cropped at the specified cropline with a torn edge visual. * e.g. A "File" tab which has cropped been cropped just after the "i": * ------------- * | ..... | * | . | * | ... . | * | . . | * | . . | * | . . | * -------------- * * The x, y arrays below define the pattern used to create a "torn" edge * segment which is repeated to fill the edge of the tab. * For tabs placed on TOP and BOTTOM, this righthand torn edge is created by * line segments which are defined by coordinates obtained by * subtracting xCropLen[i] from (tab.x + tab.width) and adding yCroplen[i] * to (tab.y). * For tabs placed on LEFT or RIGHT, the bottom torn edge is created by * subtracting xCropLen[i] from (tab.y + tab.height) and adding yCropLen[i] * to (tab.x). */ private int xCropLen[] = {1, 1, 0, 0, 1, 1, 2, 2}; private int yCropLen[] = {0, 3, 3, 6, 6, 9, 9, 12}; private static final int CROP_SEGMENT = 12; private Polygon createCroppedTabClip(int tabPlacement, Rectangle tabRect, int cropline) { int rlen = 0; int start = 0; int end = 0; int ostart = 0; switch (tabPlacement) { case LEFT: case RIGHT: rlen = tabRect.width; start = tabRect.x; end = tabRect.x + tabRect.width; ostart = tabRect.y; break; case TOP: case BOTTOM: default: rlen = tabRect.height; start = tabRect.y; end = tabRect.y + tabRect.height; ostart = tabRect.x; } int rcnt = rlen / CROP_SEGMENT; if (rlen % CROP_SEGMENT > 0) { rcnt++; } int npts = 2 + (rcnt << 3); int xp[] = new int[npts]; int yp[] = new int[npts]; int pcnt = 0; xp[pcnt] = ostart; yp[pcnt++] = end; xp[pcnt] = ostart; yp[pcnt++] = start; for (int i = 0; i < rcnt; i++) { for (int j = 0; j < xCropLen.length; j++) { xp[pcnt] = cropline - xCropLen[j]; yp[pcnt] = start + (i * CROP_SEGMENT) + yCropLen[j]; if (yp[pcnt] >= end) { yp[pcnt] = end; pcnt++; break; } pcnt++; } } if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) { return new Polygon(xp, yp, pcnt); } else { // LEFT or RIGHT return new Polygon(yp, xp, pcnt); } } /* If tabLayoutPolicy == SCROLL_TAB_LAYOUT, this method will paint an edge * indicating the tab is cropped in the viewport display */ private void paintCroppedTabEdge(Graphics g, int tabPlacement, int tabIndex, boolean isSelected, int x, int y) { switch (tabPlacement) { case LEFT: case RIGHT: int xx = x; g.setColor(_shadow); while (xx <= x + _rects[tabIndex].width) { for (int i = 0; i < xCropLen.length; i += 2) { g.drawLine(xx + yCropLen[i], y - xCropLen[i], xx + yCropLen[i + 1] - 1, y - xCropLen[i + 1]); } xx += CROP_SEGMENT; } break; case TOP: case BOTTOM: default: int yy = y; g.setColor(_shadow); while (yy <= y + _rects[tabIndex].height) { for (int i = 0; i < xCropLen.length; i += 2) { g.drawLine(x - xCropLen[i], yy + yCropLen[i], x - xCropLen[i + 1], yy + yCropLen[i + 1] - 1); } yy += CROP_SEGMENT; } } } protected void layoutLabel(int tabPlacement, FontMetrics metrics, int tabIndex, String title, Icon icon, Rectangle tabRect, Rectangle iconRect, Rectangle textRect, boolean isSelected) { textRect.x = textRect.y = iconRect.x = iconRect.y = 0; View v = getTextViewForTab(tabIndex); if (v != null) { _tabPane.putClientProperty("html", v); } SwingUtilities.layoutCompoundLabel(_tabPane, metrics, title, icon, SwingUtilities.CENTER, SwingUtilities.CENTER, SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect, iconRect, textRect, _textIconGap); _tabPane.putClientProperty("html", null); if (tabPlacement == TOP || tabPlacement == BOTTOM) { // iconRect.x = tabRect.x + _iconMargin; // textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding); // iconRect.width = Math.min(iconRect.width, tabRect.width - _tabRectPadding); // textRect.width = tabRect.width - _tabRectPadding - iconRect.width - (icon != null ? _textIconGap + _iconMargin : _noIconMargin); if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED && isShowCloseButton() && isShowCloseButtonOnTab()) { if (!_tabPane.isShowCloseButtonOnSelectedTab()) { if (!isSelected) { iconRect.width = iconRect.width + _closeButtons[tabIndex].getPreferredSize().width + _closeButtonMarginHorizon; textRect.width = 0; } } } } else {// tabplacement is left or right iconRect.y = tabRect.y + _iconMargin; textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding); iconRect.x = tabRect.x + 2; textRect.x = tabRect.x + 2; textRect.width = tabRect.width - _textMarginVertical; textRect.height = tabRect.height - _tabRectPadding - iconRect.height - (icon != null ? _textIconGap + _iconMargin : _noIconMargin); if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED && isShowCloseButton() && isShowCloseButtonOnTab()) { if (!_tabPane.isShowCloseButtonOnSelectedTab()) { if (!isSelected) { iconRect.height = iconRect.height + _closeButtons[tabIndex].getPreferredSize().height + _closeButtonMarginVertical; textRect.height = 0; } } } } } protected void paintIcon(Graphics g, int tabPlacement, int tabIndex, Icon icon, Rectangle iconRect, boolean isSelected) { if (icon != null && iconRect.width >= icon.getIconWidth()) { if (tabPlacement == TOP || tabPlacement == BOTTOM) { icon.paintIcon(_tabPane, g, iconRect.x, iconRect.y); } else { if (iconRect.height < _rects[tabIndex].height - _gripperHeight) { icon.paintIcon(_tabPane, g, iconRect.x, iconRect.y); } } } } protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) { Graphics2D g2d = (Graphics2D) g; if (isSelected && _tabPane.isBoldActiveTab()) { g.setFont(font.deriveFont(Font.BOLD)); } else { g.setFont(font); } String actualText = title; if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) { if (textRect.width <= 0) return; while (SwingUtilities.computeStringWidth(metrics, actualText) > textRect.width) { actualText = actualText.substring(0, actualText.length() - 1); } if (!actualText.equals(title)) { if (actualText.length() >= 2) actualText = actualText.substring(0, actualText.length() - 2) + ".."; else actualText = ""; } } else { if (textRect.height <= 0) return; while (SwingUtilities.computeStringWidth(metrics, actualText) > textRect.height) { actualText = actualText.substring(0, actualText.length() - 1); } if (!actualText.equals(title)) { if (actualText.length() >= 2) actualText = actualText.substring(0, actualText.length() - 2) + ".."; else actualText = ""; } } View v = getTextViewForTab(tabIndex); if (v != null) { // html v.paint(g, textRect); } else { // plain text int mnemIndex = _tabPane.getDisplayedMnemonicIndexAt(tabIndex); JideTabbedPane.ColorProvider colorProvider = _tabPane.getTabColorProvider(); if (_tabPane.isEnabled() && _tabPane.isEnabledAt(tabIndex)) { if (colorProvider != null) { g.setColor(colorProvider.getForegroudAt(tabIndex)); } else { Color color = _tabPane.getForegroundAt(tabIndex); if (isSelected && showFocusIndicator()) { if (!(color instanceof ColorUIResource)) { g.setColor(color); } else { g.setColor(_activeTabForeground); } } else { if (!(color instanceof ColorUIResource)) { g.setColor(color); } else { g.setColor(_inactiveTabForeground); } } } if (tabPlacement == TOP || tabPlacement == BOTTOM) { JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g, actualText, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); } else {// draw string from top to bottom AffineTransform old = g2d.getTransform(); g2d.translate(textRect.x, textRect.y); if (tabPlacement == RIGHT) { g2d.rotate(Math.PI / 2); g2d.translate(0, -textRect.width); } else { g2d.rotate(-Math.PI / 2); g2d.translate(-textRect.height + 7, 0); // no idea why i need 7 here } JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g, actualText, mnemIndex, 0, ((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent()); g2d.setTransform(old); } } else { // tab disabled if (tabPlacement == TOP || tabPlacement == BOTTOM) { g.setColor(_tabPane.getBackgroundAt(tabIndex).brighter()); JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g, actualText, mnemIndex, textRect.x, textRect.y + metrics.getAscent()); g.setColor(_tabPane.getBackgroundAt(tabIndex).darker()); JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g, actualText, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1); } else {// draw string from top to bottom AffineTransform old = g2d.getTransform(); g2d.translate(textRect.x, textRect.y); if (tabPlacement == RIGHT) { g2d.rotate(Math.PI / 2); g2d.translate(0, -textRect.width); } else { g2d.rotate(-Math.PI / 2); g2d.translate(-textRect.height + 7, 0); // no idea why i need 7 here } g.setColor(_tabPane.getBackgroundAt(tabIndex).brighter()); JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g, actualText, mnemIndex, 0, ((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent()); g.setColor(_tabPane.getBackgroundAt(tabIndex).darker()); JideSwingUtilities.drawStringUnderlineCharAt(_tabPane, g, actualText, mnemIndex, tabPlacement == RIGHT ? -1 : 1, ((textRect.width - metrics.getHeight()) / 2) + metrics.getAscent() - 1); g2d.setTransform(old); } } } } /** * this function draws the border around each tab note that this function does now draw the * background of the tab. that is done elsewhere */ protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { if (!PAINT_TAB_BORDER) { return; } switch (getTabShape()) { case JideTabbedPane.SHAPE_BOX: paintBoxTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_EXCEL: paintExcelTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_WINDOWS: paintWindowsTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_WINDOWS_SELECTED: if (isSelected) { paintWindowsTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); } break; case JideTabbedPane.SHAPE_VSNET: paintVsnetTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_ROUNDED_VSNET: paintRoundedVsnetTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_FLAT: paintFlatTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_ROUNDED_FLAT: paintRoundedFlatTabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_OFFICE2003: default: paintOffice2003TabBorder(g, tabPlacement, tabIndex, x, y, w, h, isSelected); } int tabShape = getTabShape(); if (tabShape == JideTabbedPane.SHAPE_WINDOWS) { if (_mouseEnter && _tabPane.getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP && tabIndex == _indexMouseOver && !isSelected && _tabPane.isEnabledAt(_indexMouseOver)) { paintTabBorderMouseOver(g, tabPlacement, tabIndex, x, y, w, h, isSelected); } } else if (tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) { if (_mouseEnter && tabIndex == _indexMouseOver && !isSelected && _tabPane.isEnabledAt(_indexMouseOver)) { paintTabBorderMouseOver(g, tabPlacement, tabIndex, x, y, w, h, isSelected); } } } protected void paintOffice2003TabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); switch (tabPlacement) { case LEFT:// when the tab on the left y += 2; if (isSelected) {// the tab is selected g.setColor(_selectColor1); g.drawLine(x, y + 3, x, y + h - 5);// left g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom // arc g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc g.drawLine(x + 2, y, x + 2, y - 1); for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + 3 + i, y - 2 - i, x + 3 + i, y - 2 - i); } g.drawLine(x + w - 1, y - w + 1, x + w - 1, y - w + 2); g.setColor(_selectColor2); g.drawLine(x + 1, y + 3, x + 1, y + h - 5);// left g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc g.drawLine(x + 3, y, x + 3, y - 1); for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + 4 + i, y - 2 - i, x + 4 + i, y - 2 - i); } } else { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { g.setColor(_unselectColor1); g.drawLine(x, y + 3, x, y + h - 5);// left g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom // arc g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc g.drawLine(x + 2, y, x + 2, y - 1); for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + 3 + i, y - 2 - i, x + 3 + i, y - 2 - i); } g.drawLine(x + w - 1, y - w + 1, x + w - 1, y - w + 2); if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 1, y + 3, x + 1, y + h - 6);// left g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc g.drawLine(x + 3, y, x + 3, y - 1); for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + 4 + i, y - 2 - i, x + 4 + i, y - 2 - i); } g.setColor(getPainter().getControlDk()); } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// bottom // arc } } else { g.setColor(_unselectColor1); g.drawLine(x, y + 3, x, y + h - 5);// left g.drawLine(x + 1, y + h - 4, x + 1, y + h - 4);// bottom // arc g.drawLine(x + 2, y + h - 3, x + w - 1, y + h - 3);// bottom g.drawLine(x + 1, y + 2, x + 1, y + 1);// top arc g.drawLine(x + 2, y, x + 2, y - 1); g.drawLine(x + 3, y - 2, x + 3, y - 2); if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 1, y + 3, x + 1, y + h - 6);// left g.drawLine(x + 2, y + 2, x + 2, y + 1);// top arc g.drawLine(x + 3, y, x + 3, y - 1); g.drawLine(x + 4, y - 2, x + 4, y - 2); } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + 2, y + h - 4, x + w - 1, y + h - 4);// bottom g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5); } } } break; case RIGHT: if (isSelected) {// the tab is selected g.setColor(_selectColor1); g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom // arc g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + w - 4 - i, y - i, x + w - 4 - i, y - i); } g.drawLine(x, y - w + 3, x, y - w + 4); g.setColor(_selectColor2); g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 3);// right g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top arc g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1); for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + w - 5 - i, y - i, x + w - 5 - i, y - i); } } else { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom // arc g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + w - 4 - i, y - i, x + w - 4 - i, y - i); } g.drawLine(x, y - w + 3, x, y - w + 4); if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 4);// right g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top // arc g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1); for (int i = 0; i < w - 4; i++) {// top g.drawLine(x + w - 5 - i, y - i, x + w - 5 - i, y - i); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom // arc g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom } } else { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 3);// right g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom // arc g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom g.drawLine(x + w - 2, y + 4, x + w - 2, y + 3);// top arc g.drawLine(x + w - 3, y + 2, x + w - 3, y + 1);// top arc g.drawLine(x + w - 4, y, x + w - 4, y);// top arc if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 5, x + w - 2, y + h - 4);// right g.drawLine(x + w - 3, y + 4, x + w - 3, y + 3);// top // arc g.drawLine(x + w - 4, y + 2, x + w - 4, y + 1); g.drawLine(x + w - 5, y, x + w - 5, y); } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom // arc g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom } } } break; case BOTTOM: if (isSelected) {// the tab is selected g.setColor(_selectColor1); g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right // arc g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc g.drawLine(x, y + h - 4, x, y + h - 4);// left arc // left for (int i = 3; i < h - 2; i++) { g.drawLine(x + 2 - i, y + h - 2 - i, x + 2 - i, y + h - 2 - i); } g.drawLine(x - h + 3, y, x - h + 4, y); g.setColor(_selectColor2); g.drawLine(x + 5, y + h - 2, x + w - 3, y + h - 2);// bottom g.drawLine(x + w - 2, y, x + w - 2, y + h - 3);// right g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left arc g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left arc g.drawLine(x, y + h - 5, x, y + h - 5);// left arc for (int i = 3; i < h - 2; i++) {// left g.drawLine(x + 2 - i, y + h - 3 - i, x + 2 - i, y + h - 3 - i); } } else { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right // arc g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc g.drawLine(x, y + h - 4, x, y + h - 4);// left arc // left for (int i = 3; i < h - 2; i++) { g.drawLine(x + 2 - i, y + h - 2 - i, x + 2 - i, y + h - 2 - i); } g.drawLine(x - h + 3, y, x - h + 4, y); if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left // arc g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left // arc g.drawLine(x, y + h - 5, x, y + h - 5);// left arc // left for (int i = 3; i < h - 2; i++) { g.drawLine(x + 2 - i, y + h - 3 - i, x + 2 - i, y + h - 3 - i); } g.drawLine(x + 5, y + h - 2, x + w - 4, y + h - 2);// bottom } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2); g.drawLine(x + w - 2, y + h - 3, x + w - 2, y);// right } } else { g.setColor(_unselectColor1); g.drawLine(x + 5, y + h - 1, x + w - 3, y + h - 1);// bottom g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right // arc g.drawLine(x + 3, y + h - 2, x + 4, y + h - 2);// left arc g.drawLine(x + 1, y + h - 3, x + 2, y + h - 3);// left arc g.drawLine(x, y + h - 4, x, y + h - 4);// left arc if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 3, y + h - 3, x + 4, y + h - 3);// left // arc g.drawLine(x + 1, y + h - 4, x + 2, y + h - 4);// left // arc g.drawLine(x, y + h - 5, x, y + h - 5);// left arc g.drawLine(x + 5, y + h - 2, x + w - 4, y + h - 2);// bottom } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2); g.drawLine(x + w - 2, y + h - 3, x + w - 2, y);// right } } } break; case TOP: default: if (isSelected) {// the tab is selected g.setColor(_selectColor1); g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc g.drawLine(x, y + 3, x, y + 3); g.drawLine(x + 5, y, x + w - 3, y);// top g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right // left for (int i = 3; i < h - 2; i++) { g.drawLine(x + 2 - i, y + 1 + i, x + 2 - i, y + 1 + i); } g.drawLine(x - h + 3, y + h - 1, x - h + 4, y + h - 1); g.setColor(_selectColor2); g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc g.drawLine(x, y + 4, x, y + 4); g.drawLine(x + 5, y + 1, x + w - 3, y + 1);// top g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right // left for (int i = 3; i < h - 2; i++) { g.drawLine(x + 2 - i, y + 2 + i, x + 2 - i, y + 2 + i); } } else { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { g.setColor(_unselectColor1); g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc g.drawLine(x, y + 3, x, y + 3); g.drawLine(x + 5, y, x + w - 3, y);// top g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right // left for (int i = 3; i < h - 2; i++) { g.drawLine(x + 2 - i, y + 1 + i, x + 2 - i, y + 1 + i); } g.drawLine(x - h + 3, y + h - 1, x - h + 4, y + h - 1); if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc g.drawLine(x, y + 4, x, y + 4); // left for (int i = 3; i < h - 2; i++) { g.drawLine(x + 2 - i, y + 2 + i, x + 2 - i, y + 2 + i); } g.drawLine(x + 5, y + 1, x + w - 4, y + 1);// top } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 3, y + 1, x + w - 3, y + 1); g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right } } else { g.setColor(_unselectColor1); g.drawLine(x + 3, y + 1, x + 4, y + 1);// left arc g.drawLine(x + 1, y + 2, x + 2, y + 2);// left arc g.drawLine(x, y + 3, x, y + 3); g.drawLine(x + 5, y, x + w - 3, y);// top g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 3, y + 2, x + 4, y + 2);// left arc g.drawLine(x + 1, y + 3, x + 2, y + 3);// left arc g.drawLine(x, y + 4, x, y + 4); g.drawLine(x + 5, y + 1, x + w - 4, y + 1);// top } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 3, y + 1, x + w - 3, y + 1); g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 1);// right } } } } } protected void paintExcelTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); switch (tabPlacement) { case LEFT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y + 5, x, y + h - 5);// left for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i); } for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i); } if (_selectColor2 != null) { g.setColor(_selectColor2); g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i); } } if (_selectColor3 != null) { g.setColor(_selectColor3); g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i); } } } else { if (tabIndex == 0) { g.setColor(_unselectColor1); g.drawLine(x, y + 5, x, y + h - 5);// left for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i); } for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left for (int i = 0, j = 0; i < w / 2; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i); } } } else if (tabIndex == _tabPane.getSelectedIndex() - 1) { g.setColor(_unselectColor1); g.drawLine(x, y + 5, x, y + h - 5);// left for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i); } for (int i = 0, j = 0; i < 5; i++, j = j + 2) {// bottom g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point for (int i = 0, j = 0; i < 5; i++, j = j + 2) {// bottom g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i); } } } else if (tabIndex != _tabPane.getSelectedIndex() - 1) { g.setColor(_unselectColor1); g.drawLine(x, y + 5, x, y + h - 5);// left for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 4 - i, x + 2 + j, y + 4 - i); } for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom g.drawLine(x + j, y + h - 4 + i, x + 1 + j, y + h - 4 + i); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 1, y + 6, x + 1, y + h - 6);// left for (int i = 0, j = 0; i < 4; i++, j = j + 2) {// top g.drawLine(x + 1 + j, y + 5 - i, x + 2 + j, y + 5 - i); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + 1, y + h - 5, x + 1, y + h - 5);// a point for (int i = 0, j = 0; i < w / 2 + 1; i++, j = j + 2) {// bottom g.drawLine(x + 2 + j, y + h - 4 + i, x + 3 + j, y + h - 4 + i); } } } } break; case RIGHT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i); } for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i); } if (_selectColor2 != null) { g.setColor(_selectColor2); g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i); } } if (_selectColor3 != null) { g.setColor(_selectColor3); g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i); } } } else { if (tabIndex == 0) { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i); } for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a // point for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i); } } } else if (tabIndex == _tabPane.getSelectedIndex() - 1) { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right for (int i = 0, j = 0; i < 4; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i); } for (int i = 0, j = 0; i < 5; i++, j += 2) {// bottom g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right for (int i = 0, j = 0; i < 4; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point for (int i = 0, j = 0; i < 5; i++, j += 2) {// bottom g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i); } } } else if (tabIndex != _tabPane.getSelectedIndex() - 1) { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + 5, x + w - 1, y + h - 5);// right for (int i = 0, j = 0; i < 4; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 4 - i, x + w - 3 - j, y + 4 - i); } for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom g.drawLine(x + w - 1 - j, y + h - 4 + i, x + w - 2 - j, y + h - 4 + i); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 6, x + w - 2, y + h - 6);// right for (int i = 0, j = 0; i < 4; i++, j += 2) {// top g.drawLine(x + w - 2 - j, y + 5 - i, x + w - 3 - j, y + 5 - i); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 2, y + h - 5, x + w - 2, y + h - 5);// a point for (int i = 0, j = 0; i < w / 2 + 1; i++, j += 2) {// bottom g.drawLine(x + w - 3 - j, y + h - 4 + i, x + w - 4 - j, y + h - 4 + i); } } } } break; case BOTTOM: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + 5, y + h - 1, x + w - 5, y + h - 1);// bottom for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j); } for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 4 - 1 + i, y + h - 1 - j, x + w - 4 - 1 + i, y + h - 2 - j); } if (_selectColor2 != null) { g.setColor(_selectColor2); g.drawLine(x + 5, y + h - 3, x + 5, y + h - 3);// bottom for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 4 - i, y + h - 4 - j, x + 4 - i, y + h - 5 - j); } } if (_selectColor3 != null) { g.setColor(_selectColor3); g.drawLine(x + 5, y + h - 2, x + w - 6, y + h - 2);// a point for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j); } } } else { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { g.setColor(_unselectColor1); g.drawLine(x + 5, y + h - 1, x + w - 5, y + h - 1);// bottom for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j); } for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 4 - 1 + i, y + h - 1 - j, x + w - 4 - 1 + i, y + h - 2 - j); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j); } } } else if (tabIndex == _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) { g.setColor(_unselectColor1); g.drawLine(x + 5, y + h - 1, x + w - 6, y + h - 1);// bottom for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j); } for (int i = 0, j = 0; i < 5; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + h - 1 - j, x + w - 5 + i, y + h - 2 - j); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point for (int i = 0, j = 0; i < 5; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j); } } } else if (tabIndex != _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) { g.setColor(_unselectColor1); g.drawLine(x + 5, y + h - 1, x + w - 6, y + h - 1);// bottom for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 4 - i, y + h - 2 - j, x + 4 - i, y + h - 3 - j); } for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + h - 1 - j, x + w - 5 + i, y + h - 2 - j); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 5 - i, y + h - 2 - j, x + 5 - i, y + h - 3 - j); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 6, y + h - 2, x + w - 6, y + h - 2);// a point for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + h - 3 - j, x + w - 5 + i, y + h - 4 - j); } } } } break; case TOP: default: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + 5, y, x + w - 5, y);// top for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j); } for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j); } if (_selectColor2 != null) { g.setColor(_selectColor2); g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j); } } if (_selectColor3 != null) { g.setColor(_selectColor3); g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j); } } } else { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { g.setColor(_unselectColor1); g.drawLine(x + 5, y, x + w - 5, y);// top for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j); } for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// left g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j); } } } else if (tabIndex == _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) { g.setColor(_unselectColor1); g.drawLine(x + 5, y, x + w - 5, y);// top for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j); } for (int i = 0, j = 0; i < 5; i++, j += 2) {// right g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point for (int i = 0, j = 0; i < 5; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j); } } } else if (tabIndex != _tabPane.getSelectedIndex() + (leftToRight ? -1 : 1)) { g.setColor(_unselectColor1); g.drawLine(x + 5, y, x + w - 5, y);// top for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 4 - i, y + 1 + j, x + 4 - i, y + 2 + j); } for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 4 - 1 + i, y + j, x + w - 4 - 1 + i, y + 1 + j); } if (_unselectColor2 != null) { g.setColor(_unselectColor2); g.drawLine(x + 6, y + 1, x + w - 7, y + 1);// top for (int i = 0, j = 0; i < 5; i++, j += 2) {// left g.drawLine(x + 5 - i, y + 1 + j, x + 5 - i, y + 2 + j); } } if (_unselectColor3 != null) { g.setColor(_unselectColor3); g.drawLine(x + w - 6, y + 1, x + w - 6, y + 1);// a point for (int i = 0, j = 0; i < h / 2 + 1; i++, j += 2) {// right g.drawLine(x + w - 5 + i, y + 2 + j, x + w - 5 + i, y + 3 + j); } } } } } } protected void paintWindowsTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { int colorTheme = getColorTheme(); switch (tabPlacement) { case LEFT: if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x - 2, y + 1, x - 2, y + h - 1);// left g.drawLine(x - 1, y, x - 1, y);// top arc g.drawLine(x, y - 1, x + w - 1, y - 1);// top g.setColor(_selectColor2); g.drawLine(x - 1, y + h, x - 1, y + h);// bottom arc g.drawLine(x, y + h + 1, x, y + h + 1);// bottom arc g.drawLine(x + 1, y + h, x + w - 1, y + h);// bottom g.setColor(_selectColor3); g.drawLine(x, y + h, x, y + h);// bottom arc g.drawLine(x + 1, y + h + 1, x + w - 1, y + h + 1);// bottom } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y + 2, x, y + h - 3);// left g.drawLine(x + 1, y + 1, x + 1, y + 1);// top arc g.drawLine(x + 2, y, x + w - 1, y);// top g.setColor(_unselectColor2); g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// bottom arc g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc g.drawLine(x + 3, y + h - 2, x + w - 1, y + h - 2);// bottom g.setColor(_unselectColor3); g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// bottom arc g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y + 3, x, y + h - 2);// left g.drawLine(x + 1, y + 2, x + 1, y + 2);// top arc g.drawLine(x + 2, y + 1, x + w - 1, y + 1);// top g.setColor(_unselectColor2); g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc g.drawLine(x + 2, y + h, x + 2, y + h);// bottom arc g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom g.setColor(_unselectColor3); g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc g.drawLine(x + 3, y + h, x + w - 1, y + h);// bottom } } } else { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x - 2, y + 1, x - 2, y + h - 1);// left g.drawLine(x - 1, y, x - 1, y);// top arc g.drawLine(x, y - 1, x, y - 1);// top arc g.drawLine(x - 1, y + h, x - 1, y + h);// bottom arc g.drawLine(x, y + h + 1, x, y + h + 1);// bottom arc g.setColor(_selectColor2); g.drawLine(x - 1, y + 1, x - 1, y + h - 1);// left g.drawLine(x, y, x, y + h);// left g.setColor(_selectColor3); g.drawLine(x + 1, y - 2, x + w - 1, y - 2);// top g.drawLine(x + 1, y + h + 2, x + w - 1, y + h + 2);// bottom } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y + 2, x, y + h - 4);// left g.drawLine(x + 1, y + 1, x + 1, y + 1);// top arc g.drawLine(x + 2, y, x + w - 1, y);// top g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3);// bottom arc g.drawLine(x + 2, y + h - 2, x + w - 1, y + h - 2);// bottom } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y + 4, x, y + h - 2);// left g.drawLine(x + 1, y + 3, x + 1, y + 3);// top arc g.drawLine(x + 2, y + 2, x + w - 1, y + 2);// top g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc g.drawLine(x + 2, y + h, x + w - 1, y + h);// bottom } } } break; case RIGHT: if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + w - 1, y - 1, x, y - 1);// top g.setColor(_selectColor2); g.drawLine(x + w, y + 1, x + w, y + h - 1);// right g.drawLine(x + w - 1, y + h, x, y + h);// bottom g.setColor(_selectColor3); g.drawLine(x + w, y, x + w, y);// top arc g.drawLine(x + w + 1, y + 1, x + w + 1, y + h - 1);// right g.drawLine(x + w, y + h, x + w, y + h);// bottom arc g.drawLine(x + w - 1, y + h + 1, x, y + h + 1);// bottom } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + w - 3, y, x, y);// top g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 3);// right g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom g.setColor(_unselectColor3); g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top arc g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);// right g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom arc g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + w - 3, y + 1, x, y + 1);// top g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 3, x + w - 2, y + h - 2);// right g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom g.setColor(_unselectColor3); g.drawLine(x + w - 2, y + 2, x + w - 2, y + 2);// top arc g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 2);// right g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc g.drawLine(x + w - 3, y + h, x, y + h);// bottom } } } else { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + w + 1, y + 1, x + w + 1, y + h - 1);// right g.drawLine(x + w, y, x + w, y);// top arc g.drawLine(x + w - 1, y - 1, x + w - 1, y - 1);// top arc g.drawLine(x + w, y + h, x + w, y + h);// bottom arc g.drawLine(x + w - 1, y + h + 1, x + w - 1, y + h + 1);// bottom arc g.setColor(_selectColor2); g.drawLine(x + w, y + 1, x + w, y + h - 1);// right g.drawLine(x + w - 1, y, x + w - 1, y + h);// right g.setColor(_selectColor3); g.drawLine(x + w - 2, y - 2, x, y - 2);// top g.drawLine(x + w - 2, y + h + 2, x, y + h + 2);// bottom } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 4);// right g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top arc g.drawLine(x + w - 2, y + h - 3, x + w - 2, y + h - 3);// bottom arc g.drawLine(x + w - 3, y, x, y);// top g.drawLine(x + w - 3, y + h - 2, x, y + h - 2);// bottom } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2);// right g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3);// top arc g.drawLine(x + w - 3, y + 2, x, y + 2);// top g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc g.drawLine(x + w - 3, y + h, x, y + h);// bottom } } } break; case BOTTOM: if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y + h, x, y + h);// left arc g.drawLine(x - 1, y + h - 1, x - 1, y);// left g.setColor(_selectColor2); g.drawLine(x + 1, y + h, x + w - 2, y + h);// bottom g.drawLine(x + w - 1, y + h - 1, x + w - 1, y - 1);// right g.setColor(_selectColor3); g.drawLine(x + 1, y + h + 1, x + w - 2, y + h + 1);// bottom g.drawLine(x + w - 1, y + h, x + w - 1, y + h);// right arc g.drawLine(x + w, y + h - 1, x + w, y - 1);// right } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y + h - 2, x, y + h - 2);// left arc g.drawLine(x - 1, y + h - 3, x - 1, y);// left g.setColor(_unselectColor2); g.drawLine(x + 1, y + h - 2, x + w - 4, y + h - 2);// bottom g.drawLine(x + w - 3, y + h - 3, x + w - 3, y - 1);// right g.setColor(_unselectColor3); g.drawLine(x + 1, y + h - 1, x + w - 4, y + h - 1);// bottom g.drawLine(x + w - 3, y + h - 2, x + w - 3, y + h - 2);// right arc g.drawLine(x + w - 2, y + h - 3, x + w - 2, y - 1);// right } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc g.drawLine(x + 1, y + h - 3, x + 1, y);// left g.setColor(_unselectColor2); g.drawLine(x + 3, y + h - 2, x + w - 2, y + h - 2);// bottom g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right g.setColor(_unselectColor3); g.drawLine(x + 3, y + h - 1, x + w - 2, y + h - 1);// bottom g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);// right arc g.drawLine(x + w, y + h - 3, x + w, y);// right } } } else { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + 1, y + h + 1, x + w, y + h + 1);// bottom g.drawLine(x, y + h, x, y + h);// right arc g.drawLine(x - 1, y + h - 1, x - 1, y + h - 1);// right arc g.drawLine(x + w + 1, y + h, x + w + 1, y + h);// left arc g.drawLine(x + w + 2, y + h - 1, x + w + 2, y + h - 1);// left arc g.setColor(_selectColor2); g.drawLine(x + 1, y + h, x + w, y + h);// bottom g.drawLine(x, y + h - 1, x + w + 1, y + h - 1);// bottom g.setColor(_selectColor3); g.drawLine(x - 1, y + h - 2, x - 1, y);// left g.drawLine(x + w + 2, y + h - 2, x + w + 2, y);// right } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);// bottom g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right arc g.drawLine(x + w - 1, y + h - 3, x + w - 1, y - 1);// right g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc g.drawLine(x + 1, y + h - 3, x + 1, y);// left } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1);// bottom g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// right arc g.drawLine(x + w - 1, y + h - 3, x + w - 1, y - 1);// right g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left arc g.drawLine(x + 1, y + h - 3, x + 1, y);// left } } } break; case TOP: default: if (colorTheme == JideTabbedPane.COLOR_THEME_OFFICE2003 || colorTheme == JideTabbedPane.COLOR_THEME_WIN2K) { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y - 1, x, y - 1); // left arc g.drawLine(x - 1, y, x - 1, y + h - 1);// left g.drawLine(x + 1, y - 2, x + w + 1, y - 2);// top g.setColor(_selectColor2); g.drawLine(x + w + 2, y - 1, x + w + 2, y + h - 1);// right g.setColor(_selectColor3); g.drawLine(x + w + 2, y - 1, x + w + 2, y - 1);// right arc g.drawLine(x + w + 3, y, x + w + 3, y + h - 1);// right } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left g.drawLine(x + 3, y, x + w - 2, y); // top g.setColor(_unselectColor2); g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right g.setColor(_unselectColor3); g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc g.drawLine(x + w, y + 2, x + w, y + h - 1);// right } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left g.drawLine(x + 3, y, x + w - 2, y); // top g.setColor(_unselectColor2); g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right g.setColor(_unselectColor3); g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc g.drawLine(x + w, y + 2, x + w, y + h - 1);// right } } } else { if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + 1, y - 2, x + w, y - 2); // top g.drawLine(x, y - 1, x, y - 1); // left arc g.drawLine(x - 1, y, x - 1, y); // left arc g.drawLine(x + w + 1, y - 1, x + w + 1, y - 1);// right arc g.drawLine(x + w + 2, y, x + w + 2, y);// right arc g.setColor(_selectColor2); g.drawLine(x + 1, y - 1, x + w, y - 1);// top g.drawLine(x, y, x + w + 1, y);// top g.setColor(_selectColor3); g.drawLine(x - 1, y + 1, x - 1, y + h - 1);// left g.drawLine(x + w + 2, y + 1, x + w + 2, y + h - 1);// right } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc g.drawLine(x + 3, y, x + w - 3, y); // top g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc g.drawLine(x + 3, y, x + w - 3, y); // top g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// right arc g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1);// right } } } } } protected void paintTabBorderMouseOver(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS) { switch (tabPlacement) { case LEFT: if (tabIndex > _tabPane.getSelectedIndex()) { y = y - 2; } g.setColor(_selectColor1); g.drawLine(x, y + 4, x, y + h - 2); g.drawLine(x + 1, y + 3, x + 1, y + 3); g.drawLine(x + 2, y + 2, x + 2, y + 2); g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); g.drawLine(x + 2, y + h, x + 2, y + h); g.setColor(_selectColor2); g.drawLine(x + 1, y + 4, x + 1, y + h - 2); g.drawLine(x + 2, y + 3, x + 2, y + h - 1); break; case RIGHT: if (tabIndex > _tabPane.getSelectedIndex()) { y = y - 2; } g.setColor(_selectColor1); g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2); g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3); g.drawLine(x + w - 3, y + 2, x + w - 3, y + 2); g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1); g.drawLine(x + w - 3, y + h, x + w - 3, y + h); g.setColor(_selectColor2); g.drawLine(x + w - 2, y + 4, x + w - 2, y + h - 2); g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 1); break; case BOTTOM: g.setColor(_selectColor1); g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1); g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2); g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3); g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2); g.drawLine(x + w - 1, y + h - 3, x + w - 1, y + h - 3); g.setColor(_selectColor2); g.drawLine(x + 3, y + h - 2, x + w - 3, y + h - 2); g.drawLine(x + 2, y + h - 3, x + w - 2, y + h - 3); break; case TOP: default: g.setColor(_selectColor1); g.drawLine(x + 3, y, x + w - 3, y); g.drawLine(x + 2, y + 1, x + 2, y + 1); g.drawLine(x + 1, y + 2, x + 1, y + 2); g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1); g.drawLine(x + w - 1, y + 2, x + w - 1, y + 2); g.setColor(_selectColor2); g.drawLine(x + 3, y + 1, x + w - 3, y + 1); g.drawLine(x + 2, y + 2, x + w - 2, y + 2); } } else if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) { switch (tabPlacement) { case LEFT: if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) { if (tabIndex > _tabPane.getSelectedIndex()) { y -= 2; } g.setColor(_selectColor1); g.drawLine(x, y + 4, x, y + h - 2); g.drawLine(x + 1, y + 3, x + 1, y + 3); g.drawLine(x + 2, y + 2, x + 2, y + 2); g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); g.drawLine(x + 2, y + h, x + 2, y + h); g.setColor(_selectColor2); g.drawLine(x + 1, y + 4, x + 1, y + h - 2); g.drawLine(x + 2, y + 3, x + 2, y + h - 1); g.setColor(_selectColor3); g.drawLine(x + 3, y + 2, x + w - 1, y + 2); g.drawLine(x + 3, y + h, x + w - 1, y + h); } else { if (tabIndex > _tabPane.getSelectedIndex()) { y = y - 1; } g.setColor(_selectColor1); g.drawLine(x, y + 3, x, y + h - 2);// left g.drawLine(x + 1, y + 2, x + 1, y + 2);// top arc g.drawLine(x + 2, y + 1, x + w - 1, y + 1);// top g.setColor(_selectColor2); g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1);// bottom arc g.drawLine(x + 2, y + h, x + 2, y + h);// bottom arc g.drawLine(x + 3, y + h - 1, x + w - 1, y + h - 1);// bottom g.setColor(_selectColor3); g.drawLine(x + 2, y + h - 1, x + 2, y + h - 1);// bottom arc g.drawLine(x + 3, y + h, x + w - 1, y + h);// bottom } break; case RIGHT: if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) { if (tabIndex > _tabPane.getSelectedIndex()) { y = y - 2; } g.setColor(_selectColor1); g.drawLine(x + w - 1, y + 4, x + w - 1, y + h - 2); g.drawLine(x + w - 2, y + 3, x + w - 2, y + 3); g.drawLine(x + w - 3, y + 2, x + w - 3, y + 2); g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1); g.drawLine(x + w - 3, y + h, x + w - 3, y + h); g.setColor(_selectColor2); g.drawLine(x + w - 2, y + 4, x + w - 2, y + h - 2); g.drawLine(x + w - 3, y + 3, x + w - 3, y + h - 1); g.setColor(_selectColor3); g.drawLine(x + w - 4, y + 2, x, y + 2); g.drawLine(x + w - 4, y + h, x, y + h); } else { if (tabIndex > _tabPane.getSelectedIndex()) { y = y - 1; } g.setColor(_selectColor3); g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 2);// right g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1);// bottom arc g.drawLine(x + w - 3, y + h, x, y + h);// bottom g.setColor(_selectColor2); g.drawLine(x + w - 2, y + 3, x + w - 2, y + h - 2);// right g.drawLine(x + w - 3, y + h - 1, x, y + h - 1);// bottom g.setColor(_selectColor1); g.drawLine(x + w - 2, y + 2, x + w - 2, y + 2);// top arc g.drawLine(x + w - 3, y + 1, x, y + 1);// top } break; case BOTTOM: if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) { g.setColor(_selectColor1); g.drawLine(x + 3, y + h - 1, x + w - 3, y + h - 1); g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2); g.drawLine(x + 1, y + h - 3, x + 1, y + h - 3); g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2); g.drawLine(x + w - 1, y + h - 3, x + w - 1, y + h - 3); g.setColor(_selectColor2); g.drawLine(x + 3, y + h - 2, x + w - 3, y + h - 2); g.drawLine(x + 2, y + h - 3, x + w - 2, y + h - 3); g.setColor(_selectColor3); g.drawLine(x + 1, y, x + 1, y + h - 4); // left g.drawLine(x + w - 1, y, x + w - 1, y + h - 4);// right } else { if (tabIndex > _tabPane.getSelectedIndex()) { x = x - 2; } g.setColor(_selectColor3); g.drawLine(x + 3, y + h - 1, x + w - 2, y + h - 1);// bottom g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2);// right arc g.drawLine(x + w, y + h - 3, x + w, y);// right g.setColor(_selectColor1); g.drawLine(x + 2, y + h - 2, x + 2, y + h - 2);// left g.drawLine(x + 1, y + h - 3, x + 1, y);// left arc g.setColor(_selectColor2); g.drawLine(x + 3, y + h - 2, x + w - 2, y + h - 2);// bottom g.drawLine(x + w - 1, y + h - 3, x + w - 1, y);// right } break; case TOP: default: if (getColorTheme() == JideTabbedPane.COLOR_THEME_WINXP) { g.setColor(_selectColor1); g.drawLine(x + 3, y, x + w - 3, y); g.drawLine(x + 2, y + 1, x + 2, y + 1); g.drawLine(x + 1, y + 2, x + 1, y + 2); g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1); g.drawLine(x + w - 1, y + 2, x + w - 1, y + 2); g.setColor(_selectColor2); g.drawLine(x + 3, y + 1, x + w - 3, y + 1); g.drawLine(x + 2, y + 2, x + w - 2, y + 2); g.setColor(_selectColor3); g.drawLine(x + 1, y + 3, x + 1, y + h - 1); // left g.drawLine(x + w - 1, y + 3, x + w - 1, y + h - 1);// right } else { if (tabIndex > _tabPane.getSelectedIndex()) { x = x - 1; } g.setColor(_selectColor1); g.drawLine(x + 2, y + 1, x + 2, y + 1); // left arc g.drawLine(x + 1, y + 2, x + 1, y + h - 1); // left g.drawLine(x + 3, y, x + w - 2, y); // top g.setColor(_selectColor2); g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1);// right g.setColor(_selectColor3); g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1);// right arc g.drawLine(x + w, y + 2, x + w, y + h - 1);// right } } } } protected void paintVsnetTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); switch (tabPlacement) { case LEFT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x + w - 1, y);// top g.drawLine(x, y, x, y + h - 2);// left g.setColor(_selectColor2); g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom } else { g.setColor(_unselectColor1); if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + 2, y + h - 2, x + w - 2, y + h - 2);// bottom } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x + 2, y, x + w - 2, y);// top } } break; case RIGHT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x + w - 1, y);// top g.setColor(_selectColor2); g.drawLine(x + w - 1, y, x + w - 1, y + h - 2);// left g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom } else { g.setColor(_unselectColor1); if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + 1, y + h - 2, x + w - 3, y + h - 2);// bottom } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x + 1, y, x + w - 3, y);// top } } break; case BOTTOM: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x, y + h - 1); // left g.setColor(_selectColor2); g.drawLine(x, y + h - 1, x + w - 1, y + h - 1); // bottom g.drawLine(x + w - 1, y, x + w - 1, y + h - 2); // right } else { g.setColor(_unselectColor1); if (leftToRight) { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x, y + 2, x, y + h - 2); // left } } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x, y + 2, x, y + h - 2); // left } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } } } break; case TOP: default: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y + 1, x, y + h - 1); // left g.drawLine(x, y, x + w - 1, y); // top g.setColor(_selectColor2); g.drawLine(x + w - 1, y, x + w - 1, y + h - 1); // right } else { g.setColor(_unselectColor1); if (leftToRight) { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x, y + 2, x, y + h - 2); // left } } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x, y + 2, x, y + h - 2); // left } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } } } } } protected void paintRoundedVsnetTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); switch (tabPlacement) { case LEFT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + 2, y, x + w - 1, y);// top g.drawLine(x + 1, y + 1, x + 1, y + 1);// top-left g.drawLine(x, y + 2, x, y + h - 3);// left g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2);// bottom-left g.drawLine(x + 2, y + h - 1, x + w - 1, y + h - 1);// bottom } else { g.setColor(_unselectColor1); if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + 2, y + h - 2, x + w - 2, y + h - 2);// bottom } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x + 2, y + 1, x + w - 2, y + 1);// top } } break; case RIGHT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x + w - 3, y);// top g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1);// top-left g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3);// left g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2);// bottom-left g.drawLine(x, y + h - 1, x + w - 3, y + h - 1);// bottom } else { g.setColor(_unselectColor1); if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + 1, y + h - 2, x + w - 3, y + h - 2);// bottom } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x + 1, y + 1, x + w - 3, y + 1);// top } } break; case BOTTOM: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x, y + h - 3); // left g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2); // bottom-left g.drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1); // bottom g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2); // bottom-right g.drawLine(x + w - 1, y, x + w - 1, y + h - 3); // right } else { g.setColor(_unselectColor1); if (leftToRight) { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x, y + 2, x, y + h - 2); // left } } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x, y + 2, x, y + h - 2); // left } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } } } break; case TOP: default: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y + 2, x, y + h - 1); // left g.drawLine(x, y + 2, x + 2, y); // top-left g.drawLine(x + 2, y, x + w - 3, y); // top g.drawLine(x + w - 3, y, x + w - 1, y + 2); // top-left g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1); // right } else { g.setColor(_unselectColor1); if (leftToRight) { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != 0) { g.drawLine(x, y + 2, x, y + h - 2); // left } } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.drawLine(x, y + 2, x, y + h - 2); // left } else if (tabIndex < _tabPane.getSelectedIndex() && tabIndex != _tabPane.getTabCount() - 1) { g.drawLine(x + w - 2, y + 2, x + w - 2, y + h - 2); // right } } } } } protected void paintFlatTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { switch (tabPlacement) { case LEFT: if (isSelected) { g.setColor(_selectColor1); g.drawRect(x, y, w, h); } else { g.setColor(_unselectColor1); if (tabIndex > _tabPane.getSelectedIndex()) { if (tabIndex == _tabPane.getTabCount() - 1) { g.drawRect(x, y, w, h - 1); } else { g.drawRect(x, y, w, h); } } else if (tabIndex < _tabPane.getSelectedIndex()) { g.drawRect(x, y, w, h); } } break; case RIGHT: if (isSelected) { g.setColor(_selectColor1); g.drawRect(x - 1, y, w, h); } else { g.setColor(_unselectColor1); if (tabIndex > _tabPane.getSelectedIndex()) { if (tabIndex == _tabPane.getTabCount() - 1) { g.drawRect(x - 1, y, w, h - 1); } else { g.drawRect(x - 1, y, w, h); } } else if (tabIndex < _tabPane.getSelectedIndex()) { g.drawRect(x - 1, y, w, h); } } break; case BOTTOM: if (isSelected) { g.setColor(_selectColor1); g.drawRect(x, y - 1, w, h); } else { g.setColor(_unselectColor1); g.drawRect(x, y - 1, w, h); } break; case TOP: default: if (isSelected) { g.setColor(_selectColor1); g.drawRect(x, y, w, h); } else { g.setColor(_unselectColor1); g.drawRect(x, y, w, h); } } } protected void paintRoundedFlatTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { switch (tabPlacement) { case LEFT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x + 2, y, x + w - 1, y); g.drawLine(x + 2, y + h, x + w - 1, y + h); g.drawLine(x, y + 2, x, y + h - 2); g.setColor(_selectColor2); g.drawLine(x + 1, y + 1, x + 1, y + 1); // g.drawLine(x, y + 1, x, y + 1); g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); // g.drawLine(x + 1, y + h, x + 1, y + h); } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 2, y, x + w - 1, y); if (tabIndex == _tabPane.getTabCount() - 1) { g.drawLine(x + 2, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x, y + 2, x, y + h - 3); } else { g.drawLine(x + 2, y + h, x + w - 1, y + h); g.drawLine(x, y + 2, x, y + h - 2); } g.setColor(_unselectColor2); g.drawLine(x + 1, y + 1, x + 1, y + 1); // g.drawLine(x, y + 1, x, y + 1); if (tabIndex == _tabPane.getTabCount() - 1) { g.drawLine(x, y + h - 2, x, y + h - 2); g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); } else { g.drawLine(x, y + h - 1, x, y + h - 1); g.drawLine(x + 1, y + h, x + 1, y + h); } } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x + 2, y, x + w - 1, y); g.drawLine(x + 2, y + h, x + w - 1, y + h); g.drawLine(x, y + 2, x, y + h - 2); g.setColor(_unselectColor2); g.drawLine(x + 1, y + 1, x + 1, y + 1); // g.drawLine(x, y + 1, x, y + 1); g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); // g.drawLine(x + 1, y + h, x + 1, y + h); } } break; case RIGHT: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x + w - 3, y); g.drawLine(x, y + h, x + w - 3, y + h); g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2); g.setColor(_selectColor2); g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1); // g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1); // g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1); } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y, x + w - 3, y); if (tabIndex == _tabPane.getTabCount() - 1) { g.drawLine(x, y + h - 1, x + w - 3, y + h - 1); g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 3); } else { g.drawLine(x, y + h, x + w - 3, y + h); g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2); } g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1); // g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1); if (tabIndex == _tabPane.getTabCount() - 1) { g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2); // g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1); } else { // g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1); } } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y, x + w - 3, y); g.drawLine(x, y + h, x + w - 3, y + h); g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 2); g.setColor(_unselectColor2); g.drawLine(x + w - 2, y + 1, x + w - 2, y + 1); // g.drawLine(x + w - 1, y + 1, x + w - 1, y + 1); g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1); // g.drawLine(x + w - 2, y + h, x + w - 2, y + h); } } break; case BOTTOM: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x, y + h - 3); g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1); g.drawLine(x + w, y, x + w, y + h - 3); g.setColor(_selectColor2); g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2); // g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); // g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2); } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y, x, y + h - 3); if (tabIndex == _tabPane.getTabCount() - 1) { g.drawLine(x + 2, y + h - 1, x + w - 3, y + h - 1); g.drawLine(x + w - 1, y, x + w - 1, y + h - 3); } else { g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1); g.drawLine(x + w, y, x + w, y + h - 3); } g.setColor(_unselectColor2); g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2); // g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); if (tabIndex == _tabPane.getTabCount() - 1) { // g.drawLine(x + w - 2, y + h - 1, x + w - 2, y + h - 1); g.drawLine(x + w - 2, y + h - 2, x + w - 2, y + h - 2); } else { // g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2); } } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y, x, y + h - 3); g.drawLine(x + 2, y + h - 1, x + w - 2, y + h - 1); g.drawLine(x + w, y, x + w, y + h - 3); g.setColor(_unselectColor2); g.drawLine(x + 1, y + h - 2, x + 1, y + h - 2); // g.drawLine(x + 1, y + h - 1, x + 1, y + h - 1); // g.drawLine(x + w - 1, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x + w - 1, y + h - 2, x + w - 1, y + h - 2); } } break; case TOP: default: if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y + h - 1, x, y + 2); g.drawLine(x + 2, y, x + w - 2, y); g.drawLine(x + w, y + 2, x + w, y + h - 1); g.setColor(_selectColor2); g.drawLine(x, y + 2, x + 2, y); // top-left g.drawLine(x + w - 2, y, x + w, y + 2); // g.drawLine(x + w, y + 1, x + w, y + 1); } else { if (tabIndex > _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y + h - 1, x, y + 2); if (tabIndex == _tabPane.getTabCount() - 1) { g.drawLine(x + 2, y, x + w - 3, y); g.drawLine(x + w - 1, y + 2, x + w - 1, y + h - 1); } else { g.drawLine(x + 2, y, x + w - 2, y); g.drawLine(x + w, y + 2, x + w, y + h - 1); } g.setColor(_unselectColor2); g.drawLine(x, y + 2, x + 2, y); // top-left if (tabIndex == _tabPane.getTabCount() - 1) { g.drawLine(x + w - 3, y, x + w - 1, y + 2); } else { g.drawLine(x + w - 2, y, x + w, y + 2); } } else if (tabIndex < _tabPane.getSelectedIndex()) { g.setColor(_unselectColor1); g.drawLine(x, y + h - 1, x, y + 2); g.drawLine(x + 2, y, x + w - 2, y); g.drawLine(x + w, y + 2, x + w, y + h - 1); g.setColor(_unselectColor2); g.drawLine(x, y + 2, x + 2, y); g.drawLine(x + w - 2, y, x + w, y + 2); } } } } protected void paintBoxTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); if (isSelected) { g.setColor(_selectColor1); g.drawLine(x, y, x + w - 2, y);// top g.drawLine(x, y, x, y + h - 2);// left g.setColor(_selectColor2); g.drawLine(x + w - 1, y, x + w - 1, y + h - 1);// right g.drawLine(x, y + h - 1, x + w - 1, y + h - 1);// bottom } else { if (tabIndex != _tabPane.getSelectedIndex() - 1) { switch (tabPlacement) { case LEFT: case RIGHT: g.setColor(_unselectColor1); g.drawLine(x + 2, y + h, x + w - 2, y + h);// bottom g.setColor(_unselectColor2); g.drawLine(x + 2, y + h + 1, x + w - 2, y + h + 1);// bottom break; case BOTTOM: case TOP: default: if (leftToRight) { g.setColor(_unselectColor1); g.drawLine(x + w, y + 2, x + w, y + h - 2);// right g.setColor(_unselectColor2); g.drawLine(x + w + 1, y + 2, x + w + 1, y + h - 2);// right } else { g.setColor(_unselectColor1); g.drawLine(x, y + 2, x, y + h - 2);// right g.setColor(_unselectColor2); g.drawLine(x + 1, y + 2, x + 1, y + h - 2);// right } } } } } protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { if (!PAINT_TAB_BACKGROUND) { return; } switch (getTabShape()) { case JideTabbedPane.SHAPE_BOX: paintButtonTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_EXCEL: paintExcelTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_WINDOWS: paintDefaultTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_WINDOWS_SELECTED: if (isSelected) { paintDefaultTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected); } break; case JideTabbedPane.SHAPE_VSNET: case JideTabbedPane.SHAPE_ROUNDED_VSNET: paintVsnetTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_FLAT: case JideTabbedPane.SHAPE_ROUNDED_FLAT: paintFlatTabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected); break; case JideTabbedPane.SHAPE_OFFICE2003: default: paintOffice2003TabBackground(g, tabPlacement, tabIndex, x, y, w, h, isSelected); } } protected void paintOffice2003TabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); switch (tabPlacement) { case LEFT: if (!isSelected) {// the tab is not selected if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x + w, x + 2, x, x, x + 3, x + w}; int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else {// tabIndex != 0 int xp[] = {x + w, x + 4, x + 2, x, x, x + 3, x + w}; int yp[] = {y, y, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x + w, x + 2, x, x, x + 3, x + w}; int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } break; case RIGHT: if (!isSelected) {// the tab is not selected if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x}; int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else {// tabIndex != 0 int xp[] = {x, x + w - 4, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x}; int yp[] = {y, y, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x}; int yp[] = {y - w + 2 + 2, y + 2, y + 5, y + h - 5, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } break; case BOTTOM: if (!isSelected) {// the tab is not selected if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x - h + 5, x, x + 4, x + w - 3, x + w - 1, x + w - 1}; int yp[] = {y, y + h - 5, y + h - 1, y + h - 1, y + h - 5, y}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else {// tabIndex != 0 int xp[] = {x, x, x + 4, x + w - 3, x + w - 1, x + w - 1}; int yp[] = {y, y + h - 5, y + h - 1, y + h - 1, y + h - 5, y}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x - h + 5, x, x + 4, x + w - 3, x + w - 1, x + w - 1}; int yp[] = {y, y + h - 5, y + h - 1, y + h - 1, y + h - 5, y}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } break; case TOP: default: if (!isSelected) {// the tab is not selected if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x - h + 5, x, x + 4, x + w - 3, x + w - 1, x + w - 1}; int yp[] = {y + h, y + 3, y + 1, y + 1, y + 3, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else {// tabIndex != 0 int xp[] = {x, x, x + 4, x + w - 3, x + w - 1, x + w - 1}; int yp[] = {y + h, y + 3, y + 1, y + 1, y + 3, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x - h + 5, x, x + 4, x + w - 3, x + w - 1, x + w - 1}; int yp[] = {y + h, y + 3, y + 1, y + 1, y + 3, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } } protected void paintExcelTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); switch (tabPlacement) { case LEFT: if (!isSelected) { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x + w, x, x, x + w}; int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x + w, x + 9, x, x, x + w}; int yp[] = {y + 8, y + 2, y + 6, y + h - 5, y + h + 6}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x + w, x, x, x + w}; int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } break; case RIGHT: if (!isSelected) { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x, x + w - 1, x + w - 1, x}; int yp[] = {y - 5, y + 5, y + h - 5, y + h + 6}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x, x + w - 10, x + w - 1, x + w - 1, x}; int yp[] = {y + 8, y + 2, y + 6, y + h - 5, y + h + 6}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x, x + w - 1, x + w - 1, x}; int yp[] = {y - 5, y + 5, y + h - 4, y + h + 6}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } break; case BOTTOM: if (!isSelected) { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x - 5, x + 5, x + w - 5, x + w + 5}; int yp[] = {y, y + h - 1, y + h - 1, y}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x + 7, x + 1, x + 5, x + w - 5, x + w + 5}; int yp[] = {y, y + h - 10, y + h - 1, y + h - 1, y}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x - 5, x + 5, x + w - 5, x + w + 5}; int yp[] = {y, y + h - 1, y + h - 1, y}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } break; case TOP: default: if (!isSelected) { if ((leftToRight && tabIndex == 0) || (!leftToRight && tabIndex == _tabPane.getTabCount() - 1)) { int xp[] = {x - 6, x + 5, x + w - 5, x + w + 5}; int yp[] = {y + h, y, y, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x + 7, x + 1, x + 6, x + w - 5, x + w + 5}; int yp[] = {y + h, y + 9, y, y, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } else { int xp[] = {x - 6, x + 5, x + w - 5, x + w + 5}; int yp[] = {y + h, y, y, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } } protected void paintDefaultTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { switch (tabPlacement) { case LEFT: if (isSelected) { x = x + 1; int xp[] = {x + w, x, x - 2, x - 2, x + w}; int yp[] = {y - 1, y - 1, y + 1, y + h + 2, y + h + 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { if (tabIndex < _tabPane.getSelectedIndex()) { y = y + 1; int xp[] = {x + w, x + 2, x, x, x + w}; int yp[] = {y + 1, y + 1, y + 3, y + h - 1, y + h - 1}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x + w, x + 2, x, x, x + w}; int yp[] = {y + 1, y + 1, y + 3, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } break; case RIGHT: if (isSelected) { int xp[] = {x, x + w - 1, x + w, x + w, x}; int yp[] = {y - 1, y - 1, y + 1, y + h + 2, y + h + 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { if (tabIndex < _tabPane.getSelectedIndex()) { y = y + 1; int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x}; int yp[] = {y + 1, y + 1, y + 3, y + h - 1, y + h - 1}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x, x + w - 2, x + w - 1, x + w - 1, x}; int yp[] = {y + 1, y + 1, y + 3, y + h - 2, y + h - 2}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } break; case BOTTOM: if (isSelected) { int xp[] = {x, x, x + 2, x + w + 2, x + w + 2}; int yp[] = {y + h, y, y - 2, y - 2, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x + 1, x + 1, x + 1, x + w - 1, x + w - 1}; int yp[] = {y + h - 1, y + 2, y, y, y + h - 1}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } break; case TOP: default: if (isSelected) { int xp[] = {x, x, x + 2, x + w + 2, x + w + 2}; int yp[] = {y + h + 1, y, y - 2, y - 2, y + h + 1}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } else { int xp[] = {x + 1, x + 1, x + 3, x + w - 1, x + w - 1}; int yp[] = {y + h, y + 2, y, y, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } } } protected void paintTabBackgroundMouseOver(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected, Color backgroundUnselectedColorStart, Color backgroundUnselectedColorEnd) { Graphics2D g2d = (Graphics2D) g; Polygon polygon = null; switch (tabPlacement) { case LEFT: if (tabIndex < _tabPane.getSelectedIndex()) { int xp[] = {x + w, x + 2, x, x, x + 2, x + w}; int yp[] = {y + 2, y + 2, y + 4, y + h - 1, y + h, y + h}; int np = yp.length; polygon = new Polygon(xp, yp, np); } else {// tabIndex > _tabPane.getSelectedIndex() int xp[] = {x + w, x + 2, x, x, x + 2, x + w}; int yp[] = {y + 1, y + 1, y + 3, y + h - 3, y + h - 2, y + h - 2}; int np = yp.length; polygon = new Polygon(xp, yp, np); } JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorStart, backgroundUnselectedColorEnd, false); break; case RIGHT: if (tabIndex < _tabPane.getSelectedIndex()) { int xp[] = {x, x + w - 3, x + w - 1, x + w - 1, x + w - 3, x}; int yp[] = {y + 2, y + 2, y + 4, y + h - 1, y + h, y + h}; int np = yp.length; polygon = new Polygon(xp, yp, np); } else { int xp[] = {x, x + w - 2, x + w - 1, x + w - 1, x + w - 3, x}; int yp[] = {y + 1, y + 1, y + 3, y + h - 3, y + h - 2, y + h - 2}; int np = yp.length; polygon = new Polygon(xp, yp, np); } JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorEnd, backgroundUnselectedColorStart, false); break; case BOTTOM: int xp[] = {x + 1, x + 1, x + 1, x + w - 1, x + w - 1}; int yp[] = {y + h - 2, y + 2, y, y, y + h - 2}; int np = yp.length; polygon = new Polygon(xp, yp, np); JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorEnd, backgroundUnselectedColorStart, true); break; case TOP: default: int xp1[] = {x + 1, x + 1, x + 3, x + w - 1, x + w - 1}; int yp1[] = {y + h, y + 2, y, y, y + h}; int np1 = yp1.length; polygon = new Polygon(xp1, yp1, np1); JideSwingUtilities.fillGradient(g2d, polygon, backgroundUnselectedColorStart, backgroundUnselectedColorEnd, true); } } protected void paintVsnetTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { int xp[]; int yp[]; switch (tabPlacement) { case LEFT: xp = new int[]{x + 1, x + 1, x + w, x + w}; yp = new int[]{y + h - 1, y + 1, y + 1, y + h - 1}; break; case RIGHT: xp = new int[]{x, x, x + w - 1, x + w - 1}; yp = new int[]{y + h - 1, y + 1, y + 1, y + h - 1}; break; case BOTTOM: xp = new int[]{x + 1, x + 1, x + w - 1, x + w - 1}; yp = new int[]{y + h - 1, y, y, y + h - 1}; break; case TOP: default: xp = new int[]{x + 1, x + 1, x + w - 1, x + w - 1}; yp = new int[]{y + h, y + 1, y + 1, y + h}; break; } int np = yp.length; tabRegion = new Polygon(xp, yp, np); } protected void paintFlatTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { switch (tabPlacement) { case LEFT: int xp1[] = {x + 1, x + 1, x + w, x + w}; int yp1[] = {y + h, y + 1, y + 1, y + h}; int np1 = yp1.length; tabRegion = new Polygon(xp1, yp1, np1); break; case RIGHT: int xp2[] = {x, x, x + w - 1, x + w - 1}; int yp2[] = {y + h, y + 1, y + 1, y + h}; int np2 = yp2.length; tabRegion = new Polygon(xp2, yp2, np2); break; case BOTTOM: int xp3[] = {x + 1, x + 1, x + w, x + w}; int yp3[] = {y + h - 1, y, y, y + h - 1}; int np3 = yp3.length; tabRegion = new Polygon(xp3, yp3, np3); break; case TOP: default: int xp4[] = {x, x + 1, x + w, x + w}; int yp4[] = {y + h, y + 1, y + 1, y + h}; int np4 = yp4.length; tabRegion = new Polygon(xp4, yp4, np4); } } protected void paintButtonTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { int xp[] = {x, x, x + w, x + w}; int yp[] = {y + h, y, y, y + h}; int np = yp.length; tabRegion = new Polygon(xp, yp, np); } protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) { int width = _tabPane.getWidth(); int height = _tabPane.getHeight(); Insets insets = _tabPane.getInsets(); int x = insets.left; int y = insets.top; int w = width - insets.right - insets.left; int h = height - insets.top - insets.bottom; int temp = -1; switch (tabPlacement) { case LEFT: x += calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth); if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().width > calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth)) { x = insets.left + _tabLeadingComponent.getSize().width; temp = _tabLeadingComponent.getSize().width; } } if (isTabTrailingComponentVisible()) { if (_maxTabWidth < _tabTrailingComponent.getSize().width && temp < _tabTrailingComponent.getSize().width) { x = insets.left + _tabTrailingComponent.getSize().width; } } w -= (x - insets.left); break; case RIGHT: w -= calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth); break; case BOTTOM: h -= calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); break; case TOP: default: y += calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().height > calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight)) { y = insets.top + _tabLeadingComponent.getSize().height; temp = _tabLeadingComponent.getSize().height; } } if (isTabTrailingComponentVisible()) { if (_maxTabHeight < _tabTrailingComponent.getSize().height && temp < _tabTrailingComponent.getSize().height) { y = insets.top + _tabTrailingComponent.getSize().height; } } h -= (y - insets.top); } if (getTabShape() != JideTabbedPane.SHAPE_BOX) { // Fill region behind content area paintContentBorder(g, x, y, w, h); switch (tabPlacement) { case LEFT: paintContentBorderLeftEdge(g, tabPlacement, selectedIndex, x, y, w, h); break; case RIGHT: paintContentBorderRightEdge(g, tabPlacement, selectedIndex, x, y, w, h); break; case BOTTOM: paintContentBorderBottomEdge(g, tabPlacement, selectedIndex, x, y, w, h); break; case TOP: default: paintContentBorderTopEdge(g, tabPlacement, selectedIndex, x, y, w, h); break; } } } protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { } protected void paintContentBorderRightEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { } protected void paintContentBorder(Graphics g, int x, int y, int w, int h) { if (!PAINT_CONTENT_BORDER) { return; } if (_tabPane.isOpaque()) { g.setColor(_tabBackground); g.fillRect(x, y, w, h); } } protected Color getBorderEdgeColor() { if ("true".equals(SecurityUtils.getProperty("shadingtheme", "false"))) { return _shadow; } else { return _lightHighlight; } } protected void paintContentBorderTopEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { if (!PAINT_CONTENT_BORDER_EDGE) { return; } if (selectedIndex < 0) { return; } Rectangle selRect = getTabBounds(selectedIndex, _calcRect); g.setColor(getBorderEdgeColor()); // Draw unbroken line if tabs are not on TOP, OR // selected tab is not in run adjacent to content, OR // selected tab is not visible (SCROLL_TAB_LAYOUT) // if (tabPlacement != TOP || selectedIndex < 0 || /*(selRect.y + selRect.height + 1 < y) ||*/ (selRect.x < x || selRect.x > x + w)) { g.drawLine(x, y, x + w - 1, y); } else { // Break line to show visual connection to selected tab g.drawLine(x, y, selRect.x, y); if (!getBorderEdgeColor().equals(_lightHighlight)) { if (selRect.x + selRect.width < x + w - 2) { g.drawLine(selRect.x + selRect.width - 1, y, selRect.x + selRect.width - 1, y); g.drawLine(selRect.x + selRect.width, y, x + w - 1, y); } else { g.drawLine(x + w - 2, y, x + w - 1, y); } } else { if (selRect.x + selRect.width < x + w - 2) { g.setColor(_darkShadow); g.drawLine(selRect.x + selRect.width - 1, y, selRect.x + selRect.width - 1, y); g.setColor(_lightHighlight); g.drawLine(selRect.x + selRect.width, y, x + w - 1, y); } else { g.setColor(_selectedColor == null ? _tabPane.getBackground() : _selectedColor); g.drawLine(x + w - 2, y, x + w - 1, y); } } } } protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { if (!PAINT_CONTENT_BORDER_EDGE) { return; } if (selectedIndex < 0) { return; } Rectangle selRect = getTabBounds(selectedIndex, _calcRect); // Draw unbroken line if tabs are not on BOTTOM, OR // selected tab is not in run adjacent to content, OR // selected tab is not visible (SCROLL_TAB_LAYOUT) // if (tabPlacement != BOTTOM || selectedIndex < 0 || /*(selRect.y - 1 > h) ||*/ (selRect.x < x || selRect.x > x + w)) { g.setColor(getBorderEdgeColor()); g.drawLine(x, y + h - 1, x + w - 2, y + h - 1); } else { if (!getBorderEdgeColor().equals(_lightHighlight)) { g.setColor(getBorderEdgeColor()); g.drawLine(x, y + h - 1, selRect.x - 1, y + h - 1); g.drawLine(selRect.x, y + h - 1, selRect.x, y + h - 1); if (selRect.x + selRect.width < x + w - 2) { g.drawLine(selRect.x + selRect.width - 1, y + h - 1, x + w - 2, y + h - 1); // dark line to the end } } else { // Break line to show visual connection to selected tab g.setColor(_darkShadow); // dark line at the beginning g.drawLine(x, y + h - 1, selRect.x - 1, y + h - 1); g.setColor(_lightHighlight); // light line to meet with tab // border g.drawLine(selRect.x, y + h - 1, selRect.x, y + h - 1); if (selRect.x + selRect.width < x + w - 2) { g.setColor(_darkShadow); g.drawLine(selRect.x + selRect.width - 1, y + h - 1, x + w - 2, y + h - 1); // dark line to the end } } } } protected void ensureCurrentLayout() { // this line cause layout when repaint. It looks like tabbed pane is always not valid. // but without this line, it causes the viewport sometimes not resized correctly. // such as the bug report at http://www.jidesoft.com/forum/viewtopic.php?p=25050#25050 if (!_tabPane.isValid()) { _tabPane.validate(); } /* If tabPane doesn't have a peer yet, the validate() call will * silently fail. We handle that by forcing a layout if tabPane * is still invalid. See bug 4237677. */ if (!_tabPane.isValid()) { TabbedPaneLayout layout = (TabbedPaneLayout) _tabPane.getLayout(); layout.calculateLayoutInfo(); } if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab()) { for (int i = 0; i < _closeButtons.length; i++) { if (_tabPane.isShowCloseButtonOnSelectedTab()) { if (i != _tabPane.getSelectedIndex()) { _closeButtons[i].setBounds(0, 0, 0, 0); continue; } } else { if (i >= _rects.length) { _closeButtons[i].setBounds(0, 0, 0, 0); continue; } } if (!_tabPane.isTabClosableAt(i)) { _closeButtons[i].setBounds(0, 0, 0, 0); continue; } Dimension size = _closeButtons[i].getPreferredSize(); Rectangle bounds = null; if (_closeButtonAlignment == SwingConstants.TRAILING) { if (_tabPane.getTabPlacement() == JideTabbedPane.TOP || _tabPane.getTabPlacement() == JideTabbedPane.BOTTOM) { bounds = new Rectangle(_rects[i].x + _rects[i].width - size.width - _closeButtonRightMargin, _rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height); bounds.x -= getTabGap(); } else /*if (_tabPane.getTabPlacement() == JideTabbedPane.LEFT || _tabPane.getTabPlacement() == JideTabbedPane.RIGHT)*/ { bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2, _rects[i].y + _rects[i].height - size.height - _closeButtonRightMargin, size.width, size.height); bounds.y -= getTabGap(); } } else { if (_tabPane.getTabPlacement() == JideTabbedPane.TOP || _tabPane.getTabPlacement() == JideTabbedPane.BOTTOM) { bounds = new Rectangle(_rects[i].x + _closeButtonLeftMargin, _rects[i].y + (_rects[i].height - size.height) / 2, size.width, size.height); } else if (_tabPane.getTabPlacement() == JideTabbedPane.LEFT) { bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2, _rects[i].y + _closeButtonLeftMargin, size.width, size.height); } else /*if (_tabPane.getTabPlacement() == JideTabbedPane.RIGHT)*/ { bounds = new Rectangle(_rects[i].x + (_rects[i].width - size.width) / 2 - 2, _rects[i].y + _closeButtonLeftMargin, size.width, size.height); } } _closeButtons[i].setIndex(i); if (!bounds.equals(_closeButtons[i].getBounds())) { _closeButtons[i].setBounds(bounds); } if (_tabPane.getSelectedIndex() == i) { _closeButtons[i].setBackground(_selectedColor == null ? _tabPane.getBackgroundAt(i) : _selectedColor); } else { _closeButtons[i].setBackground(_tabPane.getBackgroundAt(i)); } } } } // TabbedPaneUI methods /** * Returns the bounds of the specified tab index. The bounds are with respect to the * JTabbedPane's coordinate space. */ @Override public Rectangle getTabBounds(JTabbedPane pane, int i) { ensureCurrentLayout(); Rectangle tabRect = new Rectangle(); return getTabBounds(i, tabRect); } @Override public int getTabRunCount(JTabbedPane pane) { ensureCurrentLayout(); return _runCount; } /** * Returns the tab index which intersects the specified point in the JTabbedPane's coordinate * space. */ @Override public int tabForCoordinate(JTabbedPane pane, int x, int y) { ensureCurrentLayout(); Point p = new Point(x, y); if (scrollableTabLayoutEnabled()) { translatePointToTabPanel(x, y, p); } int tabCount = _tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (_rects[i].contains(p.x, p.y)) { return i; } } return -1; } /** * Returns the bounds of the specified tab in the coordinate space of the JTabbedPane component. * This is required because the tab rects are by default defined in the coordinate space of the * component where they are rendered, which could be the JTabbedPane (for WRAP_TAB_LAYOUT) or a * ScrollableTabPanel (SCROLL_TAB_LAYOUT). This method should be used whenever the tab rectangle * must be relative to the JTabbedPane itself and the result should be placed in a designated * Rectangle object (rather than instantiating and returning a new Rectangle each time). The tab * index parameter must be a valid tabbed pane tab index (0 to tab count - 1, inclusive). The * destination rectangle parameter must be a valid <code>Rectangle</code> instance. The handling * of invalid parameters is unspecified. * * @param tabIndex the index of the tab * @param dest the rectangle where the result should be placed * * @return the resulting rectangle */ protected Rectangle getTabBounds(int tabIndex, Rectangle dest) { if (_rects.length == 0) { return null; } // to make the index is in bound. if (tabIndex > _rects.length - 1) { tabIndex = _rects.length - 1; } if (tabIndex < 0) { tabIndex = 0; } dest.width = _rects[tabIndex].width; dest.height = _rects[tabIndex].height; if (scrollableTabLayoutEnabled()) { // SCROLL_TAB_LAYOUT // Need to translate coordinates based on viewport location & // view position Point vpp = _tabScroller.viewport.getLocation(); Point viewp = _tabScroller.viewport.getViewPosition(); dest.x = _rects[tabIndex].x + vpp.x - viewp.x; dest.y = _rects[tabIndex].y + vpp.y - viewp.y; } else { // WRAP_TAB_LAYOUT dest.x = _rects[tabIndex].x; dest.y = _rects[tabIndex].y; } return dest; } /** * Returns the tab index which intersects the specified point in the coordinate space of the * component where the tabs are actually rendered, which could be the JTabbedPane (for * WRAP_TAB_LAYOUT) or a ScrollableTabPanel (SCROLL_TAB_LAYOUT). */ public int getTabAtLocation(int x, int y) { ensureCurrentLayout(); int tabCount = _tabPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (_rects[i].contains(x, y)) { return i; } } return -1; } /** * Returns the index of the tab closest to the passed in location, note that the returned tab * may not contain the location x,y. */ private int getClosestTab(int x, int y) { int min = 0; int tabCount = Math.min(_rects.length, _tabPane.getTabCount()); int max = tabCount; int tabPlacement = _tabPane.getTabPlacement(); boolean useX = (tabPlacement == TOP || tabPlacement == BOTTOM); int want = (useX) ? x : y; while (min != max) { int current = (max + min) >> 1; int minLoc; int maxLoc; if (useX) { minLoc = _rects[current].x; maxLoc = minLoc + _rects[current].width; } else { minLoc = _rects[current].y; maxLoc = minLoc + _rects[current].height; } if (want < minLoc) { max = current; if (min == max) { return Math.max(0, current - 1); } } else if (want >= maxLoc) { min = current; if (max - min <= 1) { return Math.max(current + 1, tabCount - 1); } } else { return current; } } return min; } /** * Returns a point which is translated from the specified point in the JTabbedPane's coordinate * space to the coordinate space of the ScrollableTabPanel. This is used for SCROLL_TAB_LAYOUT * ONLY. */ private Point translatePointToTabPanel(int srcx, int srcy, Point dest) { Point vpp = _tabScroller.viewport.getLocation(); Point viewp = _tabScroller.viewport.getViewPosition(); dest.x = srcx - vpp.x + viewp.x; dest.y = srcy - vpp.y + viewp.y; return dest; } // VsnetJideTabbedPaneUI methods protected Component getVisibleComponent() { return visibleComponent; } protected void setVisibleComponent(Component component) { if (visibleComponent != null && visibleComponent != component && visibleComponent.getParent() == _tabPane) { visibleComponent.setVisible(false); } if (component != null && !component.isVisible()) { component.setVisible(true); } visibleComponent = component; } protected void assureRectsCreated(int tabCount) { int rectArrayLen = _rects.length; if (tabCount != rectArrayLen) { Rectangle[] tempRectArray = new Rectangle[tabCount]; System.arraycopy(_rects, 0, tempRectArray, 0, Math.min(rectArrayLen, tabCount)); _rects = tempRectArray; for (int rectIndex = rectArrayLen; rectIndex < tabCount; rectIndex++) { _rects[rectIndex] = new Rectangle(); } } } protected void expandTabRunsArray() { int rectLen = _tabRuns.length; int[] newArray = new int[rectLen + 10]; System.arraycopy(_tabRuns, 0, newArray, 0, _runCount); _tabRuns = newArray; } protected int getRunForTab(int tabCount, int tabIndex) { for (int i = 0; i < _runCount; i++) { int first = _tabRuns[i]; int last = lastTabInRun(tabCount, i); if (tabIndex >= first && tabIndex <= last) { return i; } } return 0; } protected int lastTabInRun(int tabCount, int run) { if (_runCount == 1) { return tabCount - 1; } int nextRun = (run == _runCount - 1 ? 0 : run + 1); if (_tabRuns[nextRun] == 0) { return tabCount - 1; } return _tabRuns[nextRun] - 1; } protected int getTabRunOverlay(int tabPlacement) { return _tabRunOverlay; } protected int getTabRunIndent(int tabPlacement, int run) { return 0; } protected boolean shouldPadTabRun(int tabPlacement, int run) { return _runCount > 1; } protected boolean shouldRotateTabRuns(int tabPlacement) { return true; } /** * Returns the text View object required to render stylized text (HTML) for the specified tab or * null if no specialized text rendering is needed for this tab. This is provided to support * html rendering inside tabs. * * @param tabIndex the index of the tab * * @return the text view to render the tab's text or null if no specialized rendering is * required */ protected View getTextViewForTab(int tabIndex) { if (htmlViews != null && tabIndex < htmlViews.size()) { return (View) htmlViews.elementAt(tabIndex); } return null; } protected int calculateTabHeight(int tabPlacement, int tabIndex, FontMetrics metrics) { int height = 0; if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) { View v = getTextViewForTab(tabIndex); if (v != null) { // html height += (int) v.getPreferredSpan(View.Y_AXIS); } else { // plain text height += metrics.getHeight(); } Icon icon = _tabPane.getIconForTab(tabIndex); Insets tabInsets = getTabInsets(tabPlacement, tabIndex); if (icon != null) { height = Math.max(height, icon.getIconHeight()); } height += tabInsets.top + tabInsets.bottom + 2; } else { Icon icon = _tabPane.getIconForTab(tabIndex); Insets tabInsets = getTabInsets(tabPlacement, tabIndex); height = tabInsets.top + tabInsets.bottom + 3; if (icon != null) { height += icon.getIconHeight() + _textIconGap; } View v = getTextViewForTab(tabIndex); if (v != null) { // html height += (int) v.getPreferredSpan(View.X_AXIS); } else { // plain text String title = _tabPane.getDisplayTitleAt(tabIndex); height += SwingUtilities.computeStringWidth(metrics, title); } // for gripper if (_tabPane.isShowGripper()) { height += _gripperHeight; } if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)) { if (_tabPane.isShowCloseButtonOnSelectedTab()) { if (_tabPane.getSelectedIndex() == tabIndex) { height += _closeButtons[tabIndex].getPreferredSize().height + _closeButtonRightMargin + _closeButtonLeftMargin; } } else { height += _closeButtons[tabIndex].getPreferredSize().height + _closeButtonRightMargin + _closeButtonLeftMargin; } } // height += _tabRectPadding; } return height; } protected int calculateMaxTabHeight(int tabPlacement) { int tabCount = _tabPane.getTabCount(); int result = 0; for (int i = 0; i < tabCount; i++) { FontMetrics metrics = getFontMetrics(i); result = Math.max(calculateTabHeight(tabPlacement, i, metrics), result); } return result; } protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { int width = 0; if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) { Icon icon = _tabPane.getIconForTab(tabIndex); Insets tabInsets = getTabInsets(tabPlacement, tabIndex); width = tabInsets.left + tabInsets.right + 3 + getTabGap(); if (icon != null) { width += icon.getIconWidth() + _textIconGap; } View v = getTextViewForTab(tabIndex); if (v != null) { // html width += (int) v.getPreferredSpan(View.X_AXIS); } else { // plain text String title = _tabPane.getDisplayTitleAt(tabIndex); width += SwingUtilities.computeStringWidth(metrics, title); } // for gripper if (_tabPane.isShowGripper()) { width += _gripperWidth; } if (scrollableTabLayoutEnabled() && isShowCloseButton() && isShowCloseButtonOnTab() && _tabPane.isTabClosableAt(tabIndex)) { if (_tabPane.isShowCloseButtonOnSelectedTab()) { if (_tabPane.getSelectedIndex() == tabIndex) { width += _closeButtons[tabIndex].getPreferredSize().width + _closeButtonRightMargin + _closeButtonLeftMargin; } } else { width += _closeButtons[tabIndex].getPreferredSize().width + _closeButtonRightMargin + _closeButtonLeftMargin; } } // width += _tabRectPadding; } else { View v = getTextViewForTab(tabIndex); if (v != null) { // html width += (int) v.getPreferredSpan(View.Y_AXIS); } else { // plain text width += metrics.getHeight(); } Icon icon = _tabPane.getIconForTab(tabIndex); Insets tabInsets = getTabInsets(tabPlacement, tabIndex); if (icon != null) { width = Math.max(width, icon.getIconWidth()); } width += tabInsets.left + tabInsets.right + 2; } return width; } protected int calculateMaxTabWidth(int tabPlacement) { int tabCount = _tabPane.getTabCount(); int result = 0; for (int i = 0; i < tabCount; i++) { FontMetrics metrics = getFontMetrics(i); result = Math.max(calculateTabWidth(tabPlacement, i, metrics), result); } return result; } protected int calculateTabAreaHeight(int tabPlacement, int horizRunCount, int maxTabHeight) { if (!_tabPane.isTabShown()) { return 0; } Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int tabRunOverlay = getTabRunOverlay(tabPlacement); return (horizRunCount > 0 ? horizRunCount * (maxTabHeight - tabRunOverlay) + tabRunOverlay + tabAreaInsets.top + tabAreaInsets.bottom : 0); } protected int calculateTabAreaWidth(int tabPlacement, int vertRunCount, int maxTabWidth) { if (!_tabPane.isTabShown()) { return 0; } Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int tabRunOverlay = getTabRunOverlay(tabPlacement); return (vertRunCount > 0 ? vertRunCount * (maxTabWidth - tabRunOverlay) + tabRunOverlay + tabAreaInsets.left + tabAreaInsets.right : 0); } protected Insets getTabInsets(int tabPlacement, int tabIndex) { rotateInsets(_tabInsets, _currentTabInsets, tabPlacement); return _currentTabInsets; } protected Insets getSelectedTabPadInsets(int tabPlacement) { rotateInsets(_selectedTabPadInsets, _currentPadInsets, tabPlacement); return _currentPadInsets; } protected Insets getTabAreaInsets(int tabPlacement) { rotateInsets(_tabAreaInsets, _currentTabAreaInsets, tabPlacement); return _currentTabAreaInsets; } protected Insets getContentBorderInsets(int tabPlacement) { rotateInsets(_tabPane.getContentBorderInsets(), _currentContentBorderInsets, tabPlacement); if (_ignoreContentBorderInsetsIfNoTabs && !_tabPane.isTabShown()) return new Insets(0, 0, 0, 0); else return _currentContentBorderInsets; } protected FontMetrics getFontMetrics(int tab) { Font font = null; int selectedIndex = _tabPane.getSelectedIndex(); if (selectedIndex == tab && _tabPane.getSelectedTabFont() != null) { font = _tabPane.getSelectedTabFont(); } else { font = _tabPane.getFont(); } if (selectedIndex == tab && _tabPane.isBoldActiveTab() && font.getStyle() != Font.BOLD) { font = font.deriveFont(Font.BOLD); } return _tabPane.getFontMetrics(font); } // Tab Navigation methods protected void navigateSelectedTab(int direction) { int tabPlacement = _tabPane.getTabPlacement(); int current = _tabPane.getSelectedIndex(); int tabCount = _tabPane.getTabCount(); boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); // If we have no tabs then don't navigate. if (tabCount <= 0) { return; } int offset; switch (tabPlacement) { case NEXT: selectNextTab(current); break; case PREVIOUS: selectPreviousTab(current); break; case LEFT: case RIGHT: switch (direction) { case NORTH: selectPreviousTabInRun(current); break; case SOUTH: selectNextTabInRun(current); break; case WEST: offset = getTabRunOffset(tabPlacement, tabCount, current, false); selectAdjacentRunTab(tabPlacement, current, offset); break; case EAST: offset = getTabRunOffset(tabPlacement, tabCount, current, true); selectAdjacentRunTab(tabPlacement, current, offset); break; default: } break; case BOTTOM: case TOP: default: switch (direction) { case NORTH: offset = getTabRunOffset(tabPlacement, tabCount, current, false); selectAdjacentRunTab(tabPlacement, current, offset); break; case SOUTH: offset = getTabRunOffset(tabPlacement, tabCount, current, true); selectAdjacentRunTab(tabPlacement, current, offset); break; case EAST: if (leftToRight) { selectNextTabInRun(current); } else { selectPreviousTabInRun(current); } break; case WEST: if (leftToRight) { selectPreviousTabInRun(current); } else { selectNextTabInRun(current); } break; default: } } } protected void selectNextTabInRun(int current) { int tabCount = _tabPane.getTabCount(); int tabIndex = getNextTabIndexInRun(tabCount, current); while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) { tabIndex = getNextTabIndexInRun(tabCount, tabIndex); } _tabPane.setSelectedIndex(tabIndex); } protected void selectPreviousTabInRun(int current) { int tabCount = _tabPane.getTabCount(); int tabIndex = getPreviousTabIndexInRun(tabCount, current); while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) { tabIndex = getPreviousTabIndexInRun(tabCount, tabIndex); } _tabPane.setSelectedIndex(tabIndex); } protected void selectNextTab(int current) { int tabIndex = getNextTabIndex(current); while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) { tabIndex = getNextTabIndex(tabIndex); } _tabPane.setSelectedIndex(tabIndex); } protected void selectPreviousTab(int current) { int tabIndex = getPreviousTabIndex(current); while (tabIndex != current && !_tabPane.isEnabledAt(tabIndex)) { tabIndex = getPreviousTabIndex(tabIndex); } _tabPane.setSelectedIndex(tabIndex); } protected void selectAdjacentRunTab(int tabPlacement, int tabIndex, int offset) { if (_runCount < 2) { return; } int newIndex; Rectangle r = _rects[tabIndex]; switch (tabPlacement) { case LEFT: case RIGHT: newIndex = getTabAtLocation(r.x + (r.width >> 1) + offset, r.y + (r.height >> 1)); break; case BOTTOM: case TOP: default: newIndex = getTabAtLocation(r.x + (r.width >> 1), r.y + (r.height >> 1) + offset); } if (newIndex != -1) { while (!_tabPane.isEnabledAt(newIndex) && newIndex != tabIndex) { newIndex = getNextTabIndex(newIndex); } _tabPane.setSelectedIndex(newIndex); } } protected int getTabRunOffset(int tabPlacement, int tabCount, int tabIndex, boolean forward) { int run = getRunForTab(tabCount, tabIndex); int offset; switch (tabPlacement) { case LEFT: { if (run == 0) { offset = (forward ? -(calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth) : -_maxTabWidth); } else if (run == _runCount - 1) { offset = (forward ? _maxTabWidth : calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth); } else { offset = (forward ? _maxTabWidth : -_maxTabWidth); } break; } case RIGHT: { if (run == 0) { offset = (forward ? _maxTabWidth : calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth); } else if (run == _runCount - 1) { offset = (forward ? -(calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth) - _maxTabWidth) : -_maxTabWidth); } else { offset = (forward ? _maxTabWidth : -_maxTabWidth); } break; } case BOTTOM: { if (run == 0) { offset = (forward ? _maxTabHeight : calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight); } else if (run == _runCount - 1) { offset = (forward ? -(calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight) : -_maxTabHeight); } else { offset = (forward ? _maxTabHeight : -_maxTabHeight); } break; } case TOP: default: { if (run == 0) { offset = (forward ? -(calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight) : -_maxTabHeight); } else if (run == _runCount - 1) { offset = (forward ? _maxTabHeight : calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight) - _maxTabHeight); } else { offset = (forward ? _maxTabHeight : -_maxTabHeight); } } } return offset; } protected int getPreviousTabIndex(int base) { int tabIndex = (base - 1 >= 0 ? base - 1 : _tabPane.getTabCount() - 1); return (tabIndex >= 0 ? tabIndex : 0); } protected int getNextTabIndex(int base) { return (base + 1) % _tabPane.getTabCount(); } protected int getNextTabIndexInRun(int tabCount, int base) { if (_runCount < 2) { return getNextTabIndex(base); } int currentRun = getRunForTab(tabCount, base); int next = getNextTabIndex(base); if (next == _tabRuns[getNextTabRun(currentRun)]) { return _tabRuns[currentRun]; } return next; } protected int getPreviousTabIndexInRun(int tabCount, int base) { if (_runCount < 2) { return getPreviousTabIndex(base); } int currentRun = getRunForTab(tabCount, base); if (base == _tabRuns[currentRun]) { int previous = _tabRuns[getNextTabRun(currentRun)] - 1; return (previous != -1 ? previous : tabCount - 1); } return getPreviousTabIndex(base); } protected int getPreviousTabRun(int baseRun) { int runIndex = (baseRun - 1 >= 0 ? baseRun - 1 : _runCount - 1); return (runIndex >= 0 ? runIndex : 0); } protected int getNextTabRun(int baseRun) { return (baseRun + 1) % _runCount; } public static void rotateInsets(Insets topInsets, Insets targetInsets, int targetPlacement) { switch (targetPlacement) { case LEFT: targetInsets.top = topInsets.left; targetInsets.left = topInsets.top; targetInsets.bottom = topInsets.right; targetInsets.right = topInsets.bottom; break; case BOTTOM: targetInsets.top = topInsets.bottom; targetInsets.left = topInsets.left; targetInsets.bottom = topInsets.top; targetInsets.right = topInsets.right; break; case RIGHT: targetInsets.top = topInsets.left; targetInsets.left = topInsets.bottom; targetInsets.bottom = topInsets.right; targetInsets.right = topInsets.top; break; case TOP: default: targetInsets.top = topInsets.top; targetInsets.left = topInsets.left; targetInsets.bottom = topInsets.bottom; targetInsets.right = topInsets.right; } } protected boolean requestFocusForVisibleComponent() { Component visibleComponent = getVisibleComponent(); Component lastFocused = _tabPane.getLastFocusedComponent(visibleComponent); if (lastFocused != null && lastFocused.requestFocusInWindow()) { return true; } else if (visibleComponent != null && visibleComponent.isFocusTraversable()) { JideSwingUtilities.compositeRequestFocus(visibleComponent); return true; } else if (visibleComponent instanceof JComponent) { if (((JComponent) visibleComponent).requestDefaultFocus()) { return true; } } return false; } private static class RightAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); ui.navigateSelectedTab(EAST); } } private static class LeftAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); ui.navigateSelectedTab(WEST); } } private static class UpAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); ui.navigateSelectedTab(NORTH); } } private static class DownAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); ui.navigateSelectedTab(SOUTH); } } private static class NextAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); ui.navigateSelectedTab(NEXT); } } private static class PreviousAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); ui.navigateSelectedTab(PREVIOUS); } } private static class PageUpAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); int tabPlacement = pane.getTabPlacement(); if (tabPlacement == TOP || tabPlacement == BOTTOM) { ui.navigateSelectedTab(WEST); } else { ui.navigateSelectedTab(NORTH); } } } private static class PageDownAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); int tabPlacement = pane.getTabPlacement(); if (tabPlacement == TOP || tabPlacement == BOTTOM) { ui.navigateSelectedTab(EAST); } else { ui.navigateSelectedTab(SOUTH); } } } private static class RequestFocusAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); if (!pane.requestFocusInWindow()) { pane.requestFocus(); } } } private static class RequestFocusForVisibleAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); ui.requestFocusForVisibleComponent(); } } /** * Selects a tab in the JTabbedPane based on the String of the action command. The tab selected * is based on the first tab that has a mnemonic matching the first character of the action * command. */ private static class SetSelectedIndexAction extends AbstractAction { public void actionPerformed(ActionEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); if (pane != null && (pane.getUI() instanceof BasicJideTabbedPaneUI)) { BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); String command = e.getActionCommand(); if (command != null && command.length() > 0) { int mnemonic = (int) e.getActionCommand().charAt(0); if (mnemonic >= 'a' && mnemonic <= 'z') { mnemonic -= ('a' - 'A'); } Integer index = (Integer) ui._mnemonicToIndexMap .get(new Integer(mnemonic)); if (index != null && pane.isEnabledAt(index)) { pane.setSelectedIndex(index); } } } } } protected TabCloseButton createNoFocusButton(int type) { return new TabCloseButton(type); } private static class ScrollTabsForwardAction extends AbstractAction { public ScrollTabsForwardAction() { super(); putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollForward")); } public void actionPerformed(ActionEvent e) { JTabbedPane pane = null; Object src = e.getSource(); if (src instanceof JTabbedPane) { pane = (JTabbedPane) src; } else if (src instanceof TabCloseButton) { pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src); } if (pane != null) { BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); if (ui.scrollableTabLayoutEnabled()) { ui._tabScroller.scrollForward(pane.getTabPlacement()); } } } } private static class ScrollTabsBackwardAction extends AbstractAction { public ScrollTabsBackwardAction() { super(); putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.scrollBackward")); } public void actionPerformed(ActionEvent e) { JTabbedPane pane = null; Object src = e.getSource(); if (src instanceof JTabbedPane) { pane = (JTabbedPane) src; } else if (src instanceof TabCloseButton) { pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src); } if (pane != null) { BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); if (ui.scrollableTabLayoutEnabled()) { ui._tabScroller.scrollBackward(pane.getTabPlacement()); } } } } private static class ScrollTabsListAction extends AbstractAction { public ScrollTabsListAction() { super(); putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.showList")); } public void actionPerformed(ActionEvent e) { JTabbedPane pane = null; Object src = e.getSource(); if (src instanceof JTabbedPane) { pane = (JTabbedPane) src; } else if (src instanceof TabCloseButton) { pane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, (TabCloseButton) src); } if (pane != null) { BasicJideTabbedPaneUI ui = (BasicJideTabbedPaneUI) pane.getUI(); if (ui.scrollableTabLayoutEnabled()) { if (ui._tabScroller._popup != null && ui._tabScroller._popup.isPopupVisible()) { ui._tabScroller._popup.hidePopupImmediately(); ui._tabScroller._popup = null; } else { ui._tabScroller.createPopup(pane.getTabPlacement()); } } } } } private static class CloseTabAction extends AbstractAction { public CloseTabAction() { super(); putValue(Action.SHORT_DESCRIPTION, Resource.getResourceBundle(Locale.getDefault()).getString("JideTabbedPane.close")); } public void actionPerformed(ActionEvent e) { JideTabbedPane pane = null; Object src = e.getSource(); boolean closeSelected = false; if (src instanceof JideTabbedPane) { pane = (JideTabbedPane) src; } else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof JideTabbedPane) { pane = (JideTabbedPane) ((TabCloseButton) src).getParent(); closeSelected = true; } else if (src instanceof TabCloseButton && ((TabCloseButton) src).getParent() instanceof ScrollableTabPanel) { pane = (JideTabbedPane) SwingUtilities.getAncestorOfClass(JideTabbedPane.class, (TabCloseButton) src); closeSelected = false; } else { return; // shouldn't happen } if (pane.isTabEditing()) { pane.stopTabEditing(); } if (pane.getCloseAction() != null) { if (closeSelected) { pane.getCloseAction().actionPerformed(e); } else { int i = ((TabCloseButton) src).getIndex(); if (i != -1) { pane.setSelectedIndex(i); pane.getCloseAction().actionPerformed(e); } } } else { if (closeSelected) { if (pane.getSelectedIndex() >= 0) pane.removeTabAt(pane.getSelectedIndex()); if (pane.getTabCount() == 0) { pane.updateUI(); } } else { int i = ((TabCloseButton) src).getIndex(); if (i != -1) { int tabIndex = pane.getSelectedIndex(); pane.removeTabAt(i); if (i < tabIndex) { pane.setSelectedIndex(tabIndex - 1); } if (pane.getTabCount() == 0) { pane.updateUI(); } } } } } } /** * This inner class is marked &quot;public&quot; due to a compiler bug. This class should be * treated as a &quot;protected&quot; inner class. Instantiate it only within subclasses of * VsnetJideTabbedPaneUI. */ public class TabbedPaneLayout implements LayoutManager { public void addLayoutComponent(String name, Component comp) { } public void removeLayoutComponent(Component comp) { } public Dimension preferredLayoutSize(Container parent) { Dimension dimension = calculateSize(false); return dimension; } public Dimension minimumLayoutSize(Container parent) { return calculateSize(true); } protected Dimension calculateSize(boolean minimum) { int tabPlacement = _tabPane.getTabPlacement(); Insets insets = _tabPane.getInsets(); Insets contentInsets = getContentBorderInsets(tabPlacement); Insets tabAreaInsets = getTabAreaInsets(tabPlacement); Dimension zeroSize = new Dimension(0, 0); int height = contentInsets.top + contentInsets.bottom; int width = contentInsets.left + contentInsets.right; int cWidth = 0; int cHeight = 0; synchronized (this) { ensureCloseButtonCreated(); calculateLayoutInfo(); // Determine minimum size required to display largest // child in each dimension // if (_tabPane.isShowTabContent()) { for (int i = 0; i < _tabPane.getTabCount(); i++) { Component component = _tabPane.getComponentAt(i); if (component != null) { Dimension size = zeroSize; size = minimum ? component.getMinimumSize() : component.getPreferredSize(); if (size != null) { cHeight = Math.max(size.height, cHeight); cWidth = Math.max(size.width, cWidth); } } } // Add content border insets to minimum size width += cWidth; height += cHeight; } int tabExtent = 0; // Calculate how much space the tabs will need, based on the // minimum size required to display largest child + content border // switch (tabPlacement) { case LEFT: case RIGHT: height = Math.max(height, (minimum ? 0 : calculateMaxTabHeight(tabPlacement)) + tabAreaInsets.top + tabAreaInsets.bottom); tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); if (isTabLeadingComponentVisible()) { tabExtent = Math.max(_tabLeadingComponent.getSize().width, tabExtent); } if (isTabTrailingComponentVisible()) { tabExtent = Math.max(_tabTrailingComponent.getSize().width, tabExtent); } width += tabExtent; break; case TOP: case BOTTOM: default: if (_tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) { width = Math.max(width, (_tabPane.getTabCount() << 2) + tabAreaInsets.left + tabAreaInsets.right); } else { width = Math.max(width, (minimum ? 0 : calculateMaxTabWidth(tabPlacement)) + tabAreaInsets.left + tabAreaInsets.right); } if (_tabPane.isTabShown()) { tabExtent = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); if (isTabLeadingComponentVisible()) { tabExtent = Math.max(_tabLeadingComponent.getSize().height, tabExtent); } if (isTabTrailingComponentVisible()) { tabExtent = Math.max(_tabTrailingComponent.getSize().height, tabExtent); } height += tabExtent; } } } return new Dimension(width + insets.left + insets.right, height + insets.bottom + insets.top); } protected int preferredTabAreaHeight(int tabPlacement, int width) { int tabCount = _tabPane.getTabCount(); int total = 0; if (tabCount > 0) { int rows = 1; int x = 0; int maxTabHeight = calculateMaxTabHeight(tabPlacement); for (int i = 0; i < tabCount; i++) { FontMetrics metrics = getFontMetrics(i); int tabWidth = calculateTabWidth(tabPlacement, i, metrics); if (x != 0 && x + tabWidth > width) { rows++; x = 0; } x += tabWidth; } total = calculateTabAreaHeight(tabPlacement, rows, maxTabHeight); } return total; } protected int preferredTabAreaWidth(int tabPlacement, int height) { int tabCount = _tabPane.getTabCount(); int total = 0; if (tabCount > 0) { int columns = 1; int y = 0; _maxTabWidth = calculateMaxTabWidth(tabPlacement); for (int i = 0; i < tabCount; i++) { FontMetrics metrics = getFontMetrics(i); int tabHeight = calculateTabHeight(tabPlacement, i, metrics); if (y != 0 && y + tabHeight > height) { columns++; y = 0; } y += tabHeight; } total = calculateTabAreaWidth(tabPlacement, columns, _maxTabWidth); } return total; } public void layoutContainer(Container parent) { int tabPlacement = _tabPane.getTabPlacement(); Insets insets = _tabPane.getInsets(); int selectedIndex = _tabPane.getSelectedIndex(); Component visibleComponent = getVisibleComponent(); synchronized (this) { ensureCloseButtonCreated(); calculateLayoutInfo(); if (selectedIndex < 0) { if (visibleComponent != null) { // The last tab was removed, so remove the component setVisibleComponent(null); } } else { int cx, cy, cw, ch; int totalTabWidth = 0; int totalTabHeight = 0; Insets contentInsets = getContentBorderInsets(tabPlacement); Component selectedComponent = _tabPane.getComponentAt(selectedIndex); boolean shouldChangeFocus = false; // In order to allow programs to use a single component // as the display for multiple tabs, we will not change // the visible compnent if the currently selected tab // has a null component. This is a bit dicey, as we don't // explicitly state we support this in the spec, but since // programs are now depending on this, we're making it work. // if (selectedComponent != null) { if (selectedComponent != visibleComponent && visibleComponent != null) { if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) { shouldChangeFocus = true; } } setVisibleComponent(selectedComponent); } Rectangle bounds = _tabPane.getBounds(); int numChildren = _tabPane.getComponentCount(); if (numChildren > 0) { switch (tabPlacement) { case LEFT: totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth); cx = insets.left + totalTabWidth + contentInsets.left; cy = insets.top + contentInsets.top; break; case RIGHT: totalTabWidth = calculateTabAreaWidth(tabPlacement, _runCount, _maxTabWidth); cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; break; case BOTTOM: totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; break; case TOP: default: totalTabHeight = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); cx = insets.left + contentInsets.left; cy = insets.top + totalTabHeight + contentInsets.top; } cw = bounds.width - totalTabWidth - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - totalTabHeight - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; for (int i = 0; i < numChildren; i++) { Component child = _tabPane.getComponent(i); child.setBounds(cx, cy, cw, ch); } } if (shouldChangeFocus) { if (!requestFocusForVisibleComponent()) { if (!_tabPane.requestFocusInWindow()) { _tabPane.requestFocus(); } } } } } } public void calculateLayoutInfo() { int tabCount = _tabPane.getTabCount(); assureRectsCreated(tabCount); calculateTabRects(_tabPane.getTabPlacement(), tabCount); } protected void calculateTabRects(int tabPlacement, int tabCount) { Dimension size = _tabPane.getSize(); Insets insets = _tabPane.getInsets(); Insets tabAreaInsets = getTabAreaInsets(tabPlacement); int selectedIndex = _tabPane.getSelectedIndex(); int tabRunOverlay; int i, j; int x, y; int returnAt; boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT); boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); // // Calculate bounds within which a tab run must fit // switch (tabPlacement) { case LEFT: _maxTabWidth = calculateMaxTabWidth(tabPlacement); x = insets.left + tabAreaInsets.left; y = insets.top + tabAreaInsets.top; returnAt = size.height - (insets.bottom + tabAreaInsets.bottom); break; case RIGHT: _maxTabWidth = calculateMaxTabWidth(tabPlacement); x = size.width - insets.right - tabAreaInsets.right - _maxTabWidth; y = insets.top + tabAreaInsets.top; returnAt = size.height - (insets.bottom + tabAreaInsets.bottom); break; case BOTTOM: _maxTabHeight = calculateMaxTabHeight(tabPlacement); x = insets.left + tabAreaInsets.left; y = size.height - insets.bottom - tabAreaInsets.bottom - _maxTabHeight; returnAt = size.width - (insets.right + tabAreaInsets.right); break; case TOP: default: _maxTabHeight = calculateMaxTabHeight(tabPlacement); x = insets.left + tabAreaInsets.left; y = insets.top + tabAreaInsets.top; returnAt = size.width - (insets.right + tabAreaInsets.right); break; } tabRunOverlay = getTabRunOverlay(tabPlacement); _runCount = 0; _selectedRun = -1; if (tabCount == 0) { return; } // Run through tabs and partition them into runs Rectangle rect; for (i = 0; i < tabCount; i++) { FontMetrics metrics = getFontMetrics(i); rect = _rects[i]; if (!verticalTabRuns) { // Tabs on TOP or BOTTOM.... if (i > 0) { rect.x = _rects[i - 1].x + _rects[i - 1].width; } else { _tabRuns[0] = 0; _runCount = 1; _maxTabWidth = 0; rect.x = x; } rect.width = calculateTabWidth(tabPlacement, i, metrics); _maxTabWidth = Math.max(_maxTabWidth, rect.width); // Never move a TAB down a run if it is in the first column. // Even if there isn't enough room, moving it to a fresh // line won't help. if (rect.x != 2 + insets.left && rect.x + rect.width > returnAt) { if (_runCount > _tabRuns.length - 1) { expandTabRunsArray(); } _tabRuns[_runCount] = i; _runCount++; rect.x = x; } // Initialize y position in case there's just one run rect.y = y; rect.height = _maxTabHeight/* - 2 */; } else { // Tabs on LEFT or RIGHT... if (i > 0) { rect.y = _rects[i - 1].y + _rects[i - 1].height; } else { _tabRuns[0] = 0; _runCount = 1; _maxTabHeight = 0; rect.y = y; } rect.height = calculateTabHeight(tabPlacement, i, metrics); _maxTabHeight = Math.max(_maxTabHeight, rect.height); // Never move a TAB over a run if it is in the first run. // Even if there isn't enough room, moving it to a fresh // column won't help. if (rect.y != 2 + insets.top && rect.y + rect.height > returnAt) { if (_runCount > _tabRuns.length - 1) { expandTabRunsArray(); } _tabRuns[_runCount] = i; _runCount++; rect.y = y; } // Initialize x position in case there's just one column rect.x = x; rect.width = _maxTabWidth/* - 2 */; } if (i == selectedIndex) { _selectedRun = _runCount - 1; } } if (_runCount > 1) { // Re-distribute tabs in case last run has leftover space normalizeTabRuns(tabPlacement, tabCount, verticalTabRuns ? y : x, returnAt); _selectedRun = getRunForTab(tabCount, selectedIndex); // Rotate run array so that selected run is first if (shouldRotateTabRuns(tabPlacement)) { rotateTabRuns(tabPlacement, _selectedRun); } } // Step through runs from back to front to calculate // tab y locations and to pad runs appropriately for (i = _runCount - 1; i >= 0; i--) { int start = _tabRuns[i]; int next = _tabRuns[i == (_runCount - 1) ? 0 : i + 1]; int end = (next != 0 ? next - 1 : tabCount - 1); if (!verticalTabRuns) { for (j = start; j <= end; j++) { rect = _rects[j]; rect.y = y; rect.x += getTabRunIndent(tabPlacement, i); } if (shouldPadTabRun(tabPlacement, i)) { padTabRun(tabPlacement, start, end, returnAt); } if (tabPlacement == BOTTOM) { y -= (_maxTabHeight - tabRunOverlay); } else { y += (_maxTabHeight - tabRunOverlay); } } else { for (j = start; j <= end; j++) { rect = _rects[j]; rect.x = x; rect.y += getTabRunIndent(tabPlacement, i); } if (shouldPadTabRun(tabPlacement, i)) { padTabRun(tabPlacement, start, end, returnAt); } if (tabPlacement == RIGHT) { x -= (_maxTabWidth - tabRunOverlay); } else { x += (_maxTabWidth - tabRunOverlay); } } } // Pad the selected tab so that it appears raised in front padSelectedTab(tabPlacement, selectedIndex); // if right to left and tab placement on the top or // the bottom, flip x positions and adjust by widths if (!leftToRight && !verticalTabRuns) { int rightMargin = size.width - (insets.right + tabAreaInsets.right); for (i = 0; i < tabCount; i++) { _rects[i].x = rightMargin - _rects[i].x - _rects[i].width; } } } /* * Rotates the run-index array so that the selected run is run[0] */ protected void rotateTabRuns(int tabPlacement, int selectedRun) { for (int i = 0; i < selectedRun; i++) { int save = _tabRuns[0]; for (int j = 1; j < _runCount; j++) { _tabRuns[j - 1] = _tabRuns[j]; } _tabRuns[_runCount - 1] = save; } } protected void normalizeTabRuns(int tabPlacement, int tabCount, int start, int max) { boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT); int run = _runCount - 1; boolean keepAdjusting = true; double weight = 1.25; // At this point the tab runs are packed to fit as many // tabs as possible, which can leave the last run with a lot // of extra space (resulting in very fat tabs on the last run). // So we'll attempt to distribute this extra space more evenly // across the runs in order to make the runs look more consistent. // // Starting with the last run, determine whether the last tab in // the previous run would fit (generously) in this run; if so, // move tab to current run and shift tabs accordingly. Cycle // through remaining runs using the same algorithm. // while (keepAdjusting) { int last = lastTabInRun(tabCount, run); int prevLast = lastTabInRun(tabCount, run - 1); int end; int prevLastLen; if (!verticalTabRuns) { end = _rects[last].x + _rects[last].width; prevLastLen = (int) (_maxTabWidth * weight); } else { end = _rects[last].y + _rects[last].height; prevLastLen = (int) (_maxTabHeight * weight * 2); } // Check if the run has enough extra space to fit the last tab // from the previous row... if (max - end > prevLastLen) { // Insert tab from previous row and shift rest over _tabRuns[run] = prevLast; if (!verticalTabRuns) { _rects[prevLast].x = start; } else { _rects[prevLast].y = start; } for (int i = prevLast + 1; i <= last; i++) { if (!verticalTabRuns) { _rects[i].x = _rects[i - 1].x + _rects[i - 1].width; } else { _rects[i].y = _rects[i - 1].y + _rects[i - 1].height; } } } else if (run == _runCount - 1) { // no more room left in last run, so we're done! keepAdjusting = false; } if (run - 1 > 0) { // check previous run next... run -= 1; } else { // check last run again...but require a higher ratio // of extraspace-to-tabsize because we don't want to // end up with too many tabs on the last run! run = _runCount - 1; weight += .25; } } } protected void padTabRun(int tabPlacement, int start, int end, int max) { Rectangle lastRect = _rects[end]; if (tabPlacement == TOP || tabPlacement == BOTTOM) { int runWidth = (lastRect.x + lastRect.width) - _rects[start].x; int deltaWidth = max - (lastRect.x + lastRect.width); float factor = (float) deltaWidth / (float) runWidth; for (int j = start; j <= end; j++) { Rectangle pastRect = _rects[j]; if (j > start) { pastRect.x = _rects[j - 1].x + _rects[j - 1].width; } pastRect.width += Math.round((float) pastRect.width * factor); } lastRect.width = max - lastRect.x; } else { int runHeight = (lastRect.y + lastRect.height) - _rects[start].y; int deltaHeight = max - (lastRect.y + lastRect.height); float factor = (float) deltaHeight / (float) runHeight; for (int j = start; j <= end; j++) { Rectangle pastRect = _rects[j]; if (j > start) { pastRect.y = _rects[j - 1].y + _rects[j - 1].height; } pastRect.height += Math.round((float) pastRect.height * factor); } lastRect.height = max - lastRect.y; } } protected void padSelectedTab(int tabPlacement, int selectedIndex) { if (selectedIndex >= 0) { Rectangle selRect = _rects[selectedIndex]; Insets padInsets = getSelectedTabPadInsets(tabPlacement); selRect.x -= padInsets.left; selRect.width += (padInsets.left + padInsets.right); selRect.y -= padInsets.top; selRect.height += (padInsets.top + padInsets.bottom); } } } protected TabSpaceAllocator tryTabSpacer = new TabSpaceAllocator(); protected class TabbedPaneScrollLayout extends TabbedPaneLayout { @Override protected int preferredTabAreaHeight(int tabPlacement, int width) { return calculateMaxTabHeight(tabPlacement); } @Override protected int preferredTabAreaWidth(int tabPlacement, int height) { return calculateMaxTabWidth(tabPlacement); } @Override public void layoutContainer(Container parent) { int tabPlacement = _tabPane.getTabPlacement(); int tabCount = _tabPane.getTabCount(); Insets insets = _tabPane.getInsets(); int selectedIndex = _tabPane.getSelectedIndex(); Component visibleComponent = getVisibleComponent(); boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); calculateLayoutInfo(); if (selectedIndex < 0) { if (visibleComponent != null) { // The last tab was removed, so remove the component setVisibleComponent(null); } } else { Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89 boolean shouldChangeFocus = false; // In order to allow programs to use a single component // as the display for multiple tabs, we will not change // the visible compnent if the currently selected tab // has a null component. This is a bit dicey, as we don't // explicitly state we support this in the spec, but since // programs are now depending on this, we're making it work. // if (selectedComponent != null) { if (selectedComponent != visibleComponent && visibleComponent != null) { if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) { shouldChangeFocus = true; } } setVisibleComponent(selectedComponent); } int tx, ty, tw, th; // tab area bounds int cx, cy, cw, ch; // content area bounds Insets contentInsets = getContentBorderInsets(tabPlacement); Rectangle bounds = _tabPane.getBounds(); int numChildren = _tabPane.getComponentCount(); Dimension lsize = new Dimension(0, 0); Dimension tsize = new Dimension(0, 0); if (isTabLeadingComponentVisible()) { lsize = _tabLeadingComponent.getSize(); } if (isTabTrailingComponentVisible()) { tsize = _tabTrailingComponent.getSize(); } if (numChildren > 0) { switch (tabPlacement) { case LEFT: // calculate tab area bounds tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = insets.left; ty = insets.top; if (isTabLeadingComponentVisible()) { ty += lsize.height; th -= lsize.height; if (lsize.width > tw) { tw = lsize.width; } } if (isTabTrailingComponentVisible()) { th -= tsize.height; if (tsize.width > tw) { tw = tsize.width; } } // calculate content area bounds cx = tx + tw + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case RIGHT: // calculate tab area bounds tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = bounds.width - insets.right - tw; ty = insets.top; if (isTabLeadingComponentVisible()) { ty += lsize.height; th -= lsize.height; if (lsize.width > tw) { tw = lsize.width; tx = bounds.width - insets.right - tw; } } if (isTabTrailingComponentVisible()) { th -= tsize.height; if (tsize.width > tw) { tw = tsize.width; tx = bounds.width - insets.right - tw; } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case BOTTOM: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); tx = insets.left; ty = bounds.height - insets.bottom - th; if (leftToRight) { if (isTabLeadingComponentVisible()) { tx += lsize.width; tw -= lsize.width; if (lsize.height > th) { th = lsize.height; ty = bounds.height - insets.bottom - th; } } if (isTabTrailingComponentVisible()) { tw -= tsize.width; if (tsize.height > th) { th = tsize.height; ty = bounds.height - insets.bottom - th; } } } else { if (isTabTrailingComponentVisible()) { tx += tsize.width; tw -= tsize.width; if (tsize.height > th) { th = tsize.height; ty = bounds.height - insets.bottom - th; } } if (isTabLeadingComponentVisible()) { tw -= lsize.width; if (lsize.height > th) { th = lsize.height; ty = bounds.height - insets.bottom - th; } } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; break; case TOP: default: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); tx = insets.left; ty = insets.top; if (leftToRight) { if (isTabLeadingComponentVisible()) { tx += lsize.width; tw -= lsize.width; if (lsize.height > th) { th = lsize.height; } } if (isTabTrailingComponentVisible()) { tw -= tsize.width; if (tsize.height > th) { th = tsize.height; } } } else { if (isTabTrailingComponentVisible()) { tx += tsize.width; tw -= tsize.width; if (tsize.height > th) { th = tsize.height; } } if (isTabLeadingComponentVisible()) { tw -= lsize.width; if (lsize.height > th) { th = lsize.height; } } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + th + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; } // if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) { // if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) { // int numberOfButtons = isShrinkTabs() ? 1 : 4; // if (tw < _rects[0].width + numberOfButtons * _buttonSize) { // return; // } // } // } // else { // if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) { // int numberOfButtons = isShrinkTabs() ? 1 : 4; // if (th < _rects[0].height + numberOfButtons * _buttonSize) { // return; // } // } // } for (int i = 0; i < numChildren; i++) { Component child = _tabPane.getComponent(i); if (child instanceof ScrollableTabViewport) { JViewport viewport = (JViewport) child; // Rectangle viewRect = viewport.getViewRect(); int vw = tw; int vh = th; int numberOfButtons = getNumberOfTabButtons(); switch (tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height; if (totalTabHeight > th || isShowTabButtons()) { - numberOfButtons += 3; + if (!isShowTabButtons()) numberOfButtons += 3; // Allow space for scrollbuttons vh = Math.max(th - _buttonSize * numberOfButtons, 0); // if (totalTabHeight - viewRect.y <= vh) { // // Scrolled to the end, so ensure the // // viewport size is // // such that the scroll offset aligns // // with a tab // vh = totalTabHeight - viewRect.y; // } } else { // Allow space for scrollbuttons vh = Math.max(th - _buttonSize * numberOfButtons, 0); } if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) { vh += getLayoutSize(); } break; case BOTTOM: case TOP: default: int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width; if (isShowTabButtons() || totalTabWidth > tw) { - numberOfButtons += 3; + if (!isShowTabButtons()) numberOfButtons += 3; // Need to allow space for scrollbuttons vw = Math.max(tw - _buttonSize * numberOfButtons, 0); // if (totalTabWidth - viewRect.x <= vw) { // // Scrolled to the end, so ensure the // // viewport size is // // such that the scroll offset aligns // // with a tab // vw = totalTabWidth - viewRect.x; // } } else { // Allow space for scrollbuttons vw = Math.max(tw - _buttonSize * numberOfButtons, 0); } if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) { vw += getLayoutSize(); } break; } child.setBounds(tx, ty, vw, vh); } else if (child instanceof TabCloseButton) { TabCloseButton scrollbutton = (TabCloseButton) child; if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) { Dimension bsize = scrollbutton.getPreferredSize(); int bx = 0; int by = 0; int bw = bsize.width; int bh = bsize.height; boolean visible = false; switch (tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height; if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) { int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON; scrollbutton.setType(dir); switch (dir) { case TabCloseButton.CLOSE_BUTTON: if (isShowCloseButton()) { visible = true; by = bounds.height - insets.top - bsize.height - 5; } else { visible = false; by = 0; } break; case TabCloseButton.LIST_BUTTON: visible = true; by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; case TabCloseButton.EAST_BUTTON: visible = !isShrinkTabs(); by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; case TabCloseButton.WEST_BUTTON: visible = !isShrinkTabs(); by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; } bx = tx + 2; } else { int dir = scrollbutton.getType(); scrollbutton.setType(dir); if (dir == TabCloseButton.CLOSE_BUTTON) { if (isShowCloseButton()) { visible = true; by = bounds.height - insets.top - bsize.height - 5; } else { visible = false; by = 0; } bx = tx + 2; } } if (isTabTrailingComponentVisible()) { by = by - tsize.height; } int temp = -1; if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().width >= _rects[0].width) { if (tabPlacement == LEFT) { bx += _tabLeadingComponent.getSize().width - _rects[0].width; temp = _tabLeadingComponent.getSize().width; } } } if (isTabTrailingComponentVisible()) { if (_tabTrailingComponent.getSize().width >= _rects[0].width && temp < _tabTrailingComponent.getSize().width) { if (tabPlacement == LEFT) { bx += _tabTrailingComponent.getSize().width - _rects[0].width; } } } break; case TOP: case BOTTOM: default: int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width; if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabWidth > tw)) { int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON // NoFocusButton.WEST_BUTTON; scrollbutton.setType(dir); switch (dir) { case TabCloseButton.CLOSE_BUTTON: if (isShowCloseButton()) { visible = true; bx = bounds.width - insets.left - bsize.width - 5; } else { visible = false; bx = 0; } break; case TabCloseButton.LIST_BUTTON: visible = true; bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; case TabCloseButton.EAST_BUTTON: visible = !isShrinkTabs(); bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; case TabCloseButton.WEST_BUTTON: visible = !isShrinkTabs(); bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; } by = ((th - bsize.height) >> 1) + ty; } else { int dir = scrollbutton.getType(); scrollbutton.setType(dir); if (dir == TabCloseButton.CLOSE_BUTTON) { if (isShowCloseButton()) { visible = true; bx = bounds.width - insets.left - bsize.width - 5; } else { visible = false; bx = 0; } by = ((th - bsize.height) >> 1) + ty; } } if (isTabTrailingComponentVisible()) { bx -= tsize.width; } temp = -1; if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().height >= _rects[0].height) { if (tabPlacement == TOP) { by = ty + 2 + _tabLeadingComponent.getSize().height - _rects[0].height; temp = _tabLeadingComponent.getSize().height; } else { by = ty + 2; } } } if (isTabTrailingComponentVisible()) { if (_tabTrailingComponent.getSize().height >= _rects[0].height && temp < _tabTrailingComponent.getSize().height) { if (tabPlacement == TOP) { by = ty + 2 + _tabTrailingComponent.getSize().height - _rects[0].height; } else { by = ty + 2; } } } } child.setVisible(visible); if (visible) { child.setBounds(bx, by, bw, bh); } } else { scrollbutton.setBounds(0, 0, 0, 0); } } else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) { if (_tabPane.isShowTabContent()) { // All content children... child.setBounds(cx, cy, cw, ch); } else { child.setBounds(0, 0, 0, 0); } } } if (leftToRight) { if (isTabLeadingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height); break; case RIGHT: _tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height); break; case BOTTOM: _tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height); break; case TOP: default: _tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height); break; } } if (isTabTrailingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height); break; case RIGHT: _tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height); break; case BOTTOM: _tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height); break; case TOP: default: _tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height); break; } } } else { if (isTabTrailingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height); break; case RIGHT: _tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height); break; case BOTTOM: _tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height); break; case TOP: default: _tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height); break; } } if (isTabLeadingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height); break; case RIGHT: _tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height); break; case BOTTOM: _tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height); break; case TOP: default: _tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height); break; } } } if (shouldChangeFocus) { if (!requestFocusForVisibleComponent()) { if (!_tabPane.requestFocusInWindow()) { _tabPane.requestFocus(); } } } } } } @Override protected void calculateTabRects(int tabPlacement, int tabCount) { Dimension size = _tabPane.getSize(); Insets insets = _tabPane.getInsets(); Insets tabAreaInsets = getTabAreaInsets(tabPlacement); boolean verticalTabRuns = (tabPlacement == LEFT || tabPlacement == RIGHT); boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); int x = tabAreaInsets.left; int y = tabAreaInsets.top; int totalWidth = 0; int totalHeight = 0; // // Calculate bounds within which a tab run must fit // switch (tabPlacement) { case LEFT: case RIGHT: _maxTabWidth = calculateMaxTabWidth(tabPlacement); if (isTabLeadingComponentVisible()) { if (tabPlacement == RIGHT) { if (_maxTabWidth < _tabLeadingComponent.getSize().width) { _maxTabWidth = _tabLeadingComponent.getSize().width; } } } if (isTabTrailingComponentVisible()) { if (tabPlacement == RIGHT) { if (_maxTabWidth < _tabTrailingComponent.getSize().width) { _maxTabWidth = _tabTrailingComponent.getSize().width; } } } break; case BOTTOM: case TOP: default: _maxTabHeight = calculateMaxTabHeight(tabPlacement); if (isTabLeadingComponentVisible()) { if (tabPlacement == BOTTOM) { if (_maxTabHeight < _tabLeadingComponent.getSize().height) { _maxTabHeight = _tabLeadingComponent.getSize().height; } } } if (isTabTrailingComponentVisible()) { if (tabPlacement == BOTTOM) { if (_maxTabHeight < _tabTrailingComponent.getSize().height) { _maxTabHeight = _tabTrailingComponent.getSize().height; } } } } _runCount = 0; _selectedRun = -1; if (tabCount == 0) { return; } _selectedRun = 0; _runCount = 1; // Run through tabs and lay them out in a single run Rectangle rect; for (int i = 0; i < tabCount; i++) { FontMetrics metrics = getFontMetrics(i); rect = _rects[i]; if (!verticalTabRuns) { // Tabs on TOP or BOTTOM.... if (i > 0) { rect.x = _rects[i - 1].x + _rects[i - 1].width; } else { _tabRuns[0] = 0; _maxTabWidth = 0; totalHeight += _maxTabHeight; if (getTabShape() != JideTabbedPane.SHAPE_BOX) { rect.x = x + getLeftMargin();// give the first tab arrow angle extra space } else { rect.x = x; } } rect.width = calculateTabWidth(tabPlacement, i, metrics) + _rectSizeExtend; totalWidth = rect.x + rect.width; _maxTabWidth = Math.max(_maxTabWidth, rect.width); rect.y = y; int temp = -1; if (isTabLeadingComponentVisible()) { if (tabPlacement == TOP) { if (_maxTabHeight < _tabLeadingComponent.getSize().height) { rect.y = y + _tabLeadingComponent.getSize().height - _maxTabHeight - 2; temp = _tabLeadingComponent.getSize().height; if (_rectSizeExtend > 0) { rect.y = rect.y + 2; } } } } if (isTabTrailingComponentVisible()) { if (tabPlacement == TOP) { if (_maxTabHeight < _tabTrailingComponent.getSize().height && temp < _tabTrailingComponent.getSize().height) { rect.y = y + _tabTrailingComponent.getSize().height - _maxTabHeight - 2; if (_rectSizeExtend > 0) { rect.y = rect.y + 2; } } } } rect.height = calculateMaxTabHeight(tabPlacement);///* - 2 */; } else { // Tabs on LEFT or RIGHT... if (i > 0) { rect.y = _rects[i - 1].y + _rects[i - 1].height; } else { _tabRuns[0] = 0; _maxTabHeight = 0; totalWidth = _maxTabWidth; if (getTabShape() != JideTabbedPane.SHAPE_BOX) { rect.y = y + getLeftMargin();// give the first tab arrow angle extra space } else { rect.y = y; } } rect.height = calculateTabHeight(tabPlacement, i, metrics) + _rectSizeExtend; totalHeight = rect.y + rect.height; _maxTabHeight = Math.max(_maxTabHeight, rect.height); rect.x = x; int temp = -1; if (isTabLeadingComponentVisible()) { if (tabPlacement == LEFT) { if (_maxTabWidth < _tabLeadingComponent.getSize().width) { rect.x = x + _tabLeadingComponent.getSize().width - _maxTabWidth - 2; temp = _tabLeadingComponent.getSize().width; if (_rectSizeExtend > 0) { rect.x = rect.x + 2; } } } } if (isTabTrailingComponentVisible()) { if (tabPlacement == LEFT) { if (_maxTabWidth < _tabTrailingComponent.getSize().width && temp < _tabTrailingComponent.getSize().width) { rect.x = x + _tabTrailingComponent.getSize().width - _maxTabWidth - 2; if (_rectSizeExtend > 0) { rect.x = rect.x + 2; } } } } rect.width = calculateMaxTabWidth(tabPlacement)/* - 2 */; } } // if right to left and tab placement on the top or // the bottom, flip x positions and adjust by widths if (!leftToRight && !verticalTabRuns) { int rightMargin = size.width - (insets.right + tabAreaInsets.right); if (isTabLeadingComponentVisible()) { rightMargin -= _tabLeadingComponent.getPreferredSize().width; } int offset = 0; if (isTabTrailingComponentVisible()) { offset += _tabTrailingComponent.getPreferredSize().width; } for (int i = 0; i < tabCount; i++) { _rects[i].x = rightMargin - _rects[i].x - _rects[i].width - offset + getLeftMargin(); // if(i == tabCount - 1) { // _rects[i].width += getLeftMargin(); // _rects[i].x -= getLeftMargin(); // } } } ensureCurrentRects(getLeftMargin(), tabCount); } } protected void ensureCurrentRects(int leftMargin, int tabCount) { Dimension size = _tabPane.getSize(); Insets insets = _tabPane.getInsets(); int totalWidth = 0; int totalHeight = 0; boolean verticalTabRuns = (_tabPane.getTabPlacement() == LEFT || _tabPane.getTabPlacement() == RIGHT); if (tabCount == 0) { return; } Rectangle r = _rects[tabCount - 1]; Dimension lsize = new Dimension(0, 0); Dimension tsize = new Dimension(0, 0); if (isTabLeadingComponentVisible()) { lsize = _tabLeadingComponent.getSize(); } if (isTabTrailingComponentVisible()) { tsize = _tabTrailingComponent.getSize(); } if (verticalTabRuns) { totalHeight = r.y + r.height; if (_tabLeadingComponent != null) { totalHeight -= lsize.height; } } else { totalWidth = r.x + r.width; if (_tabLeadingComponent != null) { totalWidth -= lsize.width; } } if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT) {// LayOut Style is Size to Fix if (verticalTabRuns) { int availHeight; if (getTabShape() != JideTabbedPane.SHAPE_BOX) { availHeight = (int) size.getHeight() - _fitStyleBoundSize - insets.top - insets.bottom - leftMargin - getTabRightPadding();// give the first tab extra space } else { availHeight = (int) size.getHeight() - _fitStyleBoundSize - insets.top - insets.bottom; } if (_tabPane.isShowCloseButton()) { availHeight -= _buttonSize; } if (isTabLeadingComponentVisible()) { availHeight = availHeight - lsize.height; } if (isTabTrailingComponentVisible()) { availHeight = availHeight - tsize.height; } int numberOfButtons = getNumberOfTabButtons(); availHeight -= _buttonSize * numberOfButtons; if (totalHeight > availHeight) { // shrink is necessary // calculate each tab width int tabHeight = availHeight / tabCount; totalHeight = _fitStyleFirstTabMargin; // start for (int k = 0; k < tabCount; k++) { _rects[k].height = tabHeight; Rectangle tabRect = _rects[k]; if (getTabShape() != JideTabbedPane.SHAPE_BOX) { tabRect.y = totalHeight + leftMargin;// give the first tab extra space } else { tabRect.y = totalHeight; } totalHeight += tabRect.height; } } } else { int availWidth; if (getTabShape() != JideTabbedPane.SHAPE_BOX) { availWidth = (int) size.getWidth() - _fitStyleBoundSize - insets.left - insets.right - leftMargin - getTabRightPadding(); } else { availWidth = (int) size.getWidth() - _fitStyleBoundSize - insets.left - insets.right; } if (_tabPane.isShowCloseButton()) { availWidth -= _buttonSize; } if (isTabLeadingComponentVisible()) { availWidth -= lsize.width; } if (isTabTrailingComponentVisible()) { availWidth -= tsize.width; } int numberOfButtons = getNumberOfTabButtons(); availWidth -= _buttonSize * numberOfButtons; if (totalWidth > availWidth) { // shrink is necessary // calculate each tab width int tabWidth = availWidth / tabCount; int gripperWidth = _tabPane.isShowGripper() ? _gripperWidth : 0; if (tabWidth < _textIconGap + _fitStyleTextMinWidth + _fitStyleIconMinWidth + gripperWidth && tabWidth > _fitStyleIconMinWidth + gripperWidth) // cannot // hold any text but can hold an icon tabWidth = _fitStyleIconMinWidth + gripperWidth; if (tabWidth < _fitStyleIconMinWidth + gripperWidth && tabWidth > _fitStyleFirstTabMargin + gripperWidth) // cannot // hold any icon but gripper tabWidth = _fitStyleFirstTabMargin + gripperWidth; tryTabSpacer.reArrange(_rects, insets, availWidth); } totalWidth = _fitStyleFirstTabMargin; // start for (int k = 0; k < tabCount; k++) { Rectangle tabRect = _rects[k]; if (getTabShape() != JideTabbedPane.SHAPE_BOX) { tabRect.x = totalWidth + leftMargin;// give the first tab extra space when the style is not box style } else { tabRect.x = totalWidth; } totalWidth += tabRect.width; } } } if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIXED) {// LayOut Style is Fix if (verticalTabRuns) { for (int k = 0; k < tabCount; k++) { _rects[k].height = _fixedStyleRectSize;// + _rectSizeExtend * 2; if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) { _rects[k].height += _closeButtons[k].getPreferredSize().height; } if (k != 0) { _rects[k].y = _rects[k - 1].y + _rects[k - 1].height; } totalHeight = _rects[k].y + _rects[k].height; } } else { for (int k = 0; k < tabCount; k++) { _rects[k].width = _fixedStyleRectSize;// + _rectSizeExtend * 2; if (isShowCloseButton() && _tabPane.isShowCloseButtonOnTab()) { _rects[k].width += _closeButtons[k].getPreferredSize().width; } if (k != 0) { _rects[k].x = _rects[k - 1].x + _rects[k - 1].width; } totalWidth = _rects[k].x + _rects[k].width; } } } if (getTabResizeMode() == JideTabbedPane.RESIZE_MODE_COMPRESSED) {// LayOut Style is Compressed if (verticalTabRuns) { for (int k = 0; k < tabCount; k++) { if (k != _tabPane.getSelectedIndex()) { if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) { _rects[k].height = _compressedStyleNoIconRectSize; } else { Icon icon = _tabPane.getIconForTab(k); _rects[k].height = icon.getIconHeight() + _compressedStyleIconMargin; } if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) { _rects[k].height = _rects[k].height + _closeButtons[k].getPreferredSize().height + _compressedStyleCloseButtonMarginVertical; } } if (k != 0) { _rects[k].y = _rects[k - 1].y + _rects[k - 1].height; } totalHeight = _rects[k].y + _rects[k].height; } } else { for (int k = 0; k < tabCount; k++) { if (k != _tabPane.getSelectedIndex()) { if (!_tabPane.isShowIconsOnTab() && !_tabPane.isUseDefaultShowIconsOnTab()) { _rects[k].width = _compressedStyleNoIconRectSize; } else { Icon icon = _tabPane.getIconForTab(k); _rects[k].width = icon.getIconWidth() + _compressedStyleIconMargin; } if (isShowCloseButton() && isShowCloseButtonOnTab() && !_tabPane.isShowCloseButtonOnSelectedTab()) { _rects[k].width = _rects[k].width + _closeButtons[k].getPreferredSize().width + _compressedStyleCloseButtonMarginHorizon; } } if (k != 0) { _rects[k].x = _rects[k - 1].x + _rects[k - 1].width; } totalWidth = _rects[k].x + _rects[k].width; } } } if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) { totalWidth += getLayoutSize(); if (isTabLeadingComponentVisible()) { totalWidth += _tabLeadingComponent.getSize().width; } } else { totalHeight += getLayoutSize(); if (isTabLeadingComponentVisible()) { totalHeight += _tabLeadingComponent.getSize().height; } } _tabScroller.tabPanel.setPreferredSize(new Dimension(totalWidth, totalHeight)); } protected class ActivateTabAction extends AbstractAction { int _tabIndex; public ActivateTabAction(String name, Icon icon, int tabIndex) { super(name, icon); _tabIndex = tabIndex; } public void actionPerformed(ActionEvent e) { _tabPane.setSelectedIndex(_tabIndex); } } protected ListCellRenderer getTabListCellRenderer() { return _tabPane.getTabListCellRenderer(); } public class ScrollableTabSupport implements ChangeListener { public ScrollableTabViewport viewport; public ScrollableTabPanel tabPanel; public TabCloseButton scrollForwardButton; public TabCloseButton scrollBackwardButton; public TabCloseButton listButton; public TabCloseButton closeButton; public int leadingTabIndex; private Point tabViewPosition = new Point(0, 0); public JidePopup _popup; ScrollableTabSupport(int tabPlacement) { viewport = new ScrollableTabViewport(); tabPanel = new ScrollableTabPanel(); viewport.setView(tabPanel); viewport.addChangeListener(this); scrollForwardButton = createNoFocusButton(TabCloseButton.EAST_BUTTON); scrollForwardButton.setName("TabScrollForward"); scrollBackwardButton = createNoFocusButton(TabCloseButton.WEST_BUTTON); scrollBackwardButton.setName("TabScrollBackward"); scrollForwardButton.setBackground(viewport.getBackground()); scrollBackwardButton.setBackground(viewport.getBackground()); listButton = createNoFocusButton(TabCloseButton.LIST_BUTTON); listButton.setBackground(viewport.getBackground()); closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON); closeButton.setBackground(viewport.getBackground()); } public void createPopupMenu(int tabPlacement) { JPopupMenu popup = new JPopupMenu(); int totalCount = _tabPane.getTabCount(); // drop down menu items int selectedIndex = _tabPane.getSelectedIndex(); for (int i = 0; i < totalCount; i++) { if (_tabPane.isEnabledAt(i)) { JMenuItem item; popup.add(item = new JCheckBoxMenuItem(new ActivateTabAction(_tabPane.getTitleAt(i), _tabPane.getIconForTab(i), i))); item.setToolTipText(_tabPane.getToolTipTextAt(i)); item.setSelected(selectedIndex == i); item.setHorizontalTextPosition(JMenuItem.RIGHT); } } Dimension preferredSize = popup.getPreferredSize(); Rectangle bounds = listButton.getBounds(); switch (tabPlacement) { case TOP: popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y + bounds.height); break; case BOTTOM: popup.show(_tabPane, bounds.x + bounds.width - preferredSize.width, bounds.y - preferredSize.height); break; case LEFT: popup.show(_tabPane, bounds.x + bounds.width, bounds.y + bounds.height - preferredSize.height); break; case RIGHT: popup.show(_tabPane, bounds.x - preferredSize.width, bounds.y + bounds.height - preferredSize.height); break; } } public void createPopup(int tabPlacement) { final JList list = new JList() { // override this method to disallow deselect by ctrl-click @Override public void removeSelectionInterval(int index0, int index1) { super.removeSelectionInterval(index0, index1); if (getSelectedIndex() == -1) { setSelectedIndex(index0); } } @Override public Dimension getPreferredScrollableViewportSize() { Dimension preferredScrollableViewportSize = super.getPreferredScrollableViewportSize(); if (preferredScrollableViewportSize.width < 150) { preferredScrollableViewportSize.width = 150; } return preferredScrollableViewportSize; } }; new Sticky(list); list.setBackground(_tabListBackground); JScrollPane scroller = new JScrollPane(list); scroller.setBorder(BorderFactory.createEmptyBorder()); scroller.getViewport().setOpaque(false); scroller.setOpaque(false); JPanel panel = new JPanel(new BorderLayout()); panel.setBackground(_tabListBackground); panel.setOpaque(true); panel.add(scroller); panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); if (_popup != null) { if (_popup.isPopupVisible()) { _popup.hidePopupImmediately(); } _popup = null; } _popup = new JidePopup(); _popup.setPopupBorder(BorderFactory.createLineBorder(_darkShadow)); _popup.add(panel); _popup.addExcludedComponent(listButton); _popup.setDefaultFocusComponent(list); DefaultListModel listModel = new DefaultListModel(); // drop down menu items int selectedIndex = _tabPane.getSelectedIndex(); int totalCount = _tabPane.getTabCount(); for (int i = 0; i < totalCount; i++) { listModel.addElement(_tabPane); } list.setCellRenderer(getTabListCellRenderer()); list.setModel(listModel); list.setSelectedIndex(selectedIndex); list.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { int index = list.getSelectedIndex(); if (index != -1 && _tabPane.isEnabledAt(index)) { _tabPane.setSelectedIndex(index); ensureActiveTabIsVisible(false); _popup.hidePopupImmediately(); _popup = null; } } }); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); Insets insets = panel.getInsets(); int max = (PortingUtils.getLocalScreenSize(_tabPane).height - insets.top - insets.bottom) / list.getCellBounds(0, 0).height; if (listModel.getSize() > max) { list.setVisibleRowCount(max); } else { list.setVisibleRowCount(listModel.getSize()); } _popup.setOwner(_tabPane); _popup.removeExcludedComponent(_tabPane); Dimension size = _popup.getPreferredSize(); Rectangle bounds = listButton.getBounds(); Point p = listButton.getLocationOnScreen(); bounds.x = p.x; bounds.y = p.y; int x; int y; switch (tabPlacement) { case TOP: default: x = bounds.x + bounds.width - size.width; y = bounds.y + bounds.height + 2; break; case BOTTOM: x = bounds.x + bounds.width - size.width; y = bounds.y - size.height - 2; break; case LEFT: x = bounds.x + bounds.width + 2; y = bounds.y + bounds.height - size.height; break; case RIGHT: x = bounds.x - size.width - 2; y = bounds.y + bounds.height - size.height; break; } Rectangle screenBounds = PortingUtils.getScreenBounds(_tabPane); int right = x + size.width + 3; int bottom = y + size.height + 3; if (right > screenBounds.x + screenBounds.width) { x -= right - screenBounds.x - screenBounds.width; // move left so that the whole popup can fit in } if (x < screenBounds.x) { x = screenBounds.x; // move right so that the whole popup can fit in } if (bottom > screenBounds.height) { y -= bottom - screenBounds.height; } if (y < screenBounds.y) { y = screenBounds.y; } _popup.showPopup(x, y); } public void scrollForward(int tabPlacement) { Dimension viewSize = viewport.getViewSize(); Rectangle viewRect = viewport.getViewRect(); if (tabPlacement == TOP || tabPlacement == BOTTOM) { if (viewRect.width >= viewSize.width - viewRect.x) { return; // no room left to scroll } } else { // tabPlacement == LEFT || tabPlacement == RIGHT if (viewRect.height >= viewSize.height - viewRect.y) { return; } } setLeadingTabIndex(tabPlacement, leadingTabIndex + 1); } public void scrollBackward(int tabPlacement) { setLeadingTabIndex(tabPlacement, leadingTabIndex > 0 ? leadingTabIndex - 1 : 0); } public void setLeadingTabIndex(int tabPlacement, int index) { // make sure the index is in range if (index < 0 || index >= _tabPane.getTabCount()) { return; } leadingTabIndex = index; Dimension viewSize = viewport.getViewSize(); Rectangle viewRect = viewport.getViewRect(); switch (tabPlacement) { case TOP: case BOTTOM: tabViewPosition.y = 0; tabViewPosition.x = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].x; if ((viewSize.width - tabViewPosition.x) < viewRect.width) { tabViewPosition.x = viewSize.width - viewRect.width; // // We've scrolled to the end, so adjust the viewport size // // to ensure the view position remains aligned on a tab boundary // Dimension extentSize = new Dimension(viewSize.width - tabViewPosition.x, // viewRect.height); // System.out.println("setExtendedSize: " + extentSize); // viewport.setExtentSize(extentSize); } break; case LEFT: case RIGHT: tabViewPosition.x = 0; tabViewPosition.y = leadingTabIndex == 0 ? 0 : _rects[leadingTabIndex].y; if ((viewSize.height - tabViewPosition.y) < viewRect.height) { tabViewPosition.y = viewSize.height - viewRect.height; // // We've scrolled to the end, so adjust the viewport size // // to ensure the view position remains aligned on a tab boundary // Dimension extentSize = new Dimension(viewRect.width, // viewSize.height - tabViewPosition.y); // viewport.setExtentSize(extentSize); } break; } viewport.setViewPosition(tabViewPosition); } public void stateChanged(ChangeEvent e) { if (_tabPane == null) return; ensureCurrentLayout(); JViewport viewport = (JViewport) e.getSource(); int tabPlacement = _tabPane.getTabPlacement(); int tabCount = _tabPane.getTabCount(); Rectangle vpRect = viewport.getBounds(); Dimension viewSize = viewport.getViewSize(); Rectangle viewRect = viewport.getViewRect(); leadingTabIndex = getClosestTab(viewRect.x, viewRect.y); // If the tab isn't right aligned, adjust it. if (leadingTabIndex < _rects.length && leadingTabIndex >= _rects.length) { switch (tabPlacement) { case TOP: case BOTTOM: if (_rects[leadingTabIndex].x < viewRect.x) { leadingTabIndex++; } break; case LEFT: case RIGHT: if (_rects[leadingTabIndex].y < viewRect.y) { leadingTabIndex++; } break; } } Insets contentInsets = getContentBorderInsets(tabPlacement); switch (tabPlacement) { case LEFT: _tabPane.repaint(vpRect.x + vpRect.width, vpRect.y, contentInsets.left, vpRect.height); scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0); scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height); break; case RIGHT: _tabPane.repaint(vpRect.x - contentInsets.right, vpRect.y, contentInsets.right, vpRect.height); scrollBackwardButton.setEnabled(viewRect.y > 0 || leadingTabIndex > 0); scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.height - viewRect.y > viewRect.height); break; case BOTTOM: _tabPane.repaint(vpRect.x, vpRect.y - contentInsets.bottom, vpRect.width, contentInsets.bottom); scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0); scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - viewRect.x > viewRect.width); break; case TOP: default: _tabPane.repaint(vpRect.x, vpRect.y + vpRect.height, vpRect.width, contentInsets.top); scrollBackwardButton.setEnabled(viewRect.x > 0 || leadingTabIndex > 0); scrollForwardButton.setEnabled(leadingTabIndex < tabCount - 1 && viewSize.width - viewRect.x > viewRect.width); } if (SystemInfo.isJdk15Above()) { _tabPane.setComponentZOrder(_tabScroller.scrollForwardButton, 0); _tabPane.setComponentZOrder(_tabScroller.scrollBackwardButton, 0); } _tabScroller.scrollForwardButton.repaint(); _tabScroller.scrollBackwardButton.repaint(); int selectedIndex = _tabPane.getSelectedIndex(); if (selectedIndex >= 0 && selectedIndex < _tabPane.getTabCount()) { closeButton.setEnabled(_tabPane.isTabClosableAt(selectedIndex)); } } @Override public String toString() { return "viewport.viewSize=" + viewport.getViewSize() + "\n" + "viewport.viewRectangle=" + viewport.getViewRect() + "\n" + "leadingTabIndex=" + leadingTabIndex + "\n" + "tabViewPosition=" + tabViewPosition; } } public class ScrollableTabViewport extends JViewport implements UIResource { public ScrollableTabViewport() { super(); setScrollMode(JViewport.SIMPLE_SCROLL_MODE); setOpaque(false); } /** * Gets the background color of this component. * * @return this component's background color; if this component does not have a background * color, the background color of its parent is returned */ @Override public Color getBackground() { return UIDefaultsLookup.getColor("JideTabbedPane.background"); } } public class ScrollableTabPanel extends JPanel implements UIResource { public ScrollableTabPanel() { setLayout(null); } @Override public boolean isOpaque() { return false; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (_tabPane.isOpaque()) { if (getTabShape() == JideTabbedPane.SHAPE_BOX) { g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.selectedTabBackground")); } else { g.setColor(UIDefaultsLookup.getColor("JideTabbedPane.tabAreaBackground")); } g.fillRect(0, 0, getWidth(), getHeight()); } paintTabArea(g, _tabPane.getTabPlacement(), _tabPane.getSelectedIndex(), this); } // workaround for swing bug // http://developer.java.sun.com/developer/bugParade/bugs/4668865.html @Override public void setToolTipText(String text) { _tabPane.setToolTipText(text); } @Override public String getToolTipText() { return _tabPane.getToolTipText(); } @Override public String getToolTipText(MouseEvent event) { return _tabPane.getToolTipText(SwingUtilities.convertMouseEvent(this, event, _tabPane)); } @Override public Point getToolTipLocation(MouseEvent event) { return _tabPane.getToolTipLocation(SwingUtilities.convertMouseEvent(this, event, _tabPane)); } @Override public JToolTip createToolTip() { return _tabPane.createToolTip(); } } protected Color _closeButtonSelectedColor = new Color(255, 162, 165); protected Color _closeButtonColor = Color.BLACK; protected Color _popupColor = Color.BLACK; /** * Close button on the tab. */ public class TabCloseButton extends JButton implements MouseMotionListener, MouseListener, UIResource { public static final int CLOSE_BUTTON = 0; public static final int EAST_BUTTON = 1; public static final int WEST_BUTTON = 2; public static final int NORTH_BUTTON = 3; public static final int SOUTH_BUTTON = 4; public static final int LIST_BUTTON = 5; private int _type; private int _index = -1; private boolean _mouseOver = false; private boolean _mousePressed = false; /** * Resets the UI property to a value from the current look and feel. * * @see JComponent#updateUI */ @Override public void updateUI() { super.updateUI(); setMargin(new Insets(0, 0, 0, 0)); setBorder(BorderFactory.createEmptyBorder()); setFocusPainted(false); setFocusable(false); setRequestFocusEnabled(false); } public TabCloseButton() { this(CLOSE_BUTTON); } public TabCloseButton(int type) { addMouseMotionListener(this); addMouseListener(this); setFocusPainted(false); setFocusable(false); setType(type); } @Override public Dimension getPreferredSize() { return new Dimension(16, 16); } @Override public Dimension getMinimumSize() { return new Dimension(5, 5); } public int getIndex() { return _index; } public void setIndex(int index) { _index = index; } @Override public Dimension getMaximumSize() { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } @Override protected void paintComponent(Graphics g) { if (!isEnabled()) { setMouseOver(false); setMousePressed(false); } if (isMouseOver() && isMousePressed()) { g.setColor(UIDefaultsLookup.getColor("controlDkShadow")); g.drawLine(0, 0, getWidth() - 1, 0); g.drawLine(0, getHeight() - 2, 0, 1); g.setColor(UIDefaultsLookup.getColor("control")); g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2); g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1); } else if (isMouseOver()) { g.setColor(UIDefaultsLookup.getColor("control")); g.drawLine(0, 0, getWidth() - 1, 0); g.drawLine(0, getHeight() - 2, 0, 1); g.setColor(UIDefaultsLookup.getColor("controlDkShadow")); g.drawLine(getWidth() - 1, 1, getWidth() - 1, getHeight() - 2); g.drawLine(getWidth() - 1, getHeight() - 1, 0, getHeight() - 1); } g.setColor(UIDefaultsLookup.getColor("controlShadow").darker()); int centerX = getWidth() >> 1; int centerY = getHeight() >> 1; switch (getType()) { case CLOSE_BUTTON: if (isEnabled()) { g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3); g.drawLine(centerX - 4, centerY - 3, centerX + 2, centerY + 3); g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3); g.drawLine(centerX + 2, centerY - 3, centerX - 4, centerY + 3); } else { g.drawLine(centerX - 3, centerY - 3, centerX + 3, centerY + 3); g.drawLine(centerX + 3, centerY - 3, centerX - 3, centerY + 3); } break; case EAST_BUTTON: // // | // || // ||| // |||| // ||||* // |||| // ||| // || // | // { if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) { int x = centerX + 2, y = centerY; // start point. mark as * above if (isEnabled()) { g.drawLine(x - 4, y - 4, x - 4, y + 4); g.drawLine(x - 3, y - 3, x - 3, y + 3); g.drawLine(x - 2, y - 2, x - 2, y + 2); g.drawLine(x - 1, y - 1, x - 1, y + 1); g.drawLine(x, y, x, y); } else { g.drawLine(x - 4, y - 4, x, y); g.drawLine(x - 4, y - 4, x - 4, y + 4); g.drawLine(x - 4, y + 4, x, y); } } else { int x = centerX + 3, y = centerY - 2; // start point. mark as * above if (isEnabled()) { g.drawLine(x - 8, y, x, y); g.drawLine(x - 7, y + 1, x - 1, y + 1); g.drawLine(x - 6, y + 2, x - 2, y + 2); g.drawLine(x - 5, y + 3, x - 3, y + 3); g.drawLine(x - 4, y + 4, x - 4, y + 4); } else { g.drawLine(x - 8, y, x, y); g.drawLine(x - 8, y, x - 4, y + 4); g.drawLine(x - 4, y + 4, x, y); } } } break; case WEST_BUTTON: { // // | // || // ||| // |||| // *|||| // |||| // ||| // || // | // { if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) { int x = centerX - 3, y = centerY; // start point. mark as * above if (isEnabled()) { g.drawLine(x, y, x, y); g.drawLine(x + 1, y - 1, x + 1, y + 1); g.drawLine(x + 2, y - 2, x + 2, y + 2); g.drawLine(x + 3, y - 3, x + 3, y + 3); g.drawLine(x + 4, y - 4, x + 4, y + 4); } else { g.drawLine(x, y, x + 4, y - 4); g.drawLine(x, y, x + 4, y + 4); g.drawLine(x + 4, y - 4, x + 4, y + 4); } } else { int x = centerX - 5, y = centerY + 3; // start point. mark as * above if (isEnabled()) { g.drawLine(x, y, x + 8, y); g.drawLine(x + 1, y - 1, x + 7, y - 1); g.drawLine(x + 2, y - 2, x + 6, y - 2); g.drawLine(x + 3, y - 3, x + 5, y - 3); g.drawLine(x + 4, y - 4, x + 4, y - 4); } else { g.drawLine(x, y, x + 8, y); g.drawLine(x, y, x + 4, y - 4); g.drawLine(x + 8, y, x + 4, y - 4); } } } break; } case LIST_BUTTON: { int x = centerX + 2, y = centerY; // start point. mark as // * above g.drawLine(x - 6, y - 4, x - 6, y + 4); g.drawLine(x + 1, y - 4, x + 1, y + 4); g.drawLine(x - 6, y - 4, x + 1, y - 4); g.drawLine(x - 4, y - 2, x - 1, y - 2); g.drawLine(x - 4, y, x - 1, y); g.drawLine(x - 4, y + 2, x - 1, y + 2); g.drawLine(x - 6, y + 4, x + 1, y + 4); break; } } } @Override public boolean isFocusable() { return false; } @Override public void requestFocus() { } @Override public boolean isOpaque() { return false; } public boolean scrollsForward() { return getType() == EAST_BUTTON || getType() == SOUTH_BUTTON; } public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { if (!isEnabled()) return; setMouseOver(true); repaint(); } public void mouseClicked(MouseEvent e) { if (!isEnabled()) return; setMouseOver(true); setMousePressed(false); } public void mousePressed(MouseEvent e) { if (!isEnabled()) return; setMousePressed(true); repaint(); } public void mouseReleased(MouseEvent e) { if (!isEnabled()) return; setMousePressed(false); setMouseOver(false); } public void mouseEntered(MouseEvent e) { if (!isEnabled()) return; setMouseOver(true); repaint(); } public void mouseExited(MouseEvent e) { if (!isEnabled()) return; setMouseOver(false); setMousePressed(false); _tabScroller.tabPanel.repaint(); } public int getType() { return _type; } public void setType(int type) { _type = type; } protected boolean isMouseOver() { return _mouseOver; } protected void setMouseOver(boolean mouseOver) { _mouseOver = mouseOver; } protected boolean isMousePressed() { return _mousePressed; } protected void setMousePressed(boolean mousePressed) { _mousePressed = mousePressed; } } // Controller: event listeners /** * This inner class is marked &quot;public&quot; due to a compiler bug. This class should be * treated as a &quot;protected&quot; inner class. Instantiate it only within subclasses of * VsnetJideTabbedPaneUI. */ public class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent e) { JTabbedPane pane = (JTabbedPane) e.getSource(); String name = e.getPropertyName(); if ("mnemonicAt".equals(name)) { updateMnemonics(); pane.repaint(); } else if ("displayedMnemonicIndexAt".equals(name)) { pane.repaint(); } else if (name.equals("indexForTitle")) { int index = (Integer) e.getNewValue(); String title = _tabPane.getDisplayTitleAt(index); if (BasicHTML.isHTMLString(title)) { if (htmlViews == null) { // Initialize vector htmlViews = createHTMLVector(); } else { // Vector already exists View v = BasicHTML.createHTMLView(_tabPane, title); htmlViews.setElementAt(v, index); } } else { if (htmlViews != null && htmlViews.elementAt(index) != null) { htmlViews.setElementAt(null, index); } } updateMnemonics(); } else if (name.equals("tabLayoutPolicy")) { _tabPane.updateUI(); } else if (name.equals("closeTabAction")) { syncCloseAction(); } else if (name.equals(JideTabbedPane.PROPERTY_DRAG_OVER_DISABLED)) { _tabPane.updateUI(); } else if (name.equals(JideTabbedPane.PROPERTY_TAB_COLOR_PROVIDER)) { _tabPane.repaint(); } else if (name.equals(JideTabbedPane.BOLDACTIVETAB_PROPERTY)) { getTabPanel().invalidate(); _tabPane.invalidate(); if (scrollableTabLayoutEnabled()) { _tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height)); ensureActiveTabIsVisible(true); } } else if (name.equals(JideTabbedPane.PROPERTY_TAB_LEADING_COMPONENT)) { ensureCurrentLayout(); if (_tabLeadingComponent != null) { _tabLeadingComponent.setVisible(false); _tabPane.remove(_tabLeadingComponent); } _tabLeadingComponent = (Component) e.getNewValue(); if (_tabLeadingComponent != null) { _tabLeadingComponent.setVisible(true); _tabPane.add(_tabLeadingComponent); } _tabScroller.tabPanel.updateUI(); } else if (name.equals(JideTabbedPane.PROPERTY_TAB_TRAILING_COMPONENT)) { ensureCurrentLayout(); if (_tabTrailingComponent != null) { _tabTrailingComponent.setVisible(false); _tabPane.remove(_tabTrailingComponent); } _tabTrailingComponent = (Component) e.getNewValue(); if (_tabTrailingComponent != null) { _tabPane.add(_tabTrailingComponent); _tabTrailingComponent.setVisible(true); } _tabScroller.tabPanel.updateUI(); } else if (name.equals(JideTabbedPane.SHRINK_TAB_PROPERTY) || name.equals(JideTabbedPane.HIDE_IF_ONE_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_TAB_AREA_PROPERTY) || name.equals(JideTabbedPane.SHOW_TAB_CONTENT_PROPERTY) || name.equals(JideTabbedPane.BOX_STYLE_PROPERTY) || name.equals(JideTabbedPane.SHOW_ICONS_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_PROPERTY) || name.equals(JideTabbedPane.USE_DEFAULT_SHOW_ICONS_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.TAB_CLOSABLE_PROPERTY) || name.equals(JideTabbedPane.PROPERTY_TAB_SHAPE) || name.equals(JideTabbedPane.PROPERTY_COLOR_THEME) || name.equals(JideTabbedPane.PROPERTY_TAB_RESIZE_MODE) || name.equals(JideTabbedPane.SHOW_TAB_BUTTONS_PROPERTY)) { if ((name.equals(JideTabbedPane.USE_DEFAULT_SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY) || name.equals(JideTabbedPane.SHOW_CLOSE_BUTTON_ON_TAB_PROPERTY)) && isShowCloseButton() && isShowCloseButtonOnTab()) { ensureCloseButtonCreated(); } _tabPane.updateUI(); } } } protected void syncCloseAction() { Action action = _tabPane.getCloseAction(); ActionMap map = getActionMap(); Action closeAction = map.get("closeTabAction"); closeAction.putValue(Action.SHORT_DESCRIPTION, action.getValue(Action.SHORT_DESCRIPTION)); closeAction.putValue(Action.LONG_DESCRIPTION, action.getValue(Action.LONG_DESCRIPTION)); closeAction.putValue(Action.SMALL_ICON, action.getValue(Action.SMALL_ICON)); closeAction.setEnabled(action.isEnabled()); } /** * This inner class is marked &quot;public&quot; due to a compiler bug. This class should be * treated as a &quot;protected&quot; inner class. Instantiate it only within subclasses of * VsnetJideTabbedPaneUI. */ public class TabSelectionHandler implements ChangeListener { public void stateChanged(ChangeEvent e) { ensureCloseButtonCreated(); Runnable runnable = new Runnable() { public void run() { ensureActiveTabIsVisible(false); } }; SwingUtilities.invokeLater(runnable); } } public class TabFocusListener implements FocusListener { public void focusGained(FocusEvent e) { repaintSelectedTab(); } public void focusLost(FocusEvent e) { repaintSelectedTab(); } private void repaintSelectedTab() { if (_tabPane.getTabCount() > 0) { Rectangle rect = getTabBounds(_tabPane, _tabPane.getSelectedIndex()); if (rect != null) { _tabPane.repaint(rect); } } } } public class MouseMotionHandler extends MouseMotionAdapter { } /** * This inner class is marked &quot;public&quot; due to a compiler bug. This class should be * treated as a &quot;protected&quot; inner class. Instantiate it only within subclasses of * VsnetJideTabbedPaneUI. */ public class MouseHandler extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { if (!_tabPane.isEnabled()) { return; } if (SwingUtilities.isLeftMouseButton(e) || _tabPane.isRightClickSelect()) { int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY()); if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) { if (tabIndex == _tabPane.getSelectedIndex() && JideSwingUtilities.isAncestorOfFocusOwner(_tabPane)) { if (_tabPane.isRequestFocusEnabled()) { if (!_tabPane.requestFocusInWindow()) { _tabPane.requestFocus(); } } } else { _tabPane.setSelectedIndex(tabIndex); final Component comp = _tabPane.getComponentAt(tabIndex); if (!comp.isVisible() && SystemInfo.isJdk15Above() && !SystemInfo.isJdk6Above()) { comp.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent e) { // remove the listener comp.removeComponentListener(this); Component lastFocused = _tabPane.getLastFocusedComponent(comp); if (lastFocused != null) { // this code works in JDK6 but on JDK5 if (!lastFocused.requestFocusInWindow()) { lastFocused.requestFocus(); } } else if (_tabPane.isRequestFocusEnabled()) { if (!_tabPane.requestFocusInWindow()) { _tabPane.requestFocus(); } } } }); } else { Component lastFocused = _tabPane.getLastFocusedComponent(comp); if (lastFocused != null) { // this code works in JDK6 but on JDK5 if (!lastFocused.requestFocusInWindow()) { lastFocused.requestFocus(); } } else if (_tabPane.isRequestFocusEnabled()) { if (!_tabPane.requestFocusInWindow()) { _tabPane.requestFocus(); } } } } } } startEditing(e); // start editing tab } } public class MouseWheelHandler implements MouseWheelListener { public void mouseWheelMoved(MouseWheelEvent e) { if (scrollableTabLayoutEnabled() && e.getWheelRotation() != 0) { if (e.getWheelRotation() > 0) { for (int i = 0; i < e.getScrollAmount(); i++) { _tabScroller.scrollForward(_tabPane.getTabPlacement()); } } else if (e.getWheelRotation() < 0) { for (int i = 0; i < e.getScrollAmount(); i++) { _tabScroller.scrollBackward(_tabPane.getTabPlacement()); } } } } } private class ComponentHandler implements ComponentListener { public void componentResized(ComponentEvent e) { if (scrollableTabLayoutEnabled()) { _tabScroller.viewport.setViewSize(new Dimension(_tabPane.getWidth(), _tabScroller.viewport.getViewSize().height)); ensureActiveTabIsVisible(true); } } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } } /* GES 2/3/99: The container listener code was added to support HTML rendering of tab titles. Ideally, we would be able to listen for property changes when a tab is added or its text modified. At the moment there are no such events because the Beans spec doesn't allow 'indexed' property changes (i.e. tab 2's text changed from A to B). In order to get around this, we listen for tabs to be added or removed by listening for the container events. we then queue up a runnable (so the component has a chance to complete the add) which checks the tab title of the new component to see if it requires HTML rendering. The Views (one per tab title requiring HTML rendering) are stored in the htmlViews Vector, which is only allocated after the first time we run into an HTML tab. Note that this vector is kept in step with the number of pages, and nulls are added for those pages whose tab title do not require HTML rendering. This makes it easy for the paint and layout code to tell whether to invoke the HTML engine without having to check the string during time-sensitive operations. When we have added a way to listen for tab additions and changes to tab text, this code should be removed and replaced by something which uses that. */ private class ContainerHandler implements ContainerListener { public void componentAdded(ContainerEvent e) { JideTabbedPane tp = (JideTabbedPane) e.getContainer(); // updateTabPanel(); Component child = e.getChild(); if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) { return; } int index = tp.indexOfComponent(child); String title = tp.getDisplayTitleAt(index); boolean isHTML = BasicHTML.isHTMLString(title); if (isHTML) { if (htmlViews == null) { // Initialize vector htmlViews = createHTMLVector(); } else { // Vector already exists View v = BasicHTML.createHTMLView(tp, title); htmlViews.insertElementAt(v, index); } } else { // Not HTML if (htmlViews != null) { // Add placeholder htmlViews.insertElementAt(null, index); } // else nada! } if (_tabPane.isTabEditing()) { _tabPane.stopTabEditing(); } ensureCloseButtonCreated(); // ensureActiveTabIsVisible(true); } public void componentRemoved(ContainerEvent e) { JideTabbedPane tp = (JideTabbedPane) e.getContainer(); // updateTabPanel(); Component child = e.getChild(); if (child instanceof UIResource || child == tp.getTabLeadingComponent() || child == tp.getTabTrailingComponent()) { return; } // NOTE 4/15/2002 (joutwate): // This fix is implemented using client properties since there is // currently no IndexPropertyChangeEvent. Once // IndexPropertyChangeEvents have been added this code should be // modified to use it. Integer indexObj = (Integer) tp.getClientProperty("__index_to_remove__"); if (indexObj != null) { int index = indexObj; if (htmlViews != null && htmlViews.size() >= index) { htmlViews.removeElementAt(index); } } if (_tabPane.isTabEditing()) { _tabPane.stopTabEditing(); } ensureCloseButtonCreated(); // ensureActiveTabIsVisible(true); } } private Vector createHTMLVector() { Vector htmlViews = new Vector(); int count = _tabPane.getTabCount(); if (count > 0) { for (int i = 0; i < count; i++) { String title = _tabPane.getDisplayTitleAt(i); if (BasicHTML.isHTMLString(title)) { htmlViews.addElement(BasicHTML.createHTMLView(_tabPane, title)); } else { htmlViews.addElement(null); } } } return htmlViews; } @Override public Component getTabPanel() { if (scrollableTabLayoutEnabled()) return _tabScroller.tabPanel; else return _tabPane; } static class AbstractTab { int width; int id; public void copy(AbstractTab tab) { this.width = tab.width; this.id = tab.id; } } public static class TabSpaceAllocator { static final int startOffset = 4; private Insets insets = null; static final int tabWidth = 24; static final int textIconGap = 8; private AbstractTab tabs[]; private void setInsets(Insets insets) { this.insets = (Insets) insets.clone(); } private void init(Rectangle rects[], Insets insets) { setInsets(insets); tabs = new AbstractTab[rects.length]; // fill up internal datastructure for (int i = 0; i < rects.length; i++) { tabs[i] = new AbstractTab(); tabs[i].id = i; tabs[i].width = rects[i].width; } tabSort(); } private void bestfit(AbstractTab tabs[], int freeWidth, int startTab) { int tabCount = tabs.length; int worstWidth; int currentTabWidth; int initialPos; currentTabWidth = tabs[startTab].width; initialPos = startTab; if (startTab == tabCount - 1) { // directly fill as worst case tabs[startTab].width = freeWidth; return; } worstWidth = freeWidth / (tabCount - startTab); while (currentTabWidth < worstWidth) { freeWidth -= currentTabWidth; if (++startTab < tabCount - 1) { currentTabWidth = tabs[startTab].width; } else { tabs[startTab].width = worstWidth; return; } } if (startTab == initialPos) { // didn't find anything smaller for (int i = startTab; i < tabCount; i++) { tabs[i].width = worstWidth; } } else if (startTab < tabCount - 1) { bestfit(tabs, freeWidth, startTab); } } // bubble sort for now private void tabSort() { int tabCount = tabs.length; AbstractTab tempTab = new AbstractTab(); for (int i = 0; i < tabCount - 1; i++) { for (int j = i + 1; j < tabCount; j++) { if (tabs[i].width > tabs[j].width) { tempTab.copy(tabs[j]); tabs[j].copy(tabs[i]); tabs[i].copy(tempTab); } } } } // directly modify the rects private void outpush(Rectangle rects[]) { for (int i = 0; i < tabs.length; i++) { rects[tabs[i].id].width = tabs[i].width; } rects[0].x = startOffset; for (int i = 1; i < rects.length; i++) { rects[i].x = rects[i - 1].x + rects[i - 1].width; } } public void reArrange(Rectangle rects[], Insets insets, int totalAvailableSpace) { init(rects, insets); bestfit(tabs, totalAvailableSpace, 0); outpush(rects); clearup(); } private void clearup() { for (int i = 0; i < tabs.length; i++) { tabs[i] = null; } tabs = null; } } public void ensureActiveTabIsVisible(boolean scrollLeft) { if (_tabPane == null || _tabPane.getWidth() == 0) { return; } if (scrollableTabLayoutEnabled()) { ensureCurrentLayout(); if (scrollLeft && _rects.length > 0) { _tabScroller.viewport.setViewPosition(new Point(0, 0)); _tabScroller.tabPanel.scrollRectToVisible(_rects[0]); } int index = _tabPane.getSelectedIndex(); if ((!scrollLeft || index != 0) && index < _rects.length && index != -1) { if (index == 0) { _tabScroller.viewport.setViewPosition(new Point(0, 0)); } else { if (index == _rects.length - 1) { // last one, scroll to the end Rectangle lastRect = _rects[index]; lastRect.width = _tabScroller.tabPanel.getWidth() - lastRect.x; _tabScroller.tabPanel.scrollRectToVisible(lastRect); } else if (index == 0) { // first one, scroll to the front Rectangle firstRect = _rects[index]; firstRect.x = 0; _tabScroller.tabPanel.scrollRectToVisible(firstRect); } else { _tabScroller.tabPanel.scrollRectToVisible(_rects[index]); } } _tabScroller.tabPanel.getParent().doLayout(); } _tabPane.revalidate(); _tabPane.repaint(); } } protected boolean isShowCloseButtonOnTab() { if (_tabPane.isUseDefaultShowCloseButtonOnTab()) { if (_showCloseButtonOnTab) { return true; } else { return false; } } else if (_tabPane.isShowCloseButtonOnTab()) { return true; } else { return false; } } protected boolean isShowCloseButton() { if (_tabPane.isShowCloseButton()) { return true; } else { return false; } } public void ensureCloseButtonCreated() { if (isShowCloseButton() && isShowCloseButtonOnTab() && scrollableTabLayoutEnabled()) { if (_closeButtons == null) { _closeButtons = new TabCloseButton[_tabPane.getTabCount()]; } else if (_closeButtons.length > _tabPane.getTabCount()) { TabCloseButton[] temp = new TabCloseButton[_tabPane .getTabCount()]; System.arraycopy(_closeButtons, 0, temp, 0, temp.length); for (int i = temp.length; i < _closeButtons.length; i++) { TabCloseButton tabCloseButton = _closeButtons[i]; _tabScroller.tabPanel.remove(tabCloseButton); } _closeButtons = temp; } else if (_closeButtons.length < _tabPane.getTabCount()) { TabCloseButton[] temp = new TabCloseButton[_tabPane .getTabCount()]; System.arraycopy(_closeButtons, 0, temp, 0, _closeButtons.length); _closeButtons = temp; } ActionMap am = getActionMap(); for (int i = 0; i < _closeButtons.length; i++) { TabCloseButton closeButton = _closeButtons[i]; if (closeButton == null) { closeButton = createNoFocusButton(TabCloseButton.CLOSE_BUTTON); closeButton.setName("TabClose"); _closeButtons[i] = closeButton; closeButton.setBounds(0, 0, 0, 0); closeButton.setAction(am.get("closeTabAction")); _tabScroller.tabPanel.add(closeButton); } closeButton.setIndex(i); } } } protected boolean isShowTabButtons() { if (_tabPane.getTabCount() == 0) { return false; } else { return _tabPane.isShowTabArea() && _tabPane.isShowTabButtons(); } } protected boolean isShrinkTabs() { if (_tabPane.getTabCount() == 0) { return false; } else { return _tabPane.getTabResizeMode() == JideTabbedPane.RESIZE_MODE_FIT; } } protected TabEditor _tabEditor; protected boolean _isEditing; protected int _editingTab = -1; protected String _oldValue; protected String _oldPrefix; protected String _oldPostfix; @Override public boolean isTabEditing() { return _isEditing; } protected TabEditor createDefaultTabEditor() { TabEditor editor = new TabEditor(); editor.getDocument().addDocumentListener(this); editor.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { if (_tabPane.isTabEditing()) { _tabPane.stopTabEditing(); } } }); editor.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { _tabPane.stopTabEditing(); } }); editor.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (_isEditing && (e.getKeyCode() == KeyEvent.VK_ESCAPE)) { if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) { _tabPane.setTitleAt(_editingTab, _oldValue); } _tabPane.cancelTabEditing(); } } }); editor.setFont(_tabPane.getFont()); return editor; } @Override public void stopTabEditing() { if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) { _tabPane.setTitleAt(_editingTab, _oldPrefix + _tabEditor.getText() + _oldPostfix); } cancelTabEditing(); } @Override public void cancelTabEditing() { if (_tabEditor != null) { _isEditing = false; ((Container) getTabPanel()).remove(_tabEditor); if (_editingTab >= 0 && _editingTab < _tabPane.getTabCount()) { Rectangle tabRect = _tabPane.getBoundsAt(_editingTab); getTabPanel().repaint(tabRect.x, tabRect.y, tabRect.width, tabRect.height); } else { getTabPanel().repaint(); } _tabPane.requestFocusInWindow(); _editingTab = -1; _oldValue = null; } } @Override public boolean editTabAt(int tabIndex) { if (_isEditing) { return false; } if (_tabEditor == null) _tabEditor = createDefaultTabEditor(); if (_tabEditor != null) { prepareEditor(_tabEditor, tabIndex); ((Container) getTabPanel()).add(_tabEditor); Rectangle tabsTextBoundsAt = getTabsTextBoundsAt(tabIndex); if (tabsTextBoundsAt.isEmpty()) { return false; } _tabEditor.setBounds(SwingUtilities.convertRectangle(_tabPane, tabsTextBoundsAt, getTabPanel())); _tabEditor.invalidate(); _tabEditor.validate(); _editingTab = tabIndex; _isEditing = true; getTabPanel().repaint(); _tabEditor.requestFocusInWindow(); _tabEditor.selectAll(); return true; } return false; } @Override public int getEditingTabIndex() { return _editingTab; } protected void prepareEditor(TabEditor e, int tabIndex) { _oldValue = _tabPane.getTitleAt(tabIndex); if (_oldValue.startsWith("<HTML>") && _oldValue.endsWith("/HTML>")) { _oldPrefix = "<HTML>"; _oldPostfix = "</HTML>"; String title = _oldValue.substring("<HTML>".length(), _oldValue.length() - "</HTML>".length()); if (title.startsWith("<B>") && title.endsWith("/B>")) { title = title.substring("<B>".length(), title.length() - "</B>".length()); _oldPrefix += "<B>"; _oldPostfix = "</B>" + _oldPostfix; } e.setText(title); } else { _oldPrefix = ""; _oldPostfix = ""; e.setText(_oldValue); } e.selectAll(); e.setForeground(_tabPane.getForegroundAt(tabIndex)); } protected Rectangle getTabsTextBoundsAt(int tabIndex) { Rectangle tabRect = _tabPane.getBoundsAt(tabIndex); Rectangle iconRect = new Rectangle(), textRect = new Rectangle(); String title = _tabPane.getDisplayTitleAt(tabIndex); if (title == null || title.length() < 4) { title = " "; } Icon icon = _tabPane.getIconForTab(tabIndex); Font font = _tabPane.getFont(); if (tabIndex == _tabPane.getSelectedIndex() && _tabPane.isBoldActiveTab()) { font = font.deriveFont(Font.BOLD); } SwingUtilities.layoutCompoundLabel(_tabPane, _tabPane.getGraphics().getFontMetrics(font), title, icon, SwingUtilities.CENTER, SwingUtilities.CENTER, SwingUtilities.CENTER, SwingUtilities.TRAILING, tabRect, iconRect, textRect, icon == null ? 0 : _textIconGap); if (_tabPane.getTabPlacement() == TOP || _tabPane.getTabPlacement() == BOTTOM) { iconRect.x = tabRect.x + _iconMargin; textRect.x = (icon != null ? iconRect.x + iconRect.width + _textIconGap : tabRect.x + _textPadding); textRect.width += 2; } else { iconRect.y = tabRect.y + _iconMargin; textRect.y = (icon != null ? iconRect.y + iconRect.height + _textIconGap : tabRect.y + _textPadding); iconRect.x = tabRect.x + 2; textRect.x = tabRect.x + 2; textRect.height += 2; } return textRect; } private void updateTab() { if (_isEditing) { getTabPanel().invalidate(); _tabEditor.validate(); _tabEditor.repaint(); getTabPanel().repaint(); } } public void insertUpdate(DocumentEvent e) { updateTab(); } public void removeUpdate(DocumentEvent e) { updateTab(); } public void changedUpdate(DocumentEvent e) { updateTab(); } protected class TabEditor extends JTextField implements UIResource { TabEditor() { setBorder(BorderFactory.createEmptyBorder()); } public boolean stopEditing() { return true; } } public void startEditing(MouseEvent e) { int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY()); if (!e.isPopupTrigger() && tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex) && _tabPane.isTabEditingAllowed() && (e.getClickCount() == 2)) { e.consume(); _tabPane.editTabAt(tabIndex); } if (e.getClickCount() == 1) { if (_tabPane.isTabEditing()) { _tabPane.stopTabEditing(); } } } public ThemePainter getPainter() { return _painter; } private class DragOverTimer extends Timer implements ActionListener { private int _index; public DragOverTimer(int index) { super(500, null); _index = index; addActionListener(this); setRepeats(false); } public void actionPerformed(ActionEvent e) { if (_tabPane.getTabCount() == 0) { return; } if (_index == _tabPane.getSelectedIndex()) { if (_tabPane.isRequestFocusEnabled()) { _tabPane.requestFocusInWindow(); _tabPane.repaint(getTabBounds(_tabPane, _index)); } } else { if (_tabPane.isRequestFocusEnabled()) { _tabPane.requestFocusInWindow(); } _tabPane.setSelectedIndex(_index); } stop(); } } private class DropListener implements DropTargetListener { private DragOverTimer _timer; int _index = -1; public DropListener() { } public void dragEnter(DropTargetDragEvent dtde) { } public void dragOver(DropTargetDragEvent dtde) { if (!_tabPane.isEnabled()) { return; } int tabIndex = getTabAtLocation(dtde.getLocation().x, dtde.getLocation().y); if (tabIndex >= 0 && _tabPane.isEnabledAt(tabIndex)) { if (tabIndex == _tabPane.getSelectedIndex()) { // selected already, do nothing } else if (tabIndex == _index) { // same tab, timer has started } else { stopTimer(); startTimer(tabIndex); _index = tabIndex; // save the index } } else { stopTimer(); } } private void startTimer(int tabIndex) { _timer = new DragOverTimer(tabIndex); _timer.start(); } private void stopTimer() { if (_timer != null) { _timer.stop(); _timer = null; _index = -1; } } public void dropActionChanged(DropTargetDragEvent dtde) { } public void dragExit(DropTargetEvent dte) { stopTimer(); } public void drop(DropTargetDropEvent dtde) { stopTimer(); } } protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { Rectangle tabRect = rects[tabIndex]; if (_tabPane.hasFocus() && isSelected) { int x, y, w, h; g.setColor(_focus); switch (tabPlacement) { case LEFT: x = tabRect.x + 3; y = tabRect.y + 3; w = tabRect.width - 5; h = tabRect.height - 6 - getTabGap(); break; case RIGHT: x = tabRect.x + 2; y = tabRect.y + 3; w = tabRect.width - 5; h = tabRect.height - 6 - getTabGap(); break; case BOTTOM: x = tabRect.x + 3; y = tabRect.y + 2; w = tabRect.width - 6 - getTabGap(); h = tabRect.height - 5; break; case TOP: default: x = tabRect.x + 3; y = tabRect.y + 3; w = tabRect.width - 6 - getTabGap(); h = tabRect.height - 5; } BasicGraphicsUtils.drawDashedRect(g, x, y, w, h); } } protected boolean isRoundedCorner() { return "true".equals(SecurityUtils.getProperty("shadingtheme", "false")); } protected int getTabShape() { return _tabPane.getTabShape(); } protected int getTabResizeMode() { return _tabPane.getTabResizeMode(); } protected int getColorTheme() { return _tabPane.getColorTheme(); } // for debug purpose final protected boolean PAINT_TAB = true; final protected boolean PAINT_TAB_BORDER = true; final protected boolean PAINT_TAB_BACKGROUND = true; final protected boolean PAINT_TABAREA = true; final protected boolean PAINT_CONTENT_BORDER = true; final protected boolean PAINT_CONTENT_BORDER_EDGE = true; protected int getLeftMargin() { if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) { return OFFICE2003_LEFT_MARGIN; } else if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) { return EXCEL_LEFT_MARGIN; } else { return DEFAULT_LEFT_MARGIN; } } protected int getTabGap() { if (getTabShape() == JideTabbedPane.SHAPE_OFFICE2003) { return 4; } else { return 0; } } protected int getLayoutSize() { int tabShape = getTabShape(); if (tabShape == JideTabbedPane.SHAPE_EXCEL) { return EXCEL_LEFT_MARGIN; } else if (tabShape == JideTabbedPane.SHAPE_ECLIPSE3X) { return 15; } else if (_tabPane.getTabShape() == JideTabbedPane.SHAPE_FLAT || _tabPane.getTabShape() == JideTabbedPane.SHAPE_ROUNDED_FLAT) { return 2; } else if (tabShape == JideTabbedPane.SHAPE_WINDOWS || tabShape == JideTabbedPane.SHAPE_WINDOWS_SELECTED) { return 6; } else { return 0; } } protected int getTabRightPadding() { if (getTabShape() == JideTabbedPane.SHAPE_EXCEL) { return 4; } else { return 0; } } protected MouseListener createMouseListener() { if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) { return new RolloverMouseHandler(); } else { return new MouseHandler(); } } protected MouseWheelListener createMouseWheelListener() { return new MouseWheelHandler(); } protected MouseMotionListener createMouseMotionListener() { if (getTabShape() == JideTabbedPane.SHAPE_WINDOWS || getTabShape() == JideTabbedPane.SHAPE_WINDOWS_SELECTED) { return new RolloverMouseMotionHandler(); } else { return new MouseMotionHandler(); } } public class DefaultMouseMotionHandler extends MouseMotionAdapter { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); int tabIndex = getTabAtLocation(e.getX(), e.getY()); if (tabIndex != _indexMouseOver) { _indexMouseOver = tabIndex; _tabPane.repaint(); } } } public class DefaultMouseHandler extends BasicJideTabbedPaneUI.MouseHandler { @Override public void mousePressed(MouseEvent e) { super.mousePressed(e); } @Override public void mouseEntered(MouseEvent e) { super.mouseEntered(e); int tabIndex = getTabAtLocation(e.getX(), e.getY()); _mouseEnter = true; _indexMouseOver = tabIndex; _tabPane.repaint(); } @Override public void mouseExited(MouseEvent e) { super.mouseExited(e); _indexMouseOver = -1; _mouseEnter = false; _tabPane.repaint(); } } public class RolloverMouseMotionHandler extends MouseMotionAdapter { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY()); if (tabIndex != _indexMouseOver) { _indexMouseOver = tabIndex; _tabPane.repaint(); } } } public class RolloverMouseHandler extends BasicJideTabbedPaneUI.MouseHandler { @Override public void mouseEntered(MouseEvent e) { super.mouseEntered(e); int tabIndex = tabForCoordinate(_tabPane, e.getX(), e.getY()); _mouseEnter = true; _indexMouseOver = tabIndex; _tabPane.repaint(); } @Override public void mouseExited(MouseEvent e) { super.mouseExited(e); _indexMouseOver = -1; _mouseEnter = false; _tabPane.repaint(); } } protected boolean isTabLeadingComponentVisible() { return _tabPane.isTabShown() && _tabLeadingComponent != null && _tabLeadingComponent.isVisible(); } protected boolean isTabTrailingComponentVisible() { return _tabPane.isTabShown() && _tabTrailingComponent != null && _tabTrailingComponent.isVisible(); } protected boolean isTabTopVisible(int tabPlacement) { switch (tabPlacement) { case LEFT: case RIGHT: return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)) || (isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().width > calculateMaxTabWidth(tabPlacement)); case TOP: case BOTTOM: default: return (isTabLeadingComponentVisible() && _tabLeadingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)) || (isTabTrailingComponentVisible() && _tabTrailingComponent.getPreferredSize().height > calculateMaxTabHeight(tabPlacement)); } } protected boolean showFocusIndicator() { return _tabPane.hasFocusComponent() && _showFocusIndicator; } private int getNumberOfTabButtons() { int numberOfButtons = (!isShowTabButtons() || isShrinkTabs()) ? 1 : 4; if (!isShowCloseButton() || isShowCloseButtonOnTab()) { numberOfButtons--; } return numberOfButtons; } }
false
true
public void layoutContainer(Container parent) { int tabPlacement = _tabPane.getTabPlacement(); int tabCount = _tabPane.getTabCount(); Insets insets = _tabPane.getInsets(); int selectedIndex = _tabPane.getSelectedIndex(); Component visibleComponent = getVisibleComponent(); boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); calculateLayoutInfo(); if (selectedIndex < 0) { if (visibleComponent != null) { // The last tab was removed, so remove the component setVisibleComponent(null); } } else { Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89 boolean shouldChangeFocus = false; // In order to allow programs to use a single component // as the display for multiple tabs, we will not change // the visible compnent if the currently selected tab // has a null component. This is a bit dicey, as we don't // explicitly state we support this in the spec, but since // programs are now depending on this, we're making it work. // if (selectedComponent != null) { if (selectedComponent != visibleComponent && visibleComponent != null) { if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) { shouldChangeFocus = true; } } setVisibleComponent(selectedComponent); } int tx, ty, tw, th; // tab area bounds int cx, cy, cw, ch; // content area bounds Insets contentInsets = getContentBorderInsets(tabPlacement); Rectangle bounds = _tabPane.getBounds(); int numChildren = _tabPane.getComponentCount(); Dimension lsize = new Dimension(0, 0); Dimension tsize = new Dimension(0, 0); if (isTabLeadingComponentVisible()) { lsize = _tabLeadingComponent.getSize(); } if (isTabTrailingComponentVisible()) { tsize = _tabTrailingComponent.getSize(); } if (numChildren > 0) { switch (tabPlacement) { case LEFT: // calculate tab area bounds tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = insets.left; ty = insets.top; if (isTabLeadingComponentVisible()) { ty += lsize.height; th -= lsize.height; if (lsize.width > tw) { tw = lsize.width; } } if (isTabTrailingComponentVisible()) { th -= tsize.height; if (tsize.width > tw) { tw = tsize.width; } } // calculate content area bounds cx = tx + tw + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case RIGHT: // calculate tab area bounds tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = bounds.width - insets.right - tw; ty = insets.top; if (isTabLeadingComponentVisible()) { ty += lsize.height; th -= lsize.height; if (lsize.width > tw) { tw = lsize.width; tx = bounds.width - insets.right - tw; } } if (isTabTrailingComponentVisible()) { th -= tsize.height; if (tsize.width > tw) { tw = tsize.width; tx = bounds.width - insets.right - tw; } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case BOTTOM: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); tx = insets.left; ty = bounds.height - insets.bottom - th; if (leftToRight) { if (isTabLeadingComponentVisible()) { tx += lsize.width; tw -= lsize.width; if (lsize.height > th) { th = lsize.height; ty = bounds.height - insets.bottom - th; } } if (isTabTrailingComponentVisible()) { tw -= tsize.width; if (tsize.height > th) { th = tsize.height; ty = bounds.height - insets.bottom - th; } } } else { if (isTabTrailingComponentVisible()) { tx += tsize.width; tw -= tsize.width; if (tsize.height > th) { th = tsize.height; ty = bounds.height - insets.bottom - th; } } if (isTabLeadingComponentVisible()) { tw -= lsize.width; if (lsize.height > th) { th = lsize.height; ty = bounds.height - insets.bottom - th; } } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; break; case TOP: default: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); tx = insets.left; ty = insets.top; if (leftToRight) { if (isTabLeadingComponentVisible()) { tx += lsize.width; tw -= lsize.width; if (lsize.height > th) { th = lsize.height; } } if (isTabTrailingComponentVisible()) { tw -= tsize.width; if (tsize.height > th) { th = tsize.height; } } } else { if (isTabTrailingComponentVisible()) { tx += tsize.width; tw -= tsize.width; if (tsize.height > th) { th = tsize.height; } } if (isTabLeadingComponentVisible()) { tw -= lsize.width; if (lsize.height > th) { th = lsize.height; } } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + th + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; } // if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) { // if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) { // int numberOfButtons = isShrinkTabs() ? 1 : 4; // if (tw < _rects[0].width + numberOfButtons * _buttonSize) { // return; // } // } // } // else { // if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) { // int numberOfButtons = isShrinkTabs() ? 1 : 4; // if (th < _rects[0].height + numberOfButtons * _buttonSize) { // return; // } // } // } for (int i = 0; i < numChildren; i++) { Component child = _tabPane.getComponent(i); if (child instanceof ScrollableTabViewport) { JViewport viewport = (JViewport) child; // Rectangle viewRect = viewport.getViewRect(); int vw = tw; int vh = th; int numberOfButtons = getNumberOfTabButtons(); switch (tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height; if (totalTabHeight > th || isShowTabButtons()) { numberOfButtons += 3; // Allow space for scrollbuttons vh = Math.max(th - _buttonSize * numberOfButtons, 0); // if (totalTabHeight - viewRect.y <= vh) { // // Scrolled to the end, so ensure the // // viewport size is // // such that the scroll offset aligns // // with a tab // vh = totalTabHeight - viewRect.y; // } } else { // Allow space for scrollbuttons vh = Math.max(th - _buttonSize * numberOfButtons, 0); } if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) { vh += getLayoutSize(); } break; case BOTTOM: case TOP: default: int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width; if (isShowTabButtons() || totalTabWidth > tw) { numberOfButtons += 3; // Need to allow space for scrollbuttons vw = Math.max(tw - _buttonSize * numberOfButtons, 0); // if (totalTabWidth - viewRect.x <= vw) { // // Scrolled to the end, so ensure the // // viewport size is // // such that the scroll offset aligns // // with a tab // vw = totalTabWidth - viewRect.x; // } } else { // Allow space for scrollbuttons vw = Math.max(tw - _buttonSize * numberOfButtons, 0); } if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) { vw += getLayoutSize(); } break; } child.setBounds(tx, ty, vw, vh); } else if (child instanceof TabCloseButton) { TabCloseButton scrollbutton = (TabCloseButton) child; if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) { Dimension bsize = scrollbutton.getPreferredSize(); int bx = 0; int by = 0; int bw = bsize.width; int bh = bsize.height; boolean visible = false; switch (tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height; if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) { int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON; scrollbutton.setType(dir); switch (dir) { case TabCloseButton.CLOSE_BUTTON: if (isShowCloseButton()) { visible = true; by = bounds.height - insets.top - bsize.height - 5; } else { visible = false; by = 0; } break; case TabCloseButton.LIST_BUTTON: visible = true; by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; case TabCloseButton.EAST_BUTTON: visible = !isShrinkTabs(); by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; case TabCloseButton.WEST_BUTTON: visible = !isShrinkTabs(); by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; } bx = tx + 2; } else { int dir = scrollbutton.getType(); scrollbutton.setType(dir); if (dir == TabCloseButton.CLOSE_BUTTON) { if (isShowCloseButton()) { visible = true; by = bounds.height - insets.top - bsize.height - 5; } else { visible = false; by = 0; } bx = tx + 2; } } if (isTabTrailingComponentVisible()) { by = by - tsize.height; } int temp = -1; if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().width >= _rects[0].width) { if (tabPlacement == LEFT) { bx += _tabLeadingComponent.getSize().width - _rects[0].width; temp = _tabLeadingComponent.getSize().width; } } } if (isTabTrailingComponentVisible()) { if (_tabTrailingComponent.getSize().width >= _rects[0].width && temp < _tabTrailingComponent.getSize().width) { if (tabPlacement == LEFT) { bx += _tabTrailingComponent.getSize().width - _rects[0].width; } } } break; case TOP: case BOTTOM: default: int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width; if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabWidth > tw)) { int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON // NoFocusButton.WEST_BUTTON; scrollbutton.setType(dir); switch (dir) { case TabCloseButton.CLOSE_BUTTON: if (isShowCloseButton()) { visible = true; bx = bounds.width - insets.left - bsize.width - 5; } else { visible = false; bx = 0; } break; case TabCloseButton.LIST_BUTTON: visible = true; bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; case TabCloseButton.EAST_BUTTON: visible = !isShrinkTabs(); bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; case TabCloseButton.WEST_BUTTON: visible = !isShrinkTabs(); bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; } by = ((th - bsize.height) >> 1) + ty; } else { int dir = scrollbutton.getType(); scrollbutton.setType(dir); if (dir == TabCloseButton.CLOSE_BUTTON) { if (isShowCloseButton()) { visible = true; bx = bounds.width - insets.left - bsize.width - 5; } else { visible = false; bx = 0; } by = ((th - bsize.height) >> 1) + ty; } } if (isTabTrailingComponentVisible()) { bx -= tsize.width; } temp = -1; if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().height >= _rects[0].height) { if (tabPlacement == TOP) { by = ty + 2 + _tabLeadingComponent.getSize().height - _rects[0].height; temp = _tabLeadingComponent.getSize().height; } else { by = ty + 2; } } } if (isTabTrailingComponentVisible()) { if (_tabTrailingComponent.getSize().height >= _rects[0].height && temp < _tabTrailingComponent.getSize().height) { if (tabPlacement == TOP) { by = ty + 2 + _tabTrailingComponent.getSize().height - _rects[0].height; } else { by = ty + 2; } } } } child.setVisible(visible); if (visible) { child.setBounds(bx, by, bw, bh); } } else { scrollbutton.setBounds(0, 0, 0, 0); } } else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) { if (_tabPane.isShowTabContent()) { // All content children... child.setBounds(cx, cy, cw, ch); } else { child.setBounds(0, 0, 0, 0); } } } if (leftToRight) { if (isTabLeadingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height); break; case RIGHT: _tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height); break; case BOTTOM: _tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height); break; case TOP: default: _tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height); break; } } if (isTabTrailingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height); break; case RIGHT: _tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height); break; case BOTTOM: _tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height); break; case TOP: default: _tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height); break; } } } else { if (isTabTrailingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height); break; case RIGHT: _tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height); break; case BOTTOM: _tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height); break; case TOP: default: _tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height); break; } } if (isTabLeadingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height); break; case RIGHT: _tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height); break; case BOTTOM: _tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height); break; case TOP: default: _tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height); break; } } } if (shouldChangeFocus) { if (!requestFocusForVisibleComponent()) { if (!_tabPane.requestFocusInWindow()) { _tabPane.requestFocus(); } } } } } }
public void layoutContainer(Container parent) { int tabPlacement = _tabPane.getTabPlacement(); int tabCount = _tabPane.getTabCount(); Insets insets = _tabPane.getInsets(); int selectedIndex = _tabPane.getSelectedIndex(); Component visibleComponent = getVisibleComponent(); boolean leftToRight = _tabPane.getComponentOrientation().isLeftToRight(); calculateLayoutInfo(); if (selectedIndex < 0) { if (visibleComponent != null) { // The last tab was removed, so remove the component setVisibleComponent(null); } } else { Component selectedComponent = selectedIndex >= _tabPane.getTabCount() ? null : _tabPane.getComponentAt(selectedIndex); // check for range because of a change in JDK1.6-rc-b89 boolean shouldChangeFocus = false; // In order to allow programs to use a single component // as the display for multiple tabs, we will not change // the visible compnent if the currently selected tab // has a null component. This is a bit dicey, as we don't // explicitly state we support this in the spec, but since // programs are now depending on this, we're making it work. // if (selectedComponent != null) { if (selectedComponent != visibleComponent && visibleComponent != null) { if (JideSwingUtilities.isAncestorOfFocusOwner(visibleComponent) && _tabPane.isAutoRequestFocus()) { shouldChangeFocus = true; } } setVisibleComponent(selectedComponent); } int tx, ty, tw, th; // tab area bounds int cx, cy, cw, ch; // content area bounds Insets contentInsets = getContentBorderInsets(tabPlacement); Rectangle bounds = _tabPane.getBounds(); int numChildren = _tabPane.getComponentCount(); Dimension lsize = new Dimension(0, 0); Dimension tsize = new Dimension(0, 0); if (isTabLeadingComponentVisible()) { lsize = _tabLeadingComponent.getSize(); } if (isTabTrailingComponentVisible()) { tsize = _tabTrailingComponent.getSize(); } if (numChildren > 0) { switch (tabPlacement) { case LEFT: // calculate tab area bounds tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = insets.left; ty = insets.top; if (isTabLeadingComponentVisible()) { ty += lsize.height; th -= lsize.height; if (lsize.width > tw) { tw = lsize.width; } } if (isTabTrailingComponentVisible()) { th -= tsize.height; if (tsize.width > tw) { tw = tsize.width; } } // calculate content area bounds cx = tx + tw + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case RIGHT: // calculate tab area bounds tw = calculateTabAreaHeight(TOP, _runCount, _maxTabWidth); th = bounds.height - insets.top - insets.bottom; tx = bounds.width - insets.right - tw; ty = insets.top; if (isTabLeadingComponentVisible()) { ty += lsize.height; th -= lsize.height; if (lsize.width > tw) { tw = lsize.width; tx = bounds.width - insets.right - tw; } } if (isTabTrailingComponentVisible()) { th -= tsize.height; if (tsize.width > tw) { tw = tsize.width; tx = bounds.width - insets.right - tw; } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - tw - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - contentInsets.top - contentInsets.bottom; break; case BOTTOM: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); tx = insets.left; ty = bounds.height - insets.bottom - th; if (leftToRight) { if (isTabLeadingComponentVisible()) { tx += lsize.width; tw -= lsize.width; if (lsize.height > th) { th = lsize.height; ty = bounds.height - insets.bottom - th; } } if (isTabTrailingComponentVisible()) { tw -= tsize.width; if (tsize.height > th) { th = tsize.height; ty = bounds.height - insets.bottom - th; } } } else { if (isTabTrailingComponentVisible()) { tx += tsize.width; tw -= tsize.width; if (tsize.height > th) { th = tsize.height; ty = bounds.height - insets.bottom - th; } } if (isTabLeadingComponentVisible()) { tw -= lsize.width; if (lsize.height > th) { th = lsize.height; ty = bounds.height - insets.bottom - th; } } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; break; case TOP: default: // calculate tab area bounds tw = bounds.width - insets.left - insets.right; th = calculateTabAreaHeight(tabPlacement, _runCount, _maxTabHeight); tx = insets.left; ty = insets.top; if (leftToRight) { if (isTabLeadingComponentVisible()) { tx += lsize.width; tw -= lsize.width; if (lsize.height > th) { th = lsize.height; } } if (isTabTrailingComponentVisible()) { tw -= tsize.width; if (tsize.height > th) { th = tsize.height; } } } else { if (isTabTrailingComponentVisible()) { tx += tsize.width; tw -= tsize.width; if (tsize.height > th) { th = tsize.height; } } if (isTabLeadingComponentVisible()) { tw -= lsize.width; if (lsize.height > th) { th = lsize.height; } } } // calculate content area bounds cx = insets.left + contentInsets.left; cy = insets.top + th + contentInsets.top; cw = bounds.width - insets.left - insets.right - contentInsets.left - contentInsets.right; ch = bounds.height - insets.top - insets.bottom - th - contentInsets.top - contentInsets.bottom; } // if (tabPlacement == JideTabbedPane.TOP || tabPlacement == JideTabbedPane.BOTTOM) { // if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) { // int numberOfButtons = isShrinkTabs() ? 1 : 4; // if (tw < _rects[0].width + numberOfButtons * _buttonSize) { // return; // } // } // } // else { // if (getTabResizeMode() != JideTabbedPane.RESIZE_MODE_FIT) { // int numberOfButtons = isShrinkTabs() ? 1 : 4; // if (th < _rects[0].height + numberOfButtons * _buttonSize) { // return; // } // } // } for (int i = 0; i < numChildren; i++) { Component child = _tabPane.getComponent(i); if (child instanceof ScrollableTabViewport) { JViewport viewport = (JViewport) child; // Rectangle viewRect = viewport.getViewRect(); int vw = tw; int vh = th; int numberOfButtons = getNumberOfTabButtons(); switch (tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height; if (totalTabHeight > th || isShowTabButtons()) { if (!isShowTabButtons()) numberOfButtons += 3; // Allow space for scrollbuttons vh = Math.max(th - _buttonSize * numberOfButtons, 0); // if (totalTabHeight - viewRect.y <= vh) { // // Scrolled to the end, so ensure the // // viewport size is // // such that the scroll offset aligns // // with a tab // vh = totalTabHeight - viewRect.y; // } } else { // Allow space for scrollbuttons vh = Math.max(th - _buttonSize * numberOfButtons, 0); } if (vh + getLayoutSize() < th - _buttonSize * numberOfButtons) { vh += getLayoutSize(); } break; case BOTTOM: case TOP: default: int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width; if (isShowTabButtons() || totalTabWidth > tw) { if (!isShowTabButtons()) numberOfButtons += 3; // Need to allow space for scrollbuttons vw = Math.max(tw - _buttonSize * numberOfButtons, 0); // if (totalTabWidth - viewRect.x <= vw) { // // Scrolled to the end, so ensure the // // viewport size is // // such that the scroll offset aligns // // with a tab // vw = totalTabWidth - viewRect.x; // } } else { // Allow space for scrollbuttons vw = Math.max(tw - _buttonSize * numberOfButtons, 0); } if (vw + getLayoutSize() < tw - _buttonSize * numberOfButtons) { vw += getLayoutSize(); } break; } child.setBounds(tx, ty, vw, vh); } else if (child instanceof TabCloseButton) { TabCloseButton scrollbutton = (TabCloseButton) child; if (_tabPane.isTabShown() && (scrollbutton.getType() != TabCloseButton.CLOSE_BUTTON || !isShowCloseButtonOnTab())) { Dimension bsize = scrollbutton.getPreferredSize(); int bx = 0; int by = 0; int bw = bsize.width; int bh = bsize.height; boolean visible = false; switch (tabPlacement) { case LEFT: case RIGHT: int totalTabHeight = _rects[tabCount - 1].y + _rects[tabCount - 1].height; if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabHeight > th)) { int dir = scrollbutton.getType();//NoFocusButton.EAST_BUTTON : NoFocusButton.WEST_BUTTON; scrollbutton.setType(dir); switch (dir) { case TabCloseButton.CLOSE_BUTTON: if (isShowCloseButton()) { visible = true; by = bounds.height - insets.top - bsize.height - 5; } else { visible = false; by = 0; } break; case TabCloseButton.LIST_BUTTON: visible = true; by = bounds.height - insets.top - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; case TabCloseButton.EAST_BUTTON: visible = !isShrinkTabs(); by = bounds.height - insets.top - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; case TabCloseButton.WEST_BUTTON: visible = !isShrinkTabs(); by = bounds.height - insets.top - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.height - 5; break; } bx = tx + 2; } else { int dir = scrollbutton.getType(); scrollbutton.setType(dir); if (dir == TabCloseButton.CLOSE_BUTTON) { if (isShowCloseButton()) { visible = true; by = bounds.height - insets.top - bsize.height - 5; } else { visible = false; by = 0; } bx = tx + 2; } } if (isTabTrailingComponentVisible()) { by = by - tsize.height; } int temp = -1; if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().width >= _rects[0].width) { if (tabPlacement == LEFT) { bx += _tabLeadingComponent.getSize().width - _rects[0].width; temp = _tabLeadingComponent.getSize().width; } } } if (isTabTrailingComponentVisible()) { if (_tabTrailingComponent.getSize().width >= _rects[0].width && temp < _tabTrailingComponent.getSize().width) { if (tabPlacement == LEFT) { bx += _tabTrailingComponent.getSize().width - _rects[0].width; } } } break; case TOP: case BOTTOM: default: int totalTabWidth = _rects[tabCount - 1].x + _rects[tabCount - 1].width; if (_tabPane.isTabShown() && (isShowTabButtons() || totalTabWidth > tw)) { int dir = scrollbutton.getType();// NoFocusButton.EAST_BUTTON // NoFocusButton.WEST_BUTTON; scrollbutton.setType(dir); switch (dir) { case TabCloseButton.CLOSE_BUTTON: if (isShowCloseButton()) { visible = true; bx = bounds.width - insets.left - bsize.width - 5; } else { visible = false; bx = 0; } break; case TabCloseButton.LIST_BUTTON: visible = true; bx = bounds.width - insets.left - (2 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; case TabCloseButton.EAST_BUTTON: visible = !isShrinkTabs(); bx = bounds.width - insets.left - (3 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; case TabCloseButton.WEST_BUTTON: visible = !isShrinkTabs(); bx = bounds.width - insets.left - (4 - (!isShowCloseButton() || isShowCloseButtonOnTab() ? 1 : 0)) * bsize.width - 5; break; } by = ((th - bsize.height) >> 1) + ty; } else { int dir = scrollbutton.getType(); scrollbutton.setType(dir); if (dir == TabCloseButton.CLOSE_BUTTON) { if (isShowCloseButton()) { visible = true; bx = bounds.width - insets.left - bsize.width - 5; } else { visible = false; bx = 0; } by = ((th - bsize.height) >> 1) + ty; } } if (isTabTrailingComponentVisible()) { bx -= tsize.width; } temp = -1; if (isTabLeadingComponentVisible()) { if (_tabLeadingComponent.getSize().height >= _rects[0].height) { if (tabPlacement == TOP) { by = ty + 2 + _tabLeadingComponent.getSize().height - _rects[0].height; temp = _tabLeadingComponent.getSize().height; } else { by = ty + 2; } } } if (isTabTrailingComponentVisible()) { if (_tabTrailingComponent.getSize().height >= _rects[0].height && temp < _tabTrailingComponent.getSize().height) { if (tabPlacement == TOP) { by = ty + 2 + _tabTrailingComponent.getSize().height - _rects[0].height; } else { by = ty + 2; } } } } child.setVisible(visible); if (visible) { child.setBounds(bx, by, bw, bh); } } else { scrollbutton.setBounds(0, 0, 0, 0); } } else if (child != _tabPane.getTabLeadingComponent() && child != _tabPane.getTabTrailingComponent()) { if (_tabPane.isShowTabContent()) { // All content children... child.setBounds(cx, cy, cw, ch); } else { child.setBounds(0, 0, 0, 0); } } } if (leftToRight) { if (isTabLeadingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabLeadingComponent.setBounds(tx + tw - lsize.width, ty - lsize.height, lsize.width, lsize.height); break; case RIGHT: _tabLeadingComponent.setBounds(tx, ty - lsize.height, lsize.width, lsize.height); break; case BOTTOM: _tabLeadingComponent.setBounds(tx - lsize.width, ty, lsize.width, lsize.height); break; case TOP: default: _tabLeadingComponent.setBounds(tx - lsize.width, ty + th - lsize.height, lsize.width, lsize.height); break; } } if (isTabTrailingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabTrailingComponent.setBounds(tx + tw - tsize.width, ty + th, tsize.width, tsize.height); break; case RIGHT: _tabTrailingComponent.setBounds(tx, ty + th, tsize.width, tsize.height); break; case BOTTOM: _tabTrailingComponent.setBounds(tx + tw, ty, tsize.width, tsize.height); break; case TOP: default: _tabTrailingComponent.setBounds(tx + tw, ty + th - tsize.height, tsize.width, tsize.height); break; } } } else { if (isTabTrailingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabTrailingComponent.setBounds(tx + tw - tsize.width, ty - tsize.height, tsize.width, tsize.height); break; case RIGHT: _tabTrailingComponent.setBounds(tx, ty - tsize.height, tsize.width, tsize.height); break; case BOTTOM: _tabTrailingComponent.setBounds(tx - tsize.width, ty, tsize.width, tsize.height); break; case TOP: default: _tabTrailingComponent.setBounds(tx - tsize.width, ty + th - tsize.height, tsize.width, tsize.height); break; } } if (isTabLeadingComponentVisible()) { switch (_tabPane.getTabPlacement()) { case LEFT: _tabLeadingComponent.setBounds(tx + tw - lsize.width, ty + th, lsize.width, lsize.height); break; case RIGHT: _tabLeadingComponent.setBounds(tx, ty + th, lsize.width, lsize.height); break; case BOTTOM: _tabLeadingComponent.setBounds(tx + tw, ty, lsize.width, lsize.height); break; case TOP: default: _tabLeadingComponent.setBounds(tx + tw, ty + th - lsize.height, lsize.width, lsize.height); break; } } } if (shouldChangeFocus) { if (!requestFocusForVisibleComponent()) { if (!_tabPane.requestFocusInWindow()) { _tabPane.requestFocus(); } } } } } }
diff --git a/src/main/java/nodebox/function/NetworkFunctions.java b/src/main/java/nodebox/function/NetworkFunctions.java index aeb13b11..0e9bde92 100644 --- a/src/main/java/nodebox/function/NetworkFunctions.java +++ b/src/main/java/nodebox/function/NetworkFunctions.java @@ -1,134 +1,134 @@ package nodebox.function; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.jayway.jsonpath.JsonPath; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class NetworkFunctions { public static final Map<Integer, Response> responseCache = new HashMap<Integer, Response>(); public static final FunctionLibrary LIBRARY; static { LIBRARY = JavaLibrary.ofClass("network", NetworkFunctions.class, "httpGet", "queryJSON"); } public static Map<String, Object> httpGet(final String url, final String username, final String password, final long refreshTimeSeconds) { Integer cacheKey = Objects.hashCode(url, username, password); synchronized (cacheKey) { if (responseCache.containsKey(cacheKey)) { Response r = responseCache.get(cacheKey); long timeNow = nowSeconds(); long timeFetched = r.timeFetched; if ((timeNow - timeFetched) <= refreshTimeSeconds) { return r.response; } } Map<String, Object> r = _httpGet(url, username, password); Response res = new Response(nowSeconds(), r); responseCache.put(cacheKey, res); return r; } } public static Iterable<?> queryJSON(final Object json, final String query) { if (json instanceof Map) { Map<?, ?> requestMap = (Map<?, ?>) json; if (requestMap.containsKey("text")) { return queryJSON(requestMap.get("text"), query); } else { throw new IllegalArgumentException("Cannot parse JSON input."); } } else if (json instanceof String) { Object results = JsonPath.read((String) json, query); if (!(results instanceof Iterable)) { return ImmutableList.of(results); } else { return (Iterable<?>) results; } } else { throw new IllegalArgumentException("Cannot parse JSON input."); } } private static Map<String, Object> _httpGet(final String url, final String username, final String password) { HttpGet request = new HttpGet(url); if (username != null && !username.trim().isEmpty()) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); BasicScheme scheme = new BasicScheme(); Header authorizationHeader; try { authorizationHeader = scheme.authenticate(credentials, request, new BasicHttpContext()); } catch (AuthenticationException e) { throw new RuntimeException(e); } request.addHeader(authorizationHeader); } try { DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String text = EntityUtils.toString(entity); - ImmutableMap.Builder<String, String> b = ImmutableMap.builder(); + HashMap<String,String> m = new HashMap<String, String>(); for (Header h : response.getAllHeaders()) { - b.put(h.getName(), h.getValue()); + m.put(h.getName(), h.getValue()); } - Map<String, String> headers = b.build(); + Map<String, String> headers = ImmutableMap.copyOf(m); return ImmutableMap.of( "text", text, "statusCode", response.getStatusLine().getStatusCode(), "headers", headers); } else { // 204 No Content return emptyResponse(204); } } catch (IOException e) { // We return status code 408 (Request Timeout) here since we always want to return a valid response. // However, the exception signifies an IO error, so maybe the network connection is down. // This has no valid HTTP response (since there is NO response). return emptyResponse(408); } } private static Map<String, Object> emptyResponse(int statusCode) { return ImmutableMap.<String, Object>of( "text", "", "statusCode", statusCode ); } private static long nowSeconds() { return System.currentTimeMillis() / 1000; } private static class Response { private final long timeFetched; private final Map<String, Object> response; private Response(long timeFetched, Map<String, Object> response) { this.timeFetched = timeFetched; this.response = response; } } }
false
true
private static Map<String, Object> _httpGet(final String url, final String username, final String password) { HttpGet request = new HttpGet(url); if (username != null && !username.trim().isEmpty()) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); BasicScheme scheme = new BasicScheme(); Header authorizationHeader; try { authorizationHeader = scheme.authenticate(credentials, request, new BasicHttpContext()); } catch (AuthenticationException e) { throw new RuntimeException(e); } request.addHeader(authorizationHeader); } try { DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String text = EntityUtils.toString(entity); ImmutableMap.Builder<String, String> b = ImmutableMap.builder(); for (Header h : response.getAllHeaders()) { b.put(h.getName(), h.getValue()); } Map<String, String> headers = b.build(); return ImmutableMap.of( "text", text, "statusCode", response.getStatusLine().getStatusCode(), "headers", headers); } else { // 204 No Content return emptyResponse(204); } } catch (IOException e) { // We return status code 408 (Request Timeout) here since we always want to return a valid response. // However, the exception signifies an IO error, so maybe the network connection is down. // This has no valid HTTP response (since there is NO response). return emptyResponse(408); } }
private static Map<String, Object> _httpGet(final String url, final String username, final String password) { HttpGet request = new HttpGet(url); if (username != null && !username.trim().isEmpty()) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); BasicScheme scheme = new BasicScheme(); Header authorizationHeader; try { authorizationHeader = scheme.authenticate(credentials, request, new BasicHttpContext()); } catch (AuthenticationException e) { throw new RuntimeException(e); } request.addHeader(authorizationHeader); } try { DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String text = EntityUtils.toString(entity); HashMap<String,String> m = new HashMap<String, String>(); for (Header h : response.getAllHeaders()) { m.put(h.getName(), h.getValue()); } Map<String, String> headers = ImmutableMap.copyOf(m); return ImmutableMap.of( "text", text, "statusCode", response.getStatusLine().getStatusCode(), "headers", headers); } else { // 204 No Content return emptyResponse(204); } } catch (IOException e) { // We return status code 408 (Request Timeout) here since we always want to return a valid response. // However, the exception signifies an IO error, so maybe the network connection is down. // This has no valid HTTP response (since there is NO response). return emptyResponse(408); } }
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/CubeQueryExecutor.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/CubeQueryExecutor.java index 8e3a2bf94..bc44cb25f 100644 --- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/CubeQueryExecutor.java +++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/CubeQueryExecutor.java @@ -1,139 +1,140 @@ /******************************************************************************* * Copyright (c) 2004, 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.olap.impl.query; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.eclipse.birt.data.engine.api.DataEngineContext; import org.eclipse.birt.data.engine.api.IFilterDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.impl.DataEngineSession; import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition; import org.eclipse.birt.data.engine.olap.api.query.ICubeSortDefinition; import org.eclipse.birt.data.engine.olap.util.filter.BaseDimensionFilterEvalHelper; import org.mozilla.javascript.Scriptable; /** * */ public class CubeQueryExecutor { private ICubeQueryDefinition defn; private Scriptable scope; private DataEngineSession session; private DataEngineContext context; private String queryResultsId; public CubeQueryExecutor( ICubeQueryDefinition defn, DataEngineSession session, Scriptable scope, DataEngineContext context ) { this.defn = defn; this.scope = scope; this.context = context; this.session = session; } public List getDimensionFilterEvalHelpers( ) throws DataException { List filters = defn.getFilters( ); List results = new ArrayList( ); for ( int i = 0; i < filters.size( ); i++ ) { results.add( BaseDimensionFilterEvalHelper.createFilterHelper( this.scope, defn, (IFilterDefinition) filters.get( i ) ) ); } return results; } public ICubeQueryDefinition getCubeQueryDefinition( ) { return this.defn; } public DataEngineSession getSession( ) { return this.session; } public DataEngineContext getContext( ) { return this.context; } public List getColumnEdgeSort( ) { return getEdgeSort( ICubeQueryDefinition.COLUMN_EDGE ); } public List getRowEdgeSort( ) { return getEdgeSort( ICubeQueryDefinition.ROW_EDGE ); } public String getQueryResultsId() { return this.queryResultsId; } public void setQueryResultsId( String id ) { this.queryResultsId = id; } private List getEdgeSort( int edgeType ) { List l = this.defn.getSorts( ); List result = new ArrayList( ); for ( int i = 0; i < l.size( ); i++ ) { ICubeSortDefinition sort = (ICubeSortDefinition) l.get( i ); - if ( this.defn.getEdge( edgeType ) - .getDimensions( ) - .contains( sort.getTargetLevel( ) - .getHierarchy( ) - .getDimension( ) ) ) + if ( this.defn.getEdge( edgeType ) != null && + this.defn.getEdge( edgeType ) + .getDimensions( ) + .contains( sort.getTargetLevel( ) + .getHierarchy( ) + .getDimension( ) ) ) { result.add( sort ); } } Collections.sort( result, new Comparator( ) { public int compare( Object arg0, Object arg1 ) { int level1 = ( (ICubeSortDefinition) arg0 ).getTargetLevel( ) .getHierarchy( ) .getLevels( ) .indexOf( ( (ICubeSortDefinition) arg0 ).getTargetLevel( ) ); int level2 = ( (ICubeSortDefinition) arg1 ).getTargetLevel( ) .getHierarchy( ) .getLevels( ) .indexOf( ( (ICubeSortDefinition) arg1 ).getTargetLevel( ) ); if ( level1 == level2 ) return 0; else if ( level1 < level2 ) return -1; else return 1; } } ); return result; } }
true
true
private List getEdgeSort( int edgeType ) { List l = this.defn.getSorts( ); List result = new ArrayList( ); for ( int i = 0; i < l.size( ); i++ ) { ICubeSortDefinition sort = (ICubeSortDefinition) l.get( i ); if ( this.defn.getEdge( edgeType ) .getDimensions( ) .contains( sort.getTargetLevel( ) .getHierarchy( ) .getDimension( ) ) ) { result.add( sort ); } } Collections.sort( result, new Comparator( ) { public int compare( Object arg0, Object arg1 ) { int level1 = ( (ICubeSortDefinition) arg0 ).getTargetLevel( ) .getHierarchy( ) .getLevels( ) .indexOf( ( (ICubeSortDefinition) arg0 ).getTargetLevel( ) ); int level2 = ( (ICubeSortDefinition) arg1 ).getTargetLevel( ) .getHierarchy( ) .getLevels( ) .indexOf( ( (ICubeSortDefinition) arg1 ).getTargetLevel( ) ); if ( level1 == level2 ) return 0; else if ( level1 < level2 ) return -1; else return 1; } } ); return result; }
private List getEdgeSort( int edgeType ) { List l = this.defn.getSorts( ); List result = new ArrayList( ); for ( int i = 0; i < l.size( ); i++ ) { ICubeSortDefinition sort = (ICubeSortDefinition) l.get( i ); if ( this.defn.getEdge( edgeType ) != null && this.defn.getEdge( edgeType ) .getDimensions( ) .contains( sort.getTargetLevel( ) .getHierarchy( ) .getDimension( ) ) ) { result.add( sort ); } } Collections.sort( result, new Comparator( ) { public int compare( Object arg0, Object arg1 ) { int level1 = ( (ICubeSortDefinition) arg0 ).getTargetLevel( ) .getHierarchy( ) .getLevels( ) .indexOf( ( (ICubeSortDefinition) arg0 ).getTargetLevel( ) ); int level2 = ( (ICubeSortDefinition) arg1 ).getTargetLevel( ) .getHierarchy( ) .getLevels( ) .indexOf( ( (ICubeSortDefinition) arg1 ).getTargetLevel( ) ); if ( level1 == level2 ) return 0; else if ( level1 < level2 ) return -1; else return 1; } } ); return result; }
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchSetSelectBox.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchSetSelectBox.java index df12b706a..efaa0b3dc 100644 --- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchSetSelectBox.java +++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/patches/PatchSetSelectBox.java @@ -1,209 +1,209 @@ // Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.patches; import com.google.gerrit.client.Dispatcher; import com.google.gerrit.client.Gerrit; import com.google.gerrit.common.data.PatchScript; import com.google.gerrit.common.data.PatchSetDetail; import com.google.gerrit.reviewdb.client.Patch; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DoubleClickEvent; import com.google.gwt.event.dom.client.DoubleClickHandler; import com.google.gwt.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwtorm.client.KeyUtil; import java.util.HashMap; import java.util.Map; public class PatchSetSelectBox extends Composite { interface Binder extends UiBinder<HTMLPanel, PatchSetSelectBox> { } private static Binder uiBinder = GWT.create(Binder.class); interface BoxStyle extends CssResource { String selected(); String hidden(); String sideMarker(); String patchSetLabel(); } public enum Side { A, B } PatchScript script; Patch.Key patchKey; PatchSet.Id idSideA; PatchSet.Id idSideB; PatchSet.Id idActive; Side side; PatchScreen.Type screenType; Map<Integer, Anchor> links; private Label patchSet; @UiField HTMLPanel linkPanel; @UiField BoxStyle style; public PatchSetSelectBox(Side side, final PatchScreen.Type type) { this.side = side; this.screenType = type; initWidget(uiBinder.createAndBindUi(this)); } public void display(final PatchSetDetail detail, final PatchScript script, Patch.Key key, PatchSet.Id idSideA, PatchSet.Id idSideB) { this.script = script; this.patchKey = key; this.idSideA = idSideA; this.idSideB = idSideB; this.idActive = (side == Side.A) ? idSideA : idSideB; this.links = new HashMap<Integer, Anchor>(); linkPanel.clear(); if (isFileOrCommitMessage()) { linkPanel.setTitle(PatchUtil.C.addFileCommentByDoubleClick()); } patchSet = new Label(PatchUtil.C.patchSet()); patchSet.addStyleName(style.patchSetLabel()); linkPanel.add(patchSet); if (screenType == PatchScreen.Type.UNIFIED) { Label sideMarker = new Label((side == Side.A) ? "(-)" : "(+)"); sideMarker.addStyleName(style.sideMarker()); linkPanel.add(sideMarker); } Anchor baseLink = null; if (detail.getInfo().getParents().size() > 1) { baseLink = createLink(PatchUtil.C.patchBaseAutoMerge(), null); } else { baseLink = createLink(PatchUtil.C.patchBase(), null); } links.put(0, baseLink); if (screenType == PatchScreen.Type.UNIFIED || side == Side.A) { linkPanel.add(baseLink); } if (side == Side.B) { links.get(0).setStyleName(style.hidden()); } for (Patch patch : script.getHistory()) { PatchSet.Id psId = patch.getKey().getParentKey(); Anchor anchor = createLink(Integer.toString(psId.get()), psId); links.put(psId.get(), anchor); linkPanel.add(anchor); } if (idActive == null && side == Side.A) { links.get(0).setStyleName(style.selected()); - } else { + } else if (idActive != null) { links.get(idActive.get()).setStyleName(style.selected()); } Anchor downloadLink = createDownloadLink(); if (downloadLink != null) { linkPanel.add(downloadLink); } } public void addDoubleClickHandler(DoubleClickHandler handler) { linkPanel.sinkEvents(Event.ONDBLCLICK); linkPanel.addHandler(handler, DoubleClickEvent.getType()); patchSet.addDoubleClickHandler(handler); } private Anchor createLink(String label, final PatchSet.Id id) { final Anchor anchor = new Anchor(label); anchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (side == Side.A) { idSideA = id; } else { idSideB = id; } Patch.Key keySideB = new Patch.Key(idSideB, patchKey.get()); switch (screenType) { case SIDE_BY_SIDE: Gerrit.display(Dispatcher.toPatchSideBySide(idSideA, keySideB)); break; case UNIFIED: Gerrit.display(Dispatcher.toPatchUnified(idSideA, keySideB)); break; } } }); return anchor; } public boolean isFileOrCommitMessage() { return !((side == Side.A && 0 >= script.getA().size()) || // (side == Side.B && 0 >= script.getB().size())); } private Anchor createDownloadLink() { boolean isCommitMessage = Patch.COMMIT_MSG.equals(script.getNewName()); if (isCommitMessage || // (side == Side.A && 0 >= script.getA().size()) || // (side == Side.B && 0 >= script.getB().size())) { return null; } Patch.Key key = (idActive == null) ? // patchKey : (new Patch.Key(idActive, patchKey.get())); String sideURL = (idActive == null) ? "1" : "0"; final String base = GWT.getHostPageBaseURL() + "cat/"; Image image = new Image(Gerrit.RESOURCES.downloadIcon()); final Anchor anchor = new Anchor(); anchor.setHref(base + KeyUtil.encode(key.toString()) + "^" + sideURL); anchor.setTitle(PatchUtil.C.download()); DOM.insertBefore(anchor.getElement(), image.getElement(), DOM.getFirstChild(anchor.getElement())); return anchor; } }
true
true
public void display(final PatchSetDetail detail, final PatchScript script, Patch.Key key, PatchSet.Id idSideA, PatchSet.Id idSideB) { this.script = script; this.patchKey = key; this.idSideA = idSideA; this.idSideB = idSideB; this.idActive = (side == Side.A) ? idSideA : idSideB; this.links = new HashMap<Integer, Anchor>(); linkPanel.clear(); if (isFileOrCommitMessage()) { linkPanel.setTitle(PatchUtil.C.addFileCommentByDoubleClick()); } patchSet = new Label(PatchUtil.C.patchSet()); patchSet.addStyleName(style.patchSetLabel()); linkPanel.add(patchSet); if (screenType == PatchScreen.Type.UNIFIED) { Label sideMarker = new Label((side == Side.A) ? "(-)" : "(+)"); sideMarker.addStyleName(style.sideMarker()); linkPanel.add(sideMarker); } Anchor baseLink = null; if (detail.getInfo().getParents().size() > 1) { baseLink = createLink(PatchUtil.C.patchBaseAutoMerge(), null); } else { baseLink = createLink(PatchUtil.C.patchBase(), null); } links.put(0, baseLink); if (screenType == PatchScreen.Type.UNIFIED || side == Side.A) { linkPanel.add(baseLink); } if (side == Side.B) { links.get(0).setStyleName(style.hidden()); } for (Patch patch : script.getHistory()) { PatchSet.Id psId = patch.getKey().getParentKey(); Anchor anchor = createLink(Integer.toString(psId.get()), psId); links.put(psId.get(), anchor); linkPanel.add(anchor); } if (idActive == null && side == Side.A) { links.get(0).setStyleName(style.selected()); } else { links.get(idActive.get()).setStyleName(style.selected()); } Anchor downloadLink = createDownloadLink(); if (downloadLink != null) { linkPanel.add(downloadLink); } }
public void display(final PatchSetDetail detail, final PatchScript script, Patch.Key key, PatchSet.Id idSideA, PatchSet.Id idSideB) { this.script = script; this.patchKey = key; this.idSideA = idSideA; this.idSideB = idSideB; this.idActive = (side == Side.A) ? idSideA : idSideB; this.links = new HashMap<Integer, Anchor>(); linkPanel.clear(); if (isFileOrCommitMessage()) { linkPanel.setTitle(PatchUtil.C.addFileCommentByDoubleClick()); } patchSet = new Label(PatchUtil.C.patchSet()); patchSet.addStyleName(style.patchSetLabel()); linkPanel.add(patchSet); if (screenType == PatchScreen.Type.UNIFIED) { Label sideMarker = new Label((side == Side.A) ? "(-)" : "(+)"); sideMarker.addStyleName(style.sideMarker()); linkPanel.add(sideMarker); } Anchor baseLink = null; if (detail.getInfo().getParents().size() > 1) { baseLink = createLink(PatchUtil.C.patchBaseAutoMerge(), null); } else { baseLink = createLink(PatchUtil.C.patchBase(), null); } links.put(0, baseLink); if (screenType == PatchScreen.Type.UNIFIED || side == Side.A) { linkPanel.add(baseLink); } if (side == Side.B) { links.get(0).setStyleName(style.hidden()); } for (Patch patch : script.getHistory()) { PatchSet.Id psId = patch.getKey().getParentKey(); Anchor anchor = createLink(Integer.toString(psId.get()), psId); links.put(psId.get(), anchor); linkPanel.add(anchor); } if (idActive == null && side == Side.A) { links.get(0).setStyleName(style.selected()); } else if (idActive != null) { links.get(idActive.get()).setStyleName(style.selected()); } Anchor downloadLink = createDownloadLink(); if (downloadLink != null) { linkPanel.add(downloadLink); } }
diff --git a/src/main/java/ch/x42/terye/mk/hbase/RevisionIdGenerator.java b/src/main/java/ch/x42/terye/mk/hbase/RevisionIdGenerator.java index 0b96afa..bc70735 100644 --- a/src/main/java/ch/x42/terye/mk/hbase/RevisionIdGenerator.java +++ b/src/main/java/ch/x42/terye/mk/hbase/RevisionIdGenerator.java @@ -1,83 +1,88 @@ package ch.x42.terye.mk.hbase; import org.apache.jackrabbit.mk.api.MicroKernelException; public class RevisionIdGenerator { /** * The timestamp of the revision ids to be generated is based on the * following date instead of the usual unix epoch: 01.01.2013 00:00:00. * * NEVER EVER CHANGE THIS VALUE! */ public static final long EPOCH = 1356998400; // the machine id associated with this generator instance private long machineId; // the timestamp of the id last generated private long lastTimestamp; // counter to differentiate ids generated within the same millisecond private int count; public RevisionIdGenerator(int machineId) { if (machineId < 0 || machineId > 65535) { throw new IllegalArgumentException("Machine id is out of range"); } this.machineId = machineId; lastTimestamp = -1; count = 0; } /** * This method generates a new revision id. A revision id is a signed (but * non-negative) long composed of the concatenation (left-to-right) of * following fields: * * <pre> * ------------------------------------------------------------------ * | timestamp | machine_id | count | * ------------------------------------------------------------------ * * - timestamp: 5 bytes, [0, 1099511627775] * - machine_id: 2 bytes, [0, 65535] * - count: 1 byte, [0, 255] * </pre> * * The unit of the "timestamp" field is milliseconds and since we only have * 5 bytes available, we base it on an artificial epoch constant in order to * have more values available. The machine id used for "machine_id" is * either set explicitly or generated using the hashcode of the MAC address * string. If the same machine commits a revision within the same * millisecond, then the "count" field is used in order to create a unique * revision id. * * @return a new and unique revision id */ public long getNewId() { // timestamp long timestamp = System.currentTimeMillis() - EPOCH; timestamp <<= 24; // check for overflow if (timestamp < 0) { // we have used all available time values - throw new MicroKernelException("Error generating new revision id"); + throw new MicroKernelException( + "Error generating new revision id, timestamp overflowed"); } // machine id - long machineId = (this.machineId << 16) - & Long.decode("0x00000000FFFF0000"); + long machineId = (this.machineId << 8) + & Long.decode("0x0000000000FFFF00"); // counter if (timestamp == lastTimestamp) { count++; } else { lastTimestamp = timestamp; count = 0; } + if (count > 255) { + throw new MicroKernelException( + "Error generating new revision id, counter overflowed"); + } long count = this.count & Integer.decode("0x000000FF"); // assemble and return revision id return timestamp | machineId | count; } }
false
true
public long getNewId() { // timestamp long timestamp = System.currentTimeMillis() - EPOCH; timestamp <<= 24; // check for overflow if (timestamp < 0) { // we have used all available time values throw new MicroKernelException("Error generating new revision id"); } // machine id long machineId = (this.machineId << 16) & Long.decode("0x00000000FFFF0000"); // counter if (timestamp == lastTimestamp) { count++; } else { lastTimestamp = timestamp; count = 0; } long count = this.count & Integer.decode("0x000000FF"); // assemble and return revision id return timestamp | machineId | count; }
public long getNewId() { // timestamp long timestamp = System.currentTimeMillis() - EPOCH; timestamp <<= 24; // check for overflow if (timestamp < 0) { // we have used all available time values throw new MicroKernelException( "Error generating new revision id, timestamp overflowed"); } // machine id long machineId = (this.machineId << 8) & Long.decode("0x0000000000FFFF00"); // counter if (timestamp == lastTimestamp) { count++; } else { lastTimestamp = timestamp; count = 0; } if (count > 255) { throw new MicroKernelException( "Error generating new revision id, counter overflowed"); } long count = this.count & Integer.decode("0x000000FF"); // assemble and return revision id return timestamp | machineId | count; }
diff --git a/src/main/java/nz/co/searchwellington/views/ContentDedupingService.java b/src/main/java/nz/co/searchwellington/views/ContentDedupingService.java index 27e9600d..5fe542f2 100644 --- a/src/main/java/nz/co/searchwellington/views/ContentDedupingService.java +++ b/src/main/java/nz/co/searchwellington/views/ContentDedupingService.java @@ -1,28 +1,28 @@ package nz.co.searchwellington.views; import java.util.List; import nz.co.searchwellington.model.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.google.common.collect.Lists; @Component public class ContentDedupingService { private static Logger log = Logger.getLogger(ContentDedupingService.class); public List<Resource> dedupeNewsitems(List<Resource> latestNewsitems, List<Resource> commentedNewsitems) { log.info("Called with " + latestNewsitems.size() + " main content items and " + commentedNewsitems.size() + " commented news items"); - final List <Resource> depuded = Lists.newArrayList(); + final List <Resource> depuded = Lists.newArrayList(latestNewsitems); depuded.removeAll(commentedNewsitems); if (depuded.size() < latestNewsitems.size()) { log.info("Removed " + (latestNewsitems.size() - depuded.size()) + " duplicates"); } log.info("Returning " + depuded.size() + " main content items"); return depuded; } }
true
true
public List<Resource> dedupeNewsitems(List<Resource> latestNewsitems, List<Resource> commentedNewsitems) { log.info("Called with " + latestNewsitems.size() + " main content items and " + commentedNewsitems.size() + " commented news items"); final List <Resource> depuded = Lists.newArrayList(); depuded.removeAll(commentedNewsitems); if (depuded.size() < latestNewsitems.size()) { log.info("Removed " + (latestNewsitems.size() - depuded.size()) + " duplicates"); } log.info("Returning " + depuded.size() + " main content items"); return depuded; }
public List<Resource> dedupeNewsitems(List<Resource> latestNewsitems, List<Resource> commentedNewsitems) { log.info("Called with " + latestNewsitems.size() + " main content items and " + commentedNewsitems.size() + " commented news items"); final List <Resource> depuded = Lists.newArrayList(latestNewsitems); depuded.removeAll(commentedNewsitems); if (depuded.size() < latestNewsitems.size()) { log.info("Removed " + (latestNewsitems.size() - depuded.size()) + " duplicates"); } log.info("Returning " + depuded.size() + " main content items"); return depuded; }
diff --git a/console-embed/src/main/java/org/javasimon/console/action/DetailHtmlAction.java b/console-embed/src/main/java/org/javasimon/console/action/DetailHtmlAction.java index d427a1f4..db0086fc 100644 --- a/console-embed/src/main/java/org/javasimon/console/action/DetailHtmlAction.java +++ b/console-embed/src/main/java/org/javasimon/console/action/DetailHtmlAction.java @@ -1,142 +1,143 @@ package org.javasimon.console.action; import java.io.IOException; import javax.servlet.ServletException; import org.javasimon.Simon; import org.javasimon.console.*; import org.javasimon.console.text.StringifierFactory; /** * Export single Simon data as static HTML for printing purposes. * Path: http://.../data/detail.html?name=o.j...SimonName&timeFormat=MILLISECOND * @author gquintana */ public class DetailHtmlAction extends Action { /** * HTTP Request path */ public static final String PATH="/data/detail.html"; /** * Value formatter */ protected StringifierFactory stringifierFactory; /** * Simon name */ private String name; /** * Constructor. */ public DetailHtmlAction(ActionContext context) { super(context); this.stringifierFactory = new StringifierFactory(); } @Override public void readParameters() { name=getContext().getParameterAsString("name", null); stringifierFactory.init(getContext().getParameterAsEnum("timeFormat", TimeFormatType.class, TimeFormatType.MILLISECOND), StringifierFactory.READABLE_DATE_PATTERN, StringifierFactory.READABLE_NUMBER_PATTERN); } @Override public void execute() throws ServletException, IOException, ActionException { // Check arguments if (name==null) { throw new ActionException("Null name"); } Simon simon=getContext().getManager().getSimon(name); if (simon==null) { throw new ActionException("Simon \""+name+"\" not found"); } getContext().setContentType("text/html"); SimonType simonType=SimonTypeFactory.getValueFromInstance(simon); DetailHtmlBuilder htmlBuilder=new DetailHtmlBuilder(getContext().getWriter(), stringifierFactory); // Page header htmlBuilder.header("Detail View", DetailPlugin.getResources(getContext(), DetailPlugin.class)) // Common Simon section .beginSection("simonPanel", "Simon") .beginRow() .simonProperty(simon, "Name", "name", 5) .endRow() .beginRow() .labelCell("Type") .beginValueCell().simonTypeImg(simonType,"../../").object(simonType).endValueCell() .simonProperty(simon, "State", "state") .simonProperty(simon, "Enabled", "enabled") .endRow() .beginRow() .simonProperty(simon, "Note", "note", 5) .endRow() .beginRow() .simonProperty(simon, "First Use", "firstUsage") .simonProperty(simon, "Last Reset", "lastReset") .simonProperty(simon, "Last Use", "lastUsage") .endRow() .endSection(); // Specific Stopwatch/Counter section switch(simonType) { case STOPWATCH: htmlBuilder.beginSection("stopwatchPanel", "Stopwatch") .beginRow() .simonProperty(simon, "Counter", "counter") - .simonProperty(simon, "Total", "total") + .simonProperty(simon, "Total", "total" ,3) .endRow() .beginRow() - .simonProperty(simon, "Min", "min") + .simonProperty(simon, "Min", "min", 3) .simonProperty(simon, "Min Timestamp", "minTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Mean", "mean") - .simonProperty(simon, "Standard Deviation", "standardDeviation") + .simonProperty(simon, "Standard Deviation", "standardDeviation", 3) .endRow() .beginRow() - .simonProperty(simon, "Max", "max") + .simonProperty(simon, "Max", "max", 3) .simonProperty(simon, "Max Timestamp", "maxTimeStamp") .endRow() .beginRow() - .simonProperty(simon, "Last", "last") + .simonProperty(simon, "Last", "last", 3) .simonProperty(simon, "Last Timestamp", "lastUsage") .endRow() .beginRow() + .simonProperty(simon, "Active", "active") .simonProperty(simon, "Max Active", "maxActive") .simonProperty(simon, "Max Active Timestamp", "maxActiveTimestamp") .endRow() .endSection(); break; case COUNTER: htmlBuilder.beginSection("counterPanel", "Counter") .beginRow() .simonProperty(simon, "Counter", "counter") .endRow() .beginRow() .simonProperty(simon, "Min", "min") .simonProperty(simon, "Min Timestamp", "minTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Max", "max") .simonProperty(simon, "Max Timestamp", "maxTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Increment Sum", "incrementSum") .simonProperty(simon, "Decrement Sum", "decrementSum") .endRow() .endSection(); break; } // Plugins for(DetailPlugin plugin:getContext().getPluginManager().getPluginsByType(DetailPlugin.class)) { if (plugin.supports(simon)) { htmlBuilder.beginSection(plugin.getId()+"Panel", plugin.getLabel()); plugin.executeHtml(getContext(), htmlBuilder, stringifierFactory, simon); htmlBuilder.endSection(); } } // Page footer htmlBuilder.footer(); } }
false
true
public void execute() throws ServletException, IOException, ActionException { // Check arguments if (name==null) { throw new ActionException("Null name"); } Simon simon=getContext().getManager().getSimon(name); if (simon==null) { throw new ActionException("Simon \""+name+"\" not found"); } getContext().setContentType("text/html"); SimonType simonType=SimonTypeFactory.getValueFromInstance(simon); DetailHtmlBuilder htmlBuilder=new DetailHtmlBuilder(getContext().getWriter(), stringifierFactory); // Page header htmlBuilder.header("Detail View", DetailPlugin.getResources(getContext(), DetailPlugin.class)) // Common Simon section .beginSection("simonPanel", "Simon") .beginRow() .simonProperty(simon, "Name", "name", 5) .endRow() .beginRow() .labelCell("Type") .beginValueCell().simonTypeImg(simonType,"../../").object(simonType).endValueCell() .simonProperty(simon, "State", "state") .simonProperty(simon, "Enabled", "enabled") .endRow() .beginRow() .simonProperty(simon, "Note", "note", 5) .endRow() .beginRow() .simonProperty(simon, "First Use", "firstUsage") .simonProperty(simon, "Last Reset", "lastReset") .simonProperty(simon, "Last Use", "lastUsage") .endRow() .endSection(); // Specific Stopwatch/Counter section switch(simonType) { case STOPWATCH: htmlBuilder.beginSection("stopwatchPanel", "Stopwatch") .beginRow() .simonProperty(simon, "Counter", "counter") .simonProperty(simon, "Total", "total") .endRow() .beginRow() .simonProperty(simon, "Min", "min") .simonProperty(simon, "Min Timestamp", "minTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Mean", "mean") .simonProperty(simon, "Standard Deviation", "standardDeviation") .endRow() .beginRow() .simonProperty(simon, "Max", "max") .simonProperty(simon, "Max Timestamp", "maxTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Last", "last") .simonProperty(simon, "Last Timestamp", "lastUsage") .endRow() .beginRow() .simonProperty(simon, "Max Active", "maxActive") .simonProperty(simon, "Max Active Timestamp", "maxActiveTimestamp") .endRow() .endSection(); break; case COUNTER: htmlBuilder.beginSection("counterPanel", "Counter") .beginRow() .simonProperty(simon, "Counter", "counter") .endRow() .beginRow() .simonProperty(simon, "Min", "min") .simonProperty(simon, "Min Timestamp", "minTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Max", "max") .simonProperty(simon, "Max Timestamp", "maxTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Increment Sum", "incrementSum") .simonProperty(simon, "Decrement Sum", "decrementSum") .endRow() .endSection(); break; } // Plugins for(DetailPlugin plugin:getContext().getPluginManager().getPluginsByType(DetailPlugin.class)) { if (plugin.supports(simon)) { htmlBuilder.beginSection(plugin.getId()+"Panel", plugin.getLabel()); plugin.executeHtml(getContext(), htmlBuilder, stringifierFactory, simon); htmlBuilder.endSection(); } } // Page footer htmlBuilder.footer(); }
public void execute() throws ServletException, IOException, ActionException { // Check arguments if (name==null) { throw new ActionException("Null name"); } Simon simon=getContext().getManager().getSimon(name); if (simon==null) { throw new ActionException("Simon \""+name+"\" not found"); } getContext().setContentType("text/html"); SimonType simonType=SimonTypeFactory.getValueFromInstance(simon); DetailHtmlBuilder htmlBuilder=new DetailHtmlBuilder(getContext().getWriter(), stringifierFactory); // Page header htmlBuilder.header("Detail View", DetailPlugin.getResources(getContext(), DetailPlugin.class)) // Common Simon section .beginSection("simonPanel", "Simon") .beginRow() .simonProperty(simon, "Name", "name", 5) .endRow() .beginRow() .labelCell("Type") .beginValueCell().simonTypeImg(simonType,"../../").object(simonType).endValueCell() .simonProperty(simon, "State", "state") .simonProperty(simon, "Enabled", "enabled") .endRow() .beginRow() .simonProperty(simon, "Note", "note", 5) .endRow() .beginRow() .simonProperty(simon, "First Use", "firstUsage") .simonProperty(simon, "Last Reset", "lastReset") .simonProperty(simon, "Last Use", "lastUsage") .endRow() .endSection(); // Specific Stopwatch/Counter section switch(simonType) { case STOPWATCH: htmlBuilder.beginSection("stopwatchPanel", "Stopwatch") .beginRow() .simonProperty(simon, "Counter", "counter") .simonProperty(simon, "Total", "total" ,3) .endRow() .beginRow() .simonProperty(simon, "Min", "min", 3) .simonProperty(simon, "Min Timestamp", "minTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Mean", "mean") .simonProperty(simon, "Standard Deviation", "standardDeviation", 3) .endRow() .beginRow() .simonProperty(simon, "Max", "max", 3) .simonProperty(simon, "Max Timestamp", "maxTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Last", "last", 3) .simonProperty(simon, "Last Timestamp", "lastUsage") .endRow() .beginRow() .simonProperty(simon, "Active", "active") .simonProperty(simon, "Max Active", "maxActive") .simonProperty(simon, "Max Active Timestamp", "maxActiveTimestamp") .endRow() .endSection(); break; case COUNTER: htmlBuilder.beginSection("counterPanel", "Counter") .beginRow() .simonProperty(simon, "Counter", "counter") .endRow() .beginRow() .simonProperty(simon, "Min", "min") .simonProperty(simon, "Min Timestamp", "minTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Max", "max") .simonProperty(simon, "Max Timestamp", "maxTimeStamp") .endRow() .beginRow() .simonProperty(simon, "Increment Sum", "incrementSum") .simonProperty(simon, "Decrement Sum", "decrementSum") .endRow() .endSection(); break; } // Plugins for(DetailPlugin plugin:getContext().getPluginManager().getPluginsByType(DetailPlugin.class)) { if (plugin.supports(simon)) { htmlBuilder.beginSection(plugin.getId()+"Panel", plugin.getLabel()); plugin.executeHtml(getContext(), htmlBuilder, stringifierFactory, simon); htmlBuilder.endSection(); } } // Page footer htmlBuilder.footer(); }
diff --git a/src/main/java/com/drtshock/willie/command/CommandManager.java b/src/main/java/com/drtshock/willie/command/CommandManager.java index 3f327b6..6e18e30 100755 --- a/src/main/java/com/drtshock/willie/command/CommandManager.java +++ b/src/main/java/com/drtshock/willie/command/CommandManager.java @@ -1,71 +1,72 @@ package com.drtshock.willie.command; import java.util.Collection; import java.util.HashMap; import org.pircbotx.Channel; import org.pircbotx.Colors; import org.pircbotx.hooks.Listener; import org.pircbotx.hooks.ListenerAdapter; import org.pircbotx.hooks.events.MessageEvent; import com.drtshock.willie.Willie; import com.drtshock.willie.auth.Auth; public class CommandManager extends ListenerAdapter<Willie> implements Listener<Willie>{ private Willie bot; private HashMap<String, Command> commands; private String cmdPrefix; public CommandManager(Willie bot){ this.bot = bot; this.cmdPrefix = bot.getConfig().getCommandPrefix(); this.commands = new HashMap<>(); } public void registerCommand(Command command){ this.commands.put(command.getName(), command); } public Collection<Command> getCommands(){ return this.commands.values(); } public void setCommandPrefix(String prefix){ this.cmdPrefix = prefix; } @Override public void onMessage(MessageEvent<Willie> event){ String message = event.getMessage().trim(); if(message.toLowerCase().endsWith("o/")){ event.getChannel().sendMessage("\\o"); return; - }else if(message.equalsIgnoreCase("\\o/")){ + } + if(message.equalsIgnoreCase("\\o/")){ event.getChannel().sendMessage("\\o/ Woo!"); return; } if(!message.startsWith(cmdPrefix)){ return; } String[] parts = message.substring(1).split(" "); Channel channel = event.getChannel(); String commandName = parts[0].toLowerCase(); String[] args = new String[parts.length - 1]; System.arraycopy(parts, 1, args, 0, args.length); Command command = this.commands.get(commandName); if(command.isAdminOnly() && !Auth.checkAuth(event.getUser()).isAdmin){ channel.sendMessage(Colors.RED + String.format( "%s, you aren't an admin. Maybe you forgot to identify yourself?", event.getUser().getNick())); return; } command.getHandler().handle(this.bot, channel, event.getUser(), args); } }
true
true
public void onMessage(MessageEvent<Willie> event){ String message = event.getMessage().trim(); if(message.toLowerCase().endsWith("o/")){ event.getChannel().sendMessage("\\o"); return; }else if(message.equalsIgnoreCase("\\o/")){ event.getChannel().sendMessage("\\o/ Woo!"); return; } if(!message.startsWith(cmdPrefix)){ return; } String[] parts = message.substring(1).split(" "); Channel channel = event.getChannel(); String commandName = parts[0].toLowerCase(); String[] args = new String[parts.length - 1]; System.arraycopy(parts, 1, args, 0, args.length); Command command = this.commands.get(commandName); if(command.isAdminOnly() && !Auth.checkAuth(event.getUser()).isAdmin){ channel.sendMessage(Colors.RED + String.format( "%s, you aren't an admin. Maybe you forgot to identify yourself?", event.getUser().getNick())); return; } command.getHandler().handle(this.bot, channel, event.getUser(), args); }
public void onMessage(MessageEvent<Willie> event){ String message = event.getMessage().trim(); if(message.toLowerCase().endsWith("o/")){ event.getChannel().sendMessage("\\o"); return; } if(message.equalsIgnoreCase("\\o/")){ event.getChannel().sendMessage("\\o/ Woo!"); return; } if(!message.startsWith(cmdPrefix)){ return; } String[] parts = message.substring(1).split(" "); Channel channel = event.getChannel(); String commandName = parts[0].toLowerCase(); String[] args = new String[parts.length - 1]; System.arraycopy(parts, 1, args, 0, args.length); Command command = this.commands.get(commandName); if(command.isAdminOnly() && !Auth.checkAuth(event.getUser()).isAdmin){ channel.sendMessage(Colors.RED + String.format( "%s, you aren't an admin. Maybe you forgot to identify yourself?", event.getUser().getNick())); return; } command.getHandler().handle(this.bot, channel, event.getUser(), args); }
diff --git a/src/InfraR.java b/src/InfraR.java index 74e9791..ed097da 100644 --- a/src/InfraR.java +++ b/src/InfraR.java @@ -1,136 +1,140 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author geza */ import orc.*; public class InfraR extends java.lang.Thread { public boolean running = true; public float[] leftMotorAction = null; public float[] leftMotorWeight = null; public float[] rightMotorAction = null; public float[] rightMotorWeight = null; public int idx = 0; public static double bound(double v, double max, double min) { if (v > max) return max; else if (v < min) return min; else return v; } public static void shiftleft(double[] a, double v) { int i = 0; for (; i < a.length-1; ++i) { a[i] = a[i+1]; } a[i] = v; } public static double averageArray(double[] a) { double total = 0.0; for (int i = 0; i < a.length; ++i) { total += a[i]; } return total / (double)a.length; } public void run() { try { byte[] inet = {(byte)192, (byte)168, (byte)237, (byte)7}; Orc o = new orc.Orc(java.net.Inet4Address.getByAddress(inet)); leftMotorWeight[idx] = 0.5f; rightMotorWeight[idx] = 0.5f; AnalogInput leftIR = new AnalogInput(o, 7); AnalogInput rightIR = new AnalogInput(o, 1); final double desv = 100.0; - final double kp = 0.005; - final double kd = 0.002; + final double kp = 0.002; + final double kd = 0.001; double prevleft = leftIR.getVoltage(); double prevright = rightIR.getVoltage(); double[] leftIRreadings = new double[3]; double[] rightIRreadings = new double[3]; java.util.Arrays.fill(leftIRreadings, prevleft); java.util.Arrays.fill(rightIRreadings, prevright); while (running) { shiftleft(leftIRreadings, 62.5/leftIR.getVoltage()); shiftleft(rightIRreadings, 62.5/rightIR.getVoltage()); double left = averageArray(leftIRreadings);//a.getVoltage() //double left = 999999.0; double right = averageArray(rightIRreadings); //double right = averageArray(rightIRreadings); System.out.println("left is "+left+"right is "+right); //System.out.println(right); double lspeed; double rspeed; - if (left > right) { + if (left > 200.0 && right > 200.0) { // just go straight + lspeed = 0.6; + rspeed = 0.6; + } + else if (left > right) { double error = left-desv; - if (error > 20.0) error = 20.0; - if (error < 20.0) error = -20.0; - double basevel = bound(1.0-error, 0.7, 0.6); + if (error > 100.0) error = 100.0; + if (error < -100.0) error = -100.0; + double basevel = bound(1.0-error, 0.7, 0.4); lspeed = -(kp*error-kd*(left-prevleft))+basevel; rspeed = (kp*error-kd*(left-prevleft))+basevel; } else { double error = right-desv; - if (error > 20.0) error = 20.0; - if (error < 20.0) error = -20.0; - double basevel = bound(1.0-error, 0.7, 0.6); + if (error > 100.0) error = 100.0; + if (error < -100.0) error = -100.0; + double basevel = bound(1.0-error, 0.7, 0.4); lspeed = (kp*error-kd*(right-prevright))+basevel; rspeed = -(kp*error-kd*(right-prevright))+basevel; } prevleft = left; prevright = right; /* if (lspeed > rspeed) { rspeed += basevel-Math.abs(lspeed); lspeed = basevel; } else { lspeed += basevel-Math.abs(rspeed); rspeed = basevel; } */ leftMotorAction[idx] = (float)lspeed; rightMotorAction[idx] = (float)rspeed; java.lang.Thread.sleep(20); } /* log distance ir final float dd = 30.0f; // desired distance final float k = 0.05f; // proportionality constant while (running) { float d = (62.5f/(float)a.getVoltage())-20.0f; float lspeed = k*(dd-d); float rspeed = -lspeed; if (lspeed > rspeed) { rspeed += (0.7f - lspeed); lspeed = 0.7f; } else { lspeed += (0.7f - rspeed); rspeed = 0.7f; } leftMotorAction[idx] = lspeed; rightMotorAction[idx] = rspeed; System.out.println(d); } */ } catch (Exception e) { e.printStackTrace(); } } public void setup(Arbiter a, int ActionWeightIndex) { idx = ActionWeightIndex; leftMotorAction = a.leftMotorAction; leftMotorWeight = a.leftMotorWeight; rightMotorAction = a.rightMotorAction; rightMotorWeight = a.rightMotorWeight; } public void bye() { running = false; } }
false
true
public void run() { try { byte[] inet = {(byte)192, (byte)168, (byte)237, (byte)7}; Orc o = new orc.Orc(java.net.Inet4Address.getByAddress(inet)); leftMotorWeight[idx] = 0.5f; rightMotorWeight[idx] = 0.5f; AnalogInput leftIR = new AnalogInput(o, 7); AnalogInput rightIR = new AnalogInput(o, 1); final double desv = 100.0; final double kp = 0.005; final double kd = 0.002; double prevleft = leftIR.getVoltage(); double prevright = rightIR.getVoltage(); double[] leftIRreadings = new double[3]; double[] rightIRreadings = new double[3]; java.util.Arrays.fill(leftIRreadings, prevleft); java.util.Arrays.fill(rightIRreadings, prevright); while (running) { shiftleft(leftIRreadings, 62.5/leftIR.getVoltage()); shiftleft(rightIRreadings, 62.5/rightIR.getVoltage()); double left = averageArray(leftIRreadings);//a.getVoltage() //double left = 999999.0; double right = averageArray(rightIRreadings); //double right = averageArray(rightIRreadings); System.out.println("left is "+left+"right is "+right); //System.out.println(right); double lspeed; double rspeed; if (left > right) { double error = left-desv; if (error > 20.0) error = 20.0; if (error < 20.0) error = -20.0; double basevel = bound(1.0-error, 0.7, 0.6); lspeed = -(kp*error-kd*(left-prevleft))+basevel; rspeed = (kp*error-kd*(left-prevleft))+basevel; } else { double error = right-desv; if (error > 20.0) error = 20.0; if (error < 20.0) error = -20.0; double basevel = bound(1.0-error, 0.7, 0.6); lspeed = (kp*error-kd*(right-prevright))+basevel; rspeed = -(kp*error-kd*(right-prevright))+basevel; } prevleft = left; prevright = right; /* if (lspeed > rspeed) { rspeed += basevel-Math.abs(lspeed); lspeed = basevel; } else { lspeed += basevel-Math.abs(rspeed); rspeed = basevel; } */ leftMotorAction[idx] = (float)lspeed; rightMotorAction[idx] = (float)rspeed; java.lang.Thread.sleep(20); } /* log distance ir final float dd = 30.0f; // desired distance final float k = 0.05f; // proportionality constant while (running) { float d = (62.5f/(float)a.getVoltage())-20.0f; float lspeed = k*(dd-d); float rspeed = -lspeed; if (lspeed > rspeed) { rspeed += (0.7f - lspeed); lspeed = 0.7f; } else { lspeed += (0.7f - rspeed); rspeed = 0.7f; } leftMotorAction[idx] = lspeed; rightMotorAction[idx] = rspeed; System.out.println(d); } */ } catch (Exception e) { e.printStackTrace(); } }
public void run() { try { byte[] inet = {(byte)192, (byte)168, (byte)237, (byte)7}; Orc o = new orc.Orc(java.net.Inet4Address.getByAddress(inet)); leftMotorWeight[idx] = 0.5f; rightMotorWeight[idx] = 0.5f; AnalogInput leftIR = new AnalogInput(o, 7); AnalogInput rightIR = new AnalogInput(o, 1); final double desv = 100.0; final double kp = 0.002; final double kd = 0.001; double prevleft = leftIR.getVoltage(); double prevright = rightIR.getVoltage(); double[] leftIRreadings = new double[3]; double[] rightIRreadings = new double[3]; java.util.Arrays.fill(leftIRreadings, prevleft); java.util.Arrays.fill(rightIRreadings, prevright); while (running) { shiftleft(leftIRreadings, 62.5/leftIR.getVoltage()); shiftleft(rightIRreadings, 62.5/rightIR.getVoltage()); double left = averageArray(leftIRreadings);//a.getVoltage() //double left = 999999.0; double right = averageArray(rightIRreadings); //double right = averageArray(rightIRreadings); System.out.println("left is "+left+"right is "+right); //System.out.println(right); double lspeed; double rspeed; if (left > 200.0 && right > 200.0) { // just go straight lspeed = 0.6; rspeed = 0.6; } else if (left > right) { double error = left-desv; if (error > 100.0) error = 100.0; if (error < -100.0) error = -100.0; double basevel = bound(1.0-error, 0.7, 0.4); lspeed = -(kp*error-kd*(left-prevleft))+basevel; rspeed = (kp*error-kd*(left-prevleft))+basevel; } else { double error = right-desv; if (error > 100.0) error = 100.0; if (error < -100.0) error = -100.0; double basevel = bound(1.0-error, 0.7, 0.4); lspeed = (kp*error-kd*(right-prevright))+basevel; rspeed = -(kp*error-kd*(right-prevright))+basevel; } prevleft = left; prevright = right; /* if (lspeed > rspeed) { rspeed += basevel-Math.abs(lspeed); lspeed = basevel; } else { lspeed += basevel-Math.abs(rspeed); rspeed = basevel; } */ leftMotorAction[idx] = (float)lspeed; rightMotorAction[idx] = (float)rspeed; java.lang.Thread.sleep(20); } /* log distance ir final float dd = 30.0f; // desired distance final float k = 0.05f; // proportionality constant while (running) { float d = (62.5f/(float)a.getVoltage())-20.0f; float lspeed = k*(dd-d); float rspeed = -lspeed; if (lspeed > rspeed) { rspeed += (0.7f - lspeed); lspeed = 0.7f; } else { lspeed += (0.7f - rspeed); rspeed = 0.7f; } leftMotorAction[idx] = lspeed; rightMotorAction[idx] = rspeed; System.out.println(d); } */ } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java b/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java index 68824ad3..12021862 100644 --- a/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java +++ b/src/uk/me/parabola/imgfmt/app/trergn/Subdivision.java @@ -1,537 +1,541 @@ /* * Copyright (C) 2006 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * Author: Steve Ratcliffe * Create date: 07-Dec-2006 */ package uk.me.parabola.imgfmt.app.trergn; import java.util.ArrayList; import java.util.List; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.Coord; import uk.me.parabola.imgfmt.app.ImgFileWriter; import uk.me.parabola.imgfmt.app.Label; import uk.me.parabola.imgfmt.app.lbl.LBLFile; import uk.me.parabola.log.Logger; /** * The map is divided into areas, depending on the zoom level. These are * known as subdivisions. * * A subdivision 'belongs' to a zoom level and cannot be interpreted correctly * without knowing the <i>bitsPerCoord</i> of the associated zoom level. * * Subdivisions also form a tree as subdivisions are further divided at * lower levels. The subdivisions need to know their child divisions * because this information is represented in the map. * * @author Steve Ratcliffe */ public class Subdivision { private static final Logger log = Logger.getLogger(Subdivision.class); private static final int MAP_POINT = 0; private static final int MAP_INDEXED_POINT = 1; private static final int MAP_LINE = 2; private static final int MAP_SHAPE = 3; private final LBLFile lblFile; private final RGNFile rgnFile; // The start pointer is set for read and write. The end pointer is only // set for subdivisions that are read from a file. private int startRgnPointer; private int endRgnPointer; private int lastMapElement; // The zoom level contains the number of bits per coordinate which is // critical for scaling quantities by. private final Zoom zoomLevel; private boolean hasPoints; private boolean hasIndPoints; private boolean hasPolylines; private boolean hasPolygons; private int numPolylines; // The location of the central point, not scaled AFAIK private final int longitude; private final int latitude; // The width and the height in map units scaled by the bits-per-coordinate // that applies at the map level. private final int width; private final int height; private int number; // Set if this is the last one. private boolean last; private final List<Subdivision> divisions = new ArrayList<Subdivision>(); private int extTypeAreasOffset; private int extTypeLinesOffset; private int extTypePointsOffset; private int extTypeAreasSize; private int extTypeLinesSize; private int extTypePointsSize; /** * Subdivisions can not be created directly, use either the * {@link #topLevelSubdivision} or {@link #createSubdivision} factory * methods. * * @param ifiles The internal files. * @param area The area this subdivision should cover. * @param z The zoom level. */ private Subdivision(InternalFiles ifiles, Area area, Zoom z) { this.lblFile = ifiles.getLblFile(); this.rgnFile = ifiles.getRgnFile(); this.zoomLevel = z; int shift = getShift(); int mask = getMask(); this.latitude = (area.getMinLat() + area.getMaxLat())/2; this.longitude = (area.getMinLong() + area.getMaxLong())/2; int w = ((area.getWidth() + 1)/2 + mask) >> shift; - if (w > 0x7fff) + if (w > 0x7fff) { + log.warn("Subdivision width is " + w + " at " + new Coord(latitude, longitude)); w = 0x7fff; + } int h = ((area.getHeight() + 1)/2 + mask) >> shift; - if (h > 0xffff) + if (h > 0xffff) { + log.warn("Subdivision height is " + h + " at " + new Coord(latitude, longitude)); h = 0xffff; + } this.width = w; this.height = h; } private Subdivision(Zoom z, SubdivData data) { lblFile = null; rgnFile = null; zoomLevel = z; latitude = data.getLat(); longitude = data.getLon(); this.width = data.getWidth(); this.height = data.getHeight(); startRgnPointer = data.getRgnPointer(); endRgnPointer = data.getEndRgnOffset(); int elem = data.getFlags(); if ((elem & 0x10) != 0) setHasPoints(true); if ((elem & 0x20) != 0) setHasIndPoints(true); if ((elem & 0x40) != 0) setHasPolylines(true); if ((elem & 0x80) != 0) setHasPolygons(true); } /** * Create a subdivision at a given zoom level. * * @param ifiles The RGN and LBL ifiles. * @param area The (unshifted) area that the subdivision covers. * @param zoom The zoom level that this division occupies. * * @return A new subdivision. */ public Subdivision createSubdivision(InternalFiles ifiles, Area area, Zoom zoom) { Subdivision div = new Subdivision(ifiles, area, zoom); zoom.addSubdivision(div); addSubdivision(div); return div; } /** * This should be called only once per map to create the top level * subdivision. The top level subdivision covers the whole map and it * must be empty. * * @param ifiles The LBL and RGN ifiles. * @param area The area bounded by the map. * @param zoom The zoom level which must be the highest (least detailed) * zoom in the map. * * @return The new subdivision. */ public static Subdivision topLevelSubdivision(InternalFiles ifiles, Area area, Zoom zoom) { Subdivision div = new Subdivision(ifiles, area, zoom); zoom.addSubdivision(div); return div; } /** * Create a subdivision that only contains the number. This is only * used when reading cities and similar such usages that do not really * require the full subdivision to be present. * @param number The subdivision number. * @return An empty subdivision. Any operation other than getting the * subdiv number is likely to fail. */ public static Subdivision createEmptySubdivision(int number) { Subdivision sd = new Subdivision(null, new SubdivData(0,0,0,0,0,0,0)); sd.setNumber(number); return sd; } public static Subdivision readSubdivision(Zoom zoom, SubdivData subdivData) { return new Subdivision(zoom, subdivData); } public Zoom getZoom() { return zoomLevel; } /** * Get the shift value, that is the number of bits to left shift by for * values that need to be saved shifted in the file. Related to the * resolution. * * @return The shift value. It is 24 minus the number of bits per coord. * @see #getResolution() */ public final int getShift() { return 24 - zoomLevel.getResolution(); } /** * Get the shift mask. The bits that will be lost due to the resolution * shift level. * * @return A bit mask with the lower <i>shift</i> bits set. */ public int getMask() { return (1 << getShift()) - 1; } /** * Get the resolution of this division. Resolution goes from 1 to 24 * and the higher the number the more detail there is. * * @return The resolution. */ public final int getResolution() { return zoomLevel.getResolution(); } /** * Format this record to the file. * * @param file The file to write to. */ public void write(ImgFileWriter file) { log.debug("write subdiv", latitude, longitude); file.put3(startRgnPointer); file.put(getType()); file.put3(longitude); file.put3(latitude); assert width <= 0x7fff; assert height <= 0xffff; file.putChar((char) (width | ((last) ? 0x8000 : 0))); file.putChar((char) height); if (!divisions.isEmpty()) { file.putChar((char) getNextLevel()); } } public Point createPoint(String name) { Point p = new Point(this); Label label = lblFile.newLabel(name); p.setLabel(label); return p; } public Polyline createLine(String name, String ref) { Label label = lblFile.newLabel(name); Polyline pl = new Polyline(this); pl.setLabel(label); if(ref != null) { // ref may contain multiple ids separated by ";" for(String r : ref.split(";")) { String tr = r.trim(); if(tr.length() > 0) { //System.err.println("Adding ref " + tr + " to road " + name); pl.addRefLabel(lblFile.newLabel(tr)); } } } return pl; } public void setPolylineNumber(Polyline pl) { pl.setNumber(++numPolylines); } public Polygon createPolygon(String name) { Label label = lblFile.newLabel(name); Polygon pg = new Polygon(this); pg.setLabel(label); return pg; } public void setNumber(int n) { number = n; } public void setLast(boolean last) { this.last = last; } public void setStartRgnPointer(int startRgnPointer) { this.startRgnPointer = startRgnPointer; } public int getStartRgnPointer() { return startRgnPointer; } public int getEndRgnPointer() { return endRgnPointer; } public int getLongitude() { return longitude; } public int getLatitude() { return latitude; } public void setHasPoints(boolean hasPoints) { this.hasPoints = hasPoints; } public void setHasIndPoints(boolean hasIndPoints) { this.hasIndPoints = hasIndPoints; } public void setHasPolylines(boolean hasPolylines) { this.hasPolylines = hasPolylines; } public void setHasPolygons(boolean hasPolygons) { this.hasPolygons = hasPolygons; } public boolean hasPoints() { return hasPoints; } public boolean hasIndPoints() { return hasIndPoints; } public boolean hasPolylines() { return hasPolylines; } public boolean hasPolygons() { return hasPolygons; } /** * Needed if it exists and is not first, ie there is a points * section. * @return true if pointer needed */ public boolean needsIndPointPtr() { return hasIndPoints && hasPoints; } /** * Needed if it exists and is not first, ie there is a points or * indexed points section. * @return true if pointer needed. */ public boolean needsPolylinePtr() { return hasPolylines && (hasPoints || hasIndPoints); } /** * As this is last in the list it is needed if it exists and there * is another section. * @return true if pointer needed. */ public boolean needsPolygonPtr() { return hasPolygons && (hasPoints || hasIndPoints || hasPolylines); } public String toString() { return "Sub" + zoomLevel + '(' + new Coord(latitude, longitude).toOSMURL() + ')'; } /** * Get a type that shows if this area has lines, points etc. * * @return A code showing what kinds of element are in this subdivision. */ private byte getType() { byte b = 0; if (hasPoints) b |= 0x10; if (hasIndPoints) b |= 0x20; if (hasPolylines) b |= 0x40; if (hasPolygons) b |= 0x80; return b; } /** * Get the number of the first subdivision at the next level. * @return The first subdivision at the next level. */ private int getNextLevel() { return divisions.get(0).getNumber(); } public boolean hasNextLevel() { return !divisions.isEmpty(); } public void startDivision() { rgnFile.startDivision(this); extTypeAreasOffset = rgnFile.getExtTypeAreasSize(); extTypeLinesOffset = rgnFile.getExtTypeLinesSize(); extTypePointsOffset = rgnFile.getExtTypePointsSize(); } public void endDivision() { extTypeAreasSize = rgnFile.getExtTypeAreasSize() - extTypeAreasOffset; extTypeLinesSize = rgnFile.getExtTypeLinesSize() - extTypeLinesOffset; extTypePointsSize = rgnFile.getExtTypePointsSize() - extTypePointsOffset; } public void writeExtTypeOffsetsRecord(ImgFileWriter file) { file.putInt(extTypeAreasOffset); file.putInt(extTypeLinesOffset); file.putInt(extTypePointsOffset); int kinds = 0; if(extTypeAreasSize != 0) ++kinds; if(extTypeLinesSize != 0) ++kinds; if(extTypePointsSize != 0) ++kinds; file.put((byte)kinds); } public void writeLastExtTypeOffsetsRecord(ImgFileWriter file) { file.putInt(rgnFile.getExtTypeAreasSize()); file.putInt(rgnFile.getExtTypeLinesSize()); file.putInt(rgnFile.getExtTypePointsSize()); file.put((byte)0); } /** * Add this subdivision as our child at the next level. Each subdivision * can be further divided into smaller divisions. They form a tree like * arrangement. * * @param sd One of our subdivisions. */ private void addSubdivision(Subdivision sd) { divisions.add(sd); } public int getNumber() { return number; } /** * We are starting to draw the points. These must be done first. */ public void startPoints() { if (lastMapElement > MAP_POINT) throw new IllegalStateException("Points must be drawn first"); lastMapElement = MAP_POINT; } /** * We are starting to draw the lines. These must be done before * polygons. */ public void startIndPoints() { if (lastMapElement > MAP_INDEXED_POINT) throw new IllegalStateException("Indexed points must be done before lines and polygons"); lastMapElement = MAP_INDEXED_POINT; rgnFile.setIndPointPtr(); } /** * We are starting to draw the lines. These must be done before * polygons. */ public void startLines() { if (lastMapElement > MAP_LINE) throw new IllegalStateException("Lines must be done before polygons"); lastMapElement = MAP_LINE; rgnFile.setPolylinePtr(); } /** * We are starting to draw the shapes. This is done last. */ public void startShapes() { lastMapElement = MAP_SHAPE; rgnFile.setPolygonPtr(); } /** * Convert an absolute Lat to a local, shifted value */ public int roundLatToLocalShifted(int absval) { int shift = getShift(); int val = absval - getLatitude(); val += ((1 << shift) / 2); return (val >> shift); } /** * Convert an absolute Lon to a local, shifted value */ public int roundLonToLocalShifted(int absval) { int shift = getShift(); int val = absval - getLongitude(); val += ((1 << shift) / 2); return (val >> shift); } }
false
true
private Subdivision(InternalFiles ifiles, Area area, Zoom z) { this.lblFile = ifiles.getLblFile(); this.rgnFile = ifiles.getRgnFile(); this.zoomLevel = z; int shift = getShift(); int mask = getMask(); this.latitude = (area.getMinLat() + area.getMaxLat())/2; this.longitude = (area.getMinLong() + area.getMaxLong())/2; int w = ((area.getWidth() + 1)/2 + mask) >> shift; if (w > 0x7fff) w = 0x7fff; int h = ((area.getHeight() + 1)/2 + mask) >> shift; if (h > 0xffff) h = 0xffff; this.width = w; this.height = h; }
private Subdivision(InternalFiles ifiles, Area area, Zoom z) { this.lblFile = ifiles.getLblFile(); this.rgnFile = ifiles.getRgnFile(); this.zoomLevel = z; int shift = getShift(); int mask = getMask(); this.latitude = (area.getMinLat() + area.getMaxLat())/2; this.longitude = (area.getMinLong() + area.getMaxLong())/2; int w = ((area.getWidth() + 1)/2 + mask) >> shift; if (w > 0x7fff) { log.warn("Subdivision width is " + w + " at " + new Coord(latitude, longitude)); w = 0x7fff; } int h = ((area.getHeight() + 1)/2 + mask) >> shift; if (h > 0xffff) { log.warn("Subdivision height is " + h + " at " + new Coord(latitude, longitude)); h = 0xffff; } this.width = w; this.height = h; }
diff --git a/illaclient/src/illarion/client/world/GameMapProcessor2.java b/illaclient/src/illarion/client/world/GameMapProcessor2.java index a296f954..42fe80cc 100644 --- a/illaclient/src/illarion/client/world/GameMapProcessor2.java +++ b/illaclient/src/illarion/client/world/GameMapProcessor2.java @@ -1,201 +1,203 @@ /* * This file is part of the Illarion Client. * * Copyright © 2013 - Illarion e.V. * * The Illarion Client is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Illarion Client is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Illarion Client. If not, see <http://www.gnu.org/licenses/>. */ package illarion.client.world; import illarion.client.graphics.MapDisplayManager; import illarion.common.types.Location; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; /** * This utility class is used to process the map tiles and ensure that they are properly linked and assigned to each * other. * * @author Martin Karing &lt;[email protected]&gt; */ public class GameMapProcessor2 { /** * Process a single new tile. * * @param tile the tile to process */ public static void processTile(final MapTile tile) { final Location playerLocation = World.getPlayer().getLocation(); final MapTile tileAbove = getFirstTileAbove(tile.getLocation(), playerLocation.getScZ() + 2, true); final MapTile tileBelow = getFirstTileBelow(tile.getLocation(), playerLocation.getScZ() - 2, true); if (tileAbove != null) { tile.setObstructingTile(tileAbove); } if (tileBelow != null) { tileBelow.setObstructingTile(tile); } // check if the tile is at or below the player location. In this case the map groups do not matter. if (tile.getLocation().getScZ() <= playerLocation.getScZ()) { return; } final List<MapGroup> groups = getSurroundingMapGroups(tile.getLocation()); final MapGroup tileGroup; if (groups.isEmpty()) { tileGroup = new MapGroup(); tile.setMapGroup(tileGroup); } else { tileGroup = groups.get(0); tile.setMapGroup(tileGroup); for (int i = 1; i < groups.size(); i++) { groups.get(i).setParent(tileGroup); } } if (tileAbove != null) { final MapGroup tileAboveGroup = tileAbove.getMapGroup(); - if (tileAboveGroup != null) { - tileAboveGroup.addOverwritingGroup(tileGroup); + final MapGroup tileAboveGroupRoot = (tileAboveGroup == null) ? null : tileAboveGroup.getRootGroup(); + if (tileAboveGroupRoot != null) { + tileAboveGroupRoot.addOverwritingGroup(tileGroup); } } if (tileBelow != null) { final MapGroup tileBelowGroup = tileBelow.getMapGroup(); - if (tileBelowGroup != null) { - tileGroup.addOverwritingGroup(tileBelowGroup); + final MapGroup tileBelowGroupRoot = (tileBelowGroup == null) ? null : tileBelowGroup.getRootGroup(); + if (tileBelowGroupRoot != null) { + tileGroup.addOverwritingGroup(tileBelowGroupRoot); } } } @Nullable private static MapGroup lastInsideGroup; public static void checkInside() { final Location playerLocation = World.getPlayer().getCharacter().getLocation(); final MapTile tileAbove = getFirstTileAbove(playerLocation, playerLocation.getScZ() + 2, false); final MapGroup realTileAboveGroup = (tileAbove == null) ? null : tileAbove.getMapGroup(); final MapGroup tileAboveGroup = (realTileAboveGroup == null) ? null : realTileAboveGroup.getRootGroup(); if (tileAboveGroup == null) { if (lastInsideGroup != null) { lastInsideGroup.setHidden(false); lastInsideGroup = null; } World.getWeather().setOutside(true); } else { if (lastInsideGroup != null) { if (lastInsideGroup == tileAboveGroup) { return; } lastInsideGroup.setHidden(false); } tileAboveGroup.setHidden(true); lastInsideGroup = tileAboveGroup; World.getWeather().setOutside(false); } } @Nullable private static MapTile getFirstTileBelow(final Location startLocation, final int zLimit, final boolean perceptiveOffset) { if (startLocation.getScZ() <= zLimit) { return null; } int currentX = startLocation.getScX(); int currentY = startLocation.getScY(); int currentZ = startLocation.getScZ(); while (currentZ > zLimit) { if (perceptiveOffset) { currentX += MapDisplayManager.TILE_PERSPECTIVE_OFFSET; currentY -= MapDisplayManager.TILE_PERSPECTIVE_OFFSET; } currentZ--; final MapTile tile = World.getMap().getMapAt(currentX, currentY, currentZ); if (tile != null) { return tile; } } return null; } private static List<MapTile> getAllTilesAbove(final Location startLocation, final int zLimit, final boolean perceptiveOffset) { final List<MapTile> tileList = new ArrayList<MapTile>(); Location currentLocation = startLocation; while (true) { final MapTile currentTile = getFirstTileAbove(currentLocation, zLimit, perceptiveOffset); if (currentTile == null) { break; } tileList.add(currentTile); currentLocation = currentTile.getLocation(); } return tileList; } @Nullable private static MapTile getFirstTileAbove(final Location startLocation, final int zLimit, final boolean perceptiveOffset) { if (startLocation.getScZ() >= zLimit) { return null; } int currentX = startLocation.getScX(); int currentY = startLocation.getScY(); int currentZ = startLocation.getScZ(); while (currentZ < zLimit) { if (perceptiveOffset) { currentX -= MapDisplayManager.TILE_PERSPECTIVE_OFFSET; currentY += MapDisplayManager.TILE_PERSPECTIVE_OFFSET; } currentZ++; final MapTile tile = World.getMap().getMapAt(currentX, currentY, currentZ); if (tile != null) { return tile; } } return null; } private static List<MapGroup> getSurroundingMapGroups(final Location startLocation) { final List<MapGroup> groupList = new ArrayList<MapGroup>(); for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { if ((x == 0) && (y == 0)) { continue; } final MapTile tile = World.getMap().getMapAt(startLocation.getScX() + x, startLocation.getScY() + y, startLocation.getScZ()); if (tile != null) { MapGroup group = tile.getMapGroup(); if (group != null) { group = group.getRootGroup(); } if ((group != null) && !groupList.contains(group)) { groupList.add(group); } } } } return groupList; } }
false
true
public static void processTile(final MapTile tile) { final Location playerLocation = World.getPlayer().getLocation(); final MapTile tileAbove = getFirstTileAbove(tile.getLocation(), playerLocation.getScZ() + 2, true); final MapTile tileBelow = getFirstTileBelow(tile.getLocation(), playerLocation.getScZ() - 2, true); if (tileAbove != null) { tile.setObstructingTile(tileAbove); } if (tileBelow != null) { tileBelow.setObstructingTile(tile); } // check if the tile is at or below the player location. In this case the map groups do not matter. if (tile.getLocation().getScZ() <= playerLocation.getScZ()) { return; } final List<MapGroup> groups = getSurroundingMapGroups(tile.getLocation()); final MapGroup tileGroup; if (groups.isEmpty()) { tileGroup = new MapGroup(); tile.setMapGroup(tileGroup); } else { tileGroup = groups.get(0); tile.setMapGroup(tileGroup); for (int i = 1; i < groups.size(); i++) { groups.get(i).setParent(tileGroup); } } if (tileAbove != null) { final MapGroup tileAboveGroup = tileAbove.getMapGroup(); if (tileAboveGroup != null) { tileAboveGroup.addOverwritingGroup(tileGroup); } } if (tileBelow != null) { final MapGroup tileBelowGroup = tileBelow.getMapGroup(); if (tileBelowGroup != null) { tileGroup.addOverwritingGroup(tileBelowGroup); } } }
public static void processTile(final MapTile tile) { final Location playerLocation = World.getPlayer().getLocation(); final MapTile tileAbove = getFirstTileAbove(tile.getLocation(), playerLocation.getScZ() + 2, true); final MapTile tileBelow = getFirstTileBelow(tile.getLocation(), playerLocation.getScZ() - 2, true); if (tileAbove != null) { tile.setObstructingTile(tileAbove); } if (tileBelow != null) { tileBelow.setObstructingTile(tile); } // check if the tile is at or below the player location. In this case the map groups do not matter. if (tile.getLocation().getScZ() <= playerLocation.getScZ()) { return; } final List<MapGroup> groups = getSurroundingMapGroups(tile.getLocation()); final MapGroup tileGroup; if (groups.isEmpty()) { tileGroup = new MapGroup(); tile.setMapGroup(tileGroup); } else { tileGroup = groups.get(0); tile.setMapGroup(tileGroup); for (int i = 1; i < groups.size(); i++) { groups.get(i).setParent(tileGroup); } } if (tileAbove != null) { final MapGroup tileAboveGroup = tileAbove.getMapGroup(); final MapGroup tileAboveGroupRoot = (tileAboveGroup == null) ? null : tileAboveGroup.getRootGroup(); if (tileAboveGroupRoot != null) { tileAboveGroupRoot.addOverwritingGroup(tileGroup); } } if (tileBelow != null) { final MapGroup tileBelowGroup = tileBelow.getMapGroup(); final MapGroup tileBelowGroupRoot = (tileBelowGroup == null) ? null : tileBelowGroup.getRootGroup(); if (tileBelowGroupRoot != null) { tileGroup.addOverwritingGroup(tileBelowGroupRoot); } } }
diff --git a/src/main/java/org/thomnichols/android/gmarks/BookmarksListActivity.java b/src/main/java/org/thomnichols/android/gmarks/BookmarksListActivity.java index cbc4f40..5fc1cc0 100644 --- a/src/main/java/org/thomnichols/android/gmarks/BookmarksListActivity.java +++ b/src/main/java/org/thomnichols/android/gmarks/BookmarksListActivity.java @@ -1,198 +1,199 @@ package org.thomnichols.android.gmarks; import org.thomnichols.android.gmarks.R; import android.app.ListActivity; import android.app.SearchManager; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.database.CursorWrapper; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import android.widget.AdapterView.OnItemLongClickListener; public class BookmarksListActivity extends ListActivity { private static final String TAG = "BOOKMARKS LIST"; // Menu item ids public static final int CONTEXT_MENU_ITEM_DELETE = Menu.FIRST; public static final int CONTEXT_MENU_ITEM_EDIT = Menu.FIRST + 1; static final String KEY_BOOKMARKS_SORT_PREF = "bookmarks_sort_by"; static final int SORT_MODIFIED = 0; static final int SORT_TITLE = 1; protected int currentSort = SORT_MODIFIED; /** * The columns we are interested in from the database */ private static final String[] PROJECTION = new String[] { Bookmark.Columns._ID, // 0 Bookmark.Columns.TITLE, // 1 Bookmark.Columns.URL, // 2 Bookmark.Columns.HOST, // 3 }; // the cursor index of the url column private static final int COLUMN_INDEX_URL = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); // bind an action for long-press (not a context menu) getListView().setOnItemLongClickListener(this.longClickListener); this.currentSort = PreferenceManager.getDefaultSharedPreferences(this) .getInt(KEY_BOOKMARKS_SORT_PREF, SORT_MODIFIED); Intent intent = getIntent(); + if (intent.getData() == null) intent.setData(Bookmark.CONTENT_URI); Uri uri = intent.getData(); if ( Intent.ACTION_PICK.equals(intent.getAction()) ) { setTitle(R.string.choose_bookmark); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); uri = uri.buildUpon().appendPath("search") .appendQueryParameter("q", query).build(); intent.setData( uri ); this.setTitle("GMarks search results for '" + query + "'"); } else { String labelName = uri.getQueryParameter("label"); if ( labelName != null ) this.setTitle("Bookmarks for label '" + labelName + "'"); } Cursor cursor = getCursorFromIntent(intent); // Used to map notes entries from the database to views SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.bookmarkslist_item, cursor, new String[] { Bookmark.Columns.TITLE, Bookmark.Columns.HOST }, new int[] { R.id.title, R.id.host } ); setListAdapter(adapter); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); ((SimpleCursorAdapter)this.getListAdapter()).changeCursor( getCursorFromIntent(intent) ); } protected Cursor getCursorFromIntent(Intent intent) { if (intent.getData() == null) intent.setData(Bookmark.CONTENT_URI); String sort = currentSort == SORT_MODIFIED ? Bookmark.Columns.SORT_MODIFIED : Bookmark.Columns.SORT_TITLE; return managedQuery( getIntent().getData(), PROJECTION, null, null, sort ); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.bookmark_list, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); final boolean haveItems = getListAdapter().getCount() > 0; if ( haveItems ) { // menu.findItem(R.id.menu_delete).setVisible( true ); } else menu.removeGroup(Menu.CATEGORY_ALTERNATIVE); menu.findItem(R.id.menu_sort_title).setVisible( this.currentSort != SORT_TITLE ); menu.findItem(R.id.menu_sort_date).setVisible( this.currentSort != SORT_MODIFIED ); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch ( item.getItemId() ) { case R.id.menu_add: Intent intent = new Intent(Intent.ACTION_INSERT); intent.setType(Bookmark.CONTENT_ITEM_TYPE); String label = getIntent().getData().getQueryParameter("label"); if ( label != null ) intent.putExtra("label", label); // Launch activity to insert a new item startActivity(intent); return true; case R.id.menu_sort_title: this.currentSort = SORT_TITLE; PreferenceManager.getDefaultSharedPreferences(this) .edit().putInt(KEY_BOOKMARKS_SORT_PREF, SORT_TITLE).commit(); ((SimpleCursorAdapter)getListAdapter()).changeCursor( getCursorFromIntent(getIntent()) ); break; case R.id.menu_sort_date: this.currentSort = SORT_MODIFIED; PreferenceManager.getDefaultSharedPreferences(this) .edit().putInt(KEY_BOOKMARKS_SORT_PREF, SORT_MODIFIED).commit(); ((SimpleCursorAdapter)getListAdapter()).changeCursor( getCursorFromIntent(getIntent()) ); break; case R.id.menu_delete: Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId()); startActivity( new Intent(Intent.ACTION_DELETE, uri) ); break; case R.id.menu_sync: Log.d(TAG, "Starting sync..."); Toast.makeText(this, "Starting sync...", Toast.LENGTH_SHORT).show(); // TODO only sync bookmarks for this label? new RemoteSyncTask(this).execute(); } return super.onOptionsItemSelected(item); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // The caller is waiting for us to return a note selected by // the user. The have clicked on one, so return it now. setResult(RESULT_OK, new Intent().setData(uri)); finish(); } else { String bookmarkURL = ((CursorWrapper)l.getItemAtPosition(position)) .getString(COLUMN_INDEX_URL); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(bookmarkURL))); } } protected OnItemLongClickListener longClickListener = new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> adapter, View v, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); startActivity(new Intent(Intent.ACTION_EDIT, uri)); return false; } //TODO after starting the activity, if the item was updated or deleted, this // view will need to be refreshed! }; }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); // bind an action for long-press (not a context menu) getListView().setOnItemLongClickListener(this.longClickListener); this.currentSort = PreferenceManager.getDefaultSharedPreferences(this) .getInt(KEY_BOOKMARKS_SORT_PREF, SORT_MODIFIED); Intent intent = getIntent(); Uri uri = intent.getData(); if ( Intent.ACTION_PICK.equals(intent.getAction()) ) { setTitle(R.string.choose_bookmark); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); uri = uri.buildUpon().appendPath("search") .appendQueryParameter("q", query).build(); intent.setData( uri ); this.setTitle("GMarks search results for '" + query + "'"); } else { String labelName = uri.getQueryParameter("label"); if ( labelName != null ) this.setTitle("Bookmarks for label '" + labelName + "'"); } Cursor cursor = getCursorFromIntent(intent); // Used to map notes entries from the database to views SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.bookmarkslist_item, cursor, new String[] { Bookmark.Columns.TITLE, Bookmark.Columns.HOST }, new int[] { R.id.title, R.id.host } ); setListAdapter(adapter); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); // bind an action for long-press (not a context menu) getListView().setOnItemLongClickListener(this.longClickListener); this.currentSort = PreferenceManager.getDefaultSharedPreferences(this) .getInt(KEY_BOOKMARKS_SORT_PREF, SORT_MODIFIED); Intent intent = getIntent(); if (intent.getData() == null) intent.setData(Bookmark.CONTENT_URI); Uri uri = intent.getData(); if ( Intent.ACTION_PICK.equals(intent.getAction()) ) { setTitle(R.string.choose_bookmark); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); uri = uri.buildUpon().appendPath("search") .appendQueryParameter("q", query).build(); intent.setData( uri ); this.setTitle("GMarks search results for '" + query + "'"); } else { String labelName = uri.getQueryParameter("label"); if ( labelName != null ) this.setTitle("Bookmarks for label '" + labelName + "'"); } Cursor cursor = getCursorFromIntent(intent); // Used to map notes entries from the database to views SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.bookmarkslist_item, cursor, new String[] { Bookmark.Columns.TITLE, Bookmark.Columns.HOST }, new int[] { R.id.title, R.id.host } ); setListAdapter(adapter); }
diff --git a/GameEngine_Core/com/clinkworks/gameengine/components/GameBase.java b/GameEngine_Core/com/clinkworks/gameengine/components/GameBase.java index 3ecff8e..4c16972 100644 --- a/GameEngine_Core/com/clinkworks/gameengine/components/GameBase.java +++ b/GameEngine_Core/com/clinkworks/gameengine/components/GameBase.java @@ -1,55 +1,55 @@ package com.clinkworks.gameengine.components; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.clinkworks.gameengine.api.GameEngine; import com.clinkworks.gameengine.datatypes.GameID; import com.clinkworks.gameengine.datatypes.PlayerID; abstract public class GameBase { private Map<PlayerID, Player> _players; private GameID _gameID; private GameEngine _gameEngine; public GameBase(GameID gameID){ _gameID = gameID; _players = new HashMap<PlayerID, Player>(); } public GameBase(GameEngine gameEngine){ _gameEngine = gameEngine; _players = new HashMap<PlayerID, Player>(); - _gameID = gameEngine.generateNextGameSequence(); + _gameID = gameEngine.generateNextGameID(); } public GameEngine getGameEngine(){ return _gameEngine; } public List<Player> getPlayers(){ return new ArrayList<Player>(_players.values()); } public Game addPlayerToGame(Player player){ _players.put(player.getPlayerID(), player); return (Game)this; } public Game saveGame(){ return getGameEngine().saveGame((Game)this); } public GameID getGameID(){ return _gameID; } @Override public String toString(){ return _gameID.toString(); } }
true
true
public GameBase(GameEngine gameEngine){ _gameEngine = gameEngine; _players = new HashMap<PlayerID, Player>(); _gameID = gameEngine.generateNextGameSequence(); }
public GameBase(GameEngine gameEngine){ _gameEngine = gameEngine; _players = new HashMap<PlayerID, Player>(); _gameID = gameEngine.generateNextGameID(); }
diff --git a/HelloWorld/src/HelloWorld.java b/HelloWorld/src/HelloWorld.java index a0242c0..de78655 100644 --- a/HelloWorld/src/HelloWorld.java +++ b/HelloWorld/src/HelloWorld.java @@ -1,11 +1,11 @@ public class HelloWorld { /** * @param args */ public static void main(String[] args) { - System.out.println("HelloWorld"); + System.out.println("Hello World"); } }
true
true
public static void main(String[] args) { System.out.println("HelloWorld"); }
public static void main(String[] args) { System.out.println("Hello World"); }
diff --git a/src/main/java/net/floodlightcontroller/core/OFMessageFilterManager.java b/src/main/java/net/floodlightcontroller/core/OFMessageFilterManager.java index b096f79..316c200 100644 --- a/src/main/java/net/floodlightcontroller/core/OFMessageFilterManager.java +++ b/src/main/java/net/floodlightcontroller/core/OFMessageFilterManager.java @@ -1,564 +1,568 @@ /** * Copyright 2011, Big Switch Networks, Inc. * Originally created by David Erickson, Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ package net.floodlightcontroller.core; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledExecutorService; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.openflow.protocol.OFFlowMod; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPacketOut; import org.openflow.protocol.OFType; import org.openflow.util.HexString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.ArrayList; import org.apache.thrift.TException; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransportException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packetstreamer.thrift.*; public class OFMessageFilterManager implements IOFMessageListener { /** * @author Srini */ protected static Logger log = LoggerFactory.getLogger(OFMessageFilterManager.class); // The port and client reference for packet streaming protected int serverPort = 9090; protected final int MaxRetry = 1; protected static TTransport transport = null; protected static PacketStreamer.Client packetClient = null; protected IFloodlightProvider floodlightProvider = null; // filter List is a key value pair. Key is the session id, value is the filter rules. protected ConcurrentHashMap<String, ConcurrentHashMap<String,String>> filterMap = null; protected ConcurrentHashMap<String, Long> filterTimeoutMap = null; protected Timer timer = null; protected final int MAX_FILTERS=5; protected final long MAX_FILTER_TIME= 300000; // maximum filter time is 5 minutes. protected final int TIMER_INTERVAL = 1000; // 1 second time interval. public static final String SUCCESS = "0"; public static final String FILTER_SETUP_FAILED = "-1001"; public static final String FILTER_NOT_FOUND = "-1002"; public static final String FILTER_LIMIT_REACHED = "-1003"; public static final String FILTER_SESSION_ID_NOT_FOUND = "-1004"; public static final String SERVICE_UNAVAILABLE = "-1005"; public enum FilterResult { /* * FILTER_NOT_DEFINED: Filter is not defined * FILTER_NO_MATCH: Filter is defined and the packet doesn't match the filter * FILTER_MATCH: Filter is defined and the packet matches the filter */ FILTER_NOT_DEFINED, FILTER_NO_MATCH, FILTER_MATCH } public void init (IFloodlightProvider bp) { floodlightProvider = bp; filterMap = new ConcurrentHashMap<String, ConcurrentHashMap<String,String>>(); filterTimeoutMap = new ConcurrentHashMap<String, Long>(); serverPort = Integer.parseInt(System.getProperty("net.floodlightcontroller.packetstreamer.port", "9090")); } protected String addFilter(ConcurrentHashMap<String,String> f, long delta) { // Create unique session ID. int prime = 33791; String s = null; int i; if ((filterMap == null) || (filterTimeoutMap == null)) return String.format("%d", FILTER_SETUP_FAILED); for (i=0; i<MAX_FILTERS; ++i) { Integer x = prime + i; s = String.format("%d", x.hashCode()); if (!filterMap.containsKey(s)) break; // implies you can use this key for session id. } if (i==MAX_FILTERS) { return FILTER_LIMIT_REACHED; } filterMap.put(s, f); if (filterTimeoutMap.containsKey(s)) filterTimeoutMap.remove(s); filterTimeoutMap.put(s, delta); if (filterMap.size() == 1) { // set the timer as there will be no existing timers. TimeoutFilterTask task = new TimeoutFilterTask(this); Timer timer = new Timer(); timer.schedule (task, TIMER_INTERVAL); // Keep the listeners to avoid race condition //startListening(); } return s; // the return string is the session ID. } public String setupFilter(String sid, ConcurrentHashMap<String,String> f, int deltaInSecond) { if (sid == null) { // Delta in filter needs to be milliseconds log.debug("Adding new filter: {} for {} seconds", f, deltaInSecond); return addFilter(f, deltaInSecond * 1000); } else {// this is the session id. // we will ignore the hash map features. if (deltaInSecond > 0) return refreshFilter(sid, deltaInSecond * 1000); else return deleteFilter(sid); } } public int timeoutFilters() { Iterator<String> i = filterTimeoutMap.keySet().iterator(); while(i.hasNext()) { String s = i.next(); Long t = filterTimeoutMap.get(s); if (t != null) { i.remove(); t -= TIMER_INTERVAL; if (t > 0) { filterTimeoutMap.put(s, t); } else deleteFilter(s); } else deleteFilter(s); } return filterMap.size(); } protected String refreshFilter(String s, int delta) { Long t = filterTimeoutMap.get(s); if (t != null) { filterTimeoutMap.remove(s); t += delta; // time is in milliseconds if (t > MAX_FILTER_TIME) t = MAX_FILTER_TIME; filterTimeoutMap.put(s, t); return SUCCESS; } else return FILTER_SESSION_ID_NOT_FOUND; } protected String deleteFilter(String sessionId) { if (filterMap.containsKey(sessionId)) { filterMap.remove(sessionId); try { if (packetClient != null) packetClient.terminateSession(sessionId); } catch (TException e) { log.error("terminateSession Texception: {}", e); } log.debug("Deleted Filter {}. # of filters remaining: {}", sessionId, filterMap.size()); return SUCCESS; } else return FILTER_SESSION_ID_NOT_FOUND; } public HashSet<String> getMatchedFilters(OFMessage m, FloodlightContext cntx) { HashSet<String> matchedFilters = new HashSet<String>(); // This default function is written to match on packet ins and // packet outs. Ethernet eth = null; if (m.getType() == OFType.PACKET_IN) { eth = IFloodlightProvider.bcStore.get(cntx, IFloodlightProvider.CONTEXT_PI_PAYLOAD); } else if (m.getType() == OFType.PACKET_OUT) { eth = new Ethernet(); OFPacketOut p = (OFPacketOut) m; // No MAC match if packetOut doesn't have the packet. if (p.getPacketData() == null) return null; eth.deserialize(p.getPacketData(), 0, p.getPacketData().length); } else if (m.getType() == OFType.FLOW_MOD) { // flow-mod can't be matched by mac. return null; } if (eth == null) return null; Iterator<String> filterIt = filterMap.keySet().iterator(); while (filterIt.hasNext()) { // for every filter boolean filterMatch = false; String filterSessionId = filterIt.next(); Map<String,String> filter = filterMap.get(filterSessionId); // If the filter has empty fields, then it is not considered as a match. if (filter == null || filter.isEmpty()) continue; Iterator<String> fieldIt = filter.keySet().iterator(); while (fieldIt.hasNext()) { String filterFieldType = fieldIt.next(); String filterFieldValue = filter.get(filterFieldType); if (filterFieldType.equals("mac")) { String srcMac = HexString.toHexString(eth.getSourceMACAddress()); String dstMac = HexString.toHexString(eth.getDestinationMACAddress()); log.debug("srcMac: {}, dstMac: {}", srcMac, dstMac); if (filterFieldValue.equals(srcMac) || filterFieldValue.equals(dstMac)){ filterMatch = true; } else { filterMatch = false; break; } } } if (filterMatch) { matchedFilters.add(filterSessionId); } } if (matchedFilters.isEmpty()) return null; else return matchedFilters; } protected void startListening() { floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); floodlightProvider.addOFMessageListener(OFType.PACKET_OUT, this); floodlightProvider.addOFMessageListener(OFType.FLOW_MOD, this); } protected void stopListening() { floodlightProvider.removeOFMessageListener(OFType.PACKET_IN, this); floodlightProvider.removeOFMessageListener(OFType.PACKET_OUT, this); floodlightProvider.removeOFMessageListener(OFType.FLOW_MOD, this); } public void startUp() { startListening(); //connectToPSServer(); } public void shutDown() { stopListening(); disconnectFromPSServer(); } public boolean connectToPSServer() { int numRetries = 0; if (transport != null && transport.isOpen()) { return true; } while (numRetries++ < MaxRetry) { try { transport = new TFramedTransport(new TSocket("localhost", serverPort)); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); packetClient = new PacketStreamer.Client(protocol); log.debug("Have a connection to packetstreamer server localhost:{}", serverPort); break; } catch (TException x) { try { // Wait for 1 second before retry if (numRetries < MaxRetry) { Thread.sleep(1000); } } catch (Exception e) {} } } if (numRetries > MaxRetry) { log.error("Failed to establish connection with the packetstreamer server."); return false; } return true; } public void disconnectFromPSServer() { if (transport != null && transport.isOpen()) { log.debug("Close the connection to packetstreamer server localhost:{}", serverPort); transport.close(); } } @Override public String getName() { return "messageFilterManager"; } @Override public int getId() { return FlListenerID.OFMESSAGEFILTERMANAGER; } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { return (type == OFType.PACKET_IN && name.equals("devicemanager")); } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { return (type == OFType.PACKET_IN && name.equals("learningswitch")); } @Override public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { if (filterMap == null || filterMap.isEmpty()) return Command.CONTINUE; HashSet<String> matchedFilters = null; if (log.isDebugEnabled()) { log.debug("Received packet {} from switch {}", msg, sw.getStringId()); } matchedFilters = getMatchedFilters(msg, cntx); if (matchedFilters == null) { return Command.CONTINUE; } else { try { sendPacket(matchedFilters, sw, msg, cntx, true); } catch (TException e) { log.error("sendPacket Texception: {}", e); } catch (Exception e) { log.error("sendPacket exception: {}", e); } } return Command.CONTINUE; } public class TimeoutFilterTask extends TimerTask { OFMessageFilterManager filterManager; ScheduledExecutorService ses = floodlightProvider.getScheduledExecutor(); public TimeoutFilterTask(OFMessageFilterManager manager) { filterManager = manager; } public void run() { int x = filterManager.timeoutFilters(); if (x > 0) { // there's at least one filter still active. Timer timer = new Timer(); timer.schedule(new TimeoutFilterTask(filterManager), TIMER_INTERVAL); } else { // Don't stop the listener to avoid race condition //stopListening(); } } } public int getNumberOfFilters() { return filterMap.size(); } public int getMaxFilterSize() { return MAX_FILTERS; } protected void sendPacket(HashSet<String> matchedFilters, IOFSwitch sw, OFMessage msg, FloodlightContext cntx, boolean sync) throws TException { Message sendMsg = new Message(); Packet packet = new Packet(); ChannelBuffer bb; sendMsg.setPacket(packet); List<String> sids = new ArrayList<String>(matchedFilters); sendMsg.setSessionIDs(sids); packet.setMessageType(OFMessageType.findByValue((msg.getType().ordinal()))); switch (msg.getType()) { case PACKET_IN: OFPacketIn pktIn = (OFPacketIn)msg; packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), pktIn.getInPort())); bb = ChannelBuffers.buffer(pktIn.getLength()); pktIn.writeTo(bb); packet.setData(getData(sw, msg, cntx)); break; case PACKET_OUT: OFPacketOut pktOut = (OFPacketOut)msg; packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), pktOut.getInPort())); bb = ChannelBuffers.buffer(pktOut.getLength()); pktOut.writeTo(bb); packet.setData(getData(sw, msg, cntx)); break; case FLOW_MOD: OFFlowMod offlowMod = (OFFlowMod)msg; packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), offlowMod.getOutPort())); bb = ChannelBuffers.buffer(offlowMod.getLength()); offlowMod.writeTo(bb); packet.setData(getData(sw, msg, cntx)); break; default: packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), (short)0)); String strData = "Unknown packet"; packet.setData(strData.getBytes()); break; } try { if (transport == null || !transport.isOpen() || packetClient == null) { if (!connectToPSServer()) { // No need to sendPacket if can't make connection to the server return; } } if (sync) { log.debug("Send packet sync: {}", packet.toString()); packetClient.pushMessageSync(sendMsg); } else { log.debug("Send packet sync: ", packet.toString()); packetClient.pushMessageAsync(sendMsg); } } catch (TTransportException e) { log.info("Caught TTransportException: {}", e); System.out.println(e); disconnectFromPSServer(); connectToPSServer(); } catch (Exception e) { log.info("Caught exception: {}", e); System.out.println(e); disconnectFromPSServer(); connectToPSServer(); } } public String getDataAsString(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { Ethernet eth; StringBuffer sb = new StringBuffer(""); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS"); Date date = new Date(); sb.append(dateFormat.format(date)); sb.append(" "); switch (msg.getType()) { case PACKET_IN: OFPacketIn pktIn = (OFPacketIn) msg; sb.append("packet_in [ "); sb.append(sw.getStringId()); sb.append(" -> Controller"); sb.append(" ]"); sb.append("\ntotal length: "); sb.append(pktIn.getTotalLength()); sb.append("\nin_port: "); sb.append(pktIn.getInPort()); sb.append("\ndata_length: "); sb.append(pktIn.getTotalLength() - OFPacketIn.MINIMUM_LENGTH); sb.append("\nbuffer: "); sb.append(pktIn.getBufferId()); // If the conext is not set by floodlight, then ignore. if (cntx != null) { // packet type icmp, arp, etc. eth = IFloodlightProvider.bcStore.get(cntx, IFloodlightProvider.CONTEXT_PI_PAYLOAD); if (eth != null) sb.append(eth.toString()); } break; case PACKET_OUT: OFPacketOut pktOut = (OFPacketOut) msg; sb.append("packet_out [ "); sb.append("Controller -> "); sb.append(HexString.toHexString(sw.getId())); sb.append(" ]"); sb.append("\nin_port: "); sb.append(pktOut.getInPort()); sb.append("\nactions_len: "); sb.append(pktOut.getActionsLength()); - sb.append("\nactions: "); - sb.append(pktOut.getActions().toString()); + if (pktOut.getActions() != null) { + sb.append("\nactions: "); + sb.append(pktOut.getActions().toString()); + } break; case FLOW_MOD: OFFlowMod fm = (OFFlowMod) msg; sb.append("flow_mod [ "); sb.append("Controller -> "); sb.append(HexString.toHexString(sw.getId())); sb.append(" ]"); // If the conext is not set by floodlight, then ignore. if (cntx != null) { eth = IFloodlightProvider.bcStore.get(cntx, IFloodlightProvider.CONTEXT_PI_PAYLOAD); if (eth != null) sb.append(eth.toString()); } sb.append("\nADD: cookie: "); sb.append(fm.getCookie()); sb.append(" idle: "); sb.append(fm.getIdleTimeout()); sb.append(" hard: "); sb.append(fm.getHardTimeout()); sb.append(" pri: "); sb.append(fm.getPriority()); sb.append(" buf: "); sb.append(fm.getBufferId()); sb.append(" flg: "); sb.append(fm.getFlags()); - sb.append("\nactions: "); - sb.append(fm.getActions().toString()); + if (fm.getActions() != null) { + sb.append("\nactions: "); + sb.append(fm.getActions().toString()); + } break; default: sb.append("[Unknown Packet]"); } sb.append("\n\n"); return sb.toString(); } public byte[] getData(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { return this.getDataAsString(sw, msg, cntx).getBytes(); } }
false
true
public String getDataAsString(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { Ethernet eth; StringBuffer sb = new StringBuffer(""); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS"); Date date = new Date(); sb.append(dateFormat.format(date)); sb.append(" "); switch (msg.getType()) { case PACKET_IN: OFPacketIn pktIn = (OFPacketIn) msg; sb.append("packet_in [ "); sb.append(sw.getStringId()); sb.append(" -> Controller"); sb.append(" ]"); sb.append("\ntotal length: "); sb.append(pktIn.getTotalLength()); sb.append("\nin_port: "); sb.append(pktIn.getInPort()); sb.append("\ndata_length: "); sb.append(pktIn.getTotalLength() - OFPacketIn.MINIMUM_LENGTH); sb.append("\nbuffer: "); sb.append(pktIn.getBufferId()); // If the conext is not set by floodlight, then ignore. if (cntx != null) { // packet type icmp, arp, etc. eth = IFloodlightProvider.bcStore.get(cntx, IFloodlightProvider.CONTEXT_PI_PAYLOAD); if (eth != null) sb.append(eth.toString()); } break; case PACKET_OUT: OFPacketOut pktOut = (OFPacketOut) msg; sb.append("packet_out [ "); sb.append("Controller -> "); sb.append(HexString.toHexString(sw.getId())); sb.append(" ]"); sb.append("\nin_port: "); sb.append(pktOut.getInPort()); sb.append("\nactions_len: "); sb.append(pktOut.getActionsLength()); sb.append("\nactions: "); sb.append(pktOut.getActions().toString()); break; case FLOW_MOD: OFFlowMod fm = (OFFlowMod) msg; sb.append("flow_mod [ "); sb.append("Controller -> "); sb.append(HexString.toHexString(sw.getId())); sb.append(" ]"); // If the conext is not set by floodlight, then ignore. if (cntx != null) { eth = IFloodlightProvider.bcStore.get(cntx, IFloodlightProvider.CONTEXT_PI_PAYLOAD); if (eth != null) sb.append(eth.toString()); } sb.append("\nADD: cookie: "); sb.append(fm.getCookie()); sb.append(" idle: "); sb.append(fm.getIdleTimeout()); sb.append(" hard: "); sb.append(fm.getHardTimeout()); sb.append(" pri: "); sb.append(fm.getPriority()); sb.append(" buf: "); sb.append(fm.getBufferId()); sb.append(" flg: "); sb.append(fm.getFlags()); sb.append("\nactions: "); sb.append(fm.getActions().toString()); break; default: sb.append("[Unknown Packet]"); } sb.append("\n\n"); return sb.toString(); }
public String getDataAsString(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { Ethernet eth; StringBuffer sb = new StringBuffer(""); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS"); Date date = new Date(); sb.append(dateFormat.format(date)); sb.append(" "); switch (msg.getType()) { case PACKET_IN: OFPacketIn pktIn = (OFPacketIn) msg; sb.append("packet_in [ "); sb.append(sw.getStringId()); sb.append(" -> Controller"); sb.append(" ]"); sb.append("\ntotal length: "); sb.append(pktIn.getTotalLength()); sb.append("\nin_port: "); sb.append(pktIn.getInPort()); sb.append("\ndata_length: "); sb.append(pktIn.getTotalLength() - OFPacketIn.MINIMUM_LENGTH); sb.append("\nbuffer: "); sb.append(pktIn.getBufferId()); // If the conext is not set by floodlight, then ignore. if (cntx != null) { // packet type icmp, arp, etc. eth = IFloodlightProvider.bcStore.get(cntx, IFloodlightProvider.CONTEXT_PI_PAYLOAD); if (eth != null) sb.append(eth.toString()); } break; case PACKET_OUT: OFPacketOut pktOut = (OFPacketOut) msg; sb.append("packet_out [ "); sb.append("Controller -> "); sb.append(HexString.toHexString(sw.getId())); sb.append(" ]"); sb.append("\nin_port: "); sb.append(pktOut.getInPort()); sb.append("\nactions_len: "); sb.append(pktOut.getActionsLength()); if (pktOut.getActions() != null) { sb.append("\nactions: "); sb.append(pktOut.getActions().toString()); } break; case FLOW_MOD: OFFlowMod fm = (OFFlowMod) msg; sb.append("flow_mod [ "); sb.append("Controller -> "); sb.append(HexString.toHexString(sw.getId())); sb.append(" ]"); // If the conext is not set by floodlight, then ignore. if (cntx != null) { eth = IFloodlightProvider.bcStore.get(cntx, IFloodlightProvider.CONTEXT_PI_PAYLOAD); if (eth != null) sb.append(eth.toString()); } sb.append("\nADD: cookie: "); sb.append(fm.getCookie()); sb.append(" idle: "); sb.append(fm.getIdleTimeout()); sb.append(" hard: "); sb.append(fm.getHardTimeout()); sb.append(" pri: "); sb.append(fm.getPriority()); sb.append(" buf: "); sb.append(fm.getBufferId()); sb.append(" flg: "); sb.append(fm.getFlags()); if (fm.getActions() != null) { sb.append("\nactions: "); sb.append(fm.getActions().toString()); } break; default: sb.append("[Unknown Packet]"); } sb.append("\n\n"); return sb.toString(); }
diff --git a/FiltersPlugin/src/org/gephi/filters/plugin/edge/EdgeWeightBuilder.java b/FiltersPlugin/src/org/gephi/filters/plugin/edge/EdgeWeightBuilder.java index 1259668ff..00711e708 100644 --- a/FiltersPlugin/src/org/gephi/filters/plugin/edge/EdgeWeightBuilder.java +++ b/FiltersPlugin/src/org/gephi/filters/plugin/edge/EdgeWeightBuilder.java @@ -1,160 +1,160 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.gephi.filters.plugin.edge; import java.util.ArrayList; import java.util.List; import javax.swing.Icon; import javax.swing.JPanel; import org.gephi.filters.api.FilterLibrary; import org.gephi.filters.api.Range; import org.gephi.filters.plugin.RangeFilter; import org.gephi.filters.plugin.graph.DegreeRangeBuilder; import org.gephi.filters.plugin.graph.RangeUI; import org.gephi.filters.spi.Category; import org.gephi.filters.spi.EdgeFilter; import org.gephi.filters.spi.Filter; import org.gephi.filters.spi.FilterBuilder; import org.gephi.filters.spi.FilterProperty; import org.gephi.graph.api.Edge; import org.gephi.graph.api.Graph; import org.gephi.graph.api.GraphController; import org.gephi.graph.api.GraphModel; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.lookup.ServiceProvider; /** * * @author Mathieu Bastian */ @ServiceProvider(service = FilterBuilder.class) public class EdgeWeightBuilder implements FilterBuilder { public Category getCategory() { return FilterLibrary.EDGE; } public String getName() { return NbBundle.getMessage(EdgeWeightBuilder.class, "EdgeWeightBuilder.name"); } public Icon getIcon() { return null; } public String getDescription() { return null; } public Filter getFilter() { return new EdgeWeightFilter(); } public JPanel getPanel(Filter filter) { RangeUI ui = Lookup.getDefault().lookup(RangeUI.class); if (ui != null) { return ui.getPanel((EdgeWeightFilter) filter); } return null; } public static class EdgeWeightFilter implements RangeFilter, EdgeFilter { private Float min = 0f; private Float max = 0f; private Range range = new Range(0f, 0f); //States private List<Float> values; public String getName() { return NbBundle.getMessage(EdgeWeightBuilder.class, "EdgeWeightBuilder.name"); } private void refreshRange() { Float lowerBound = range.getLowerFloat(); Float upperBound = range.getUpperFloat(); if ((Float) min > lowerBound || (Float) max < lowerBound || lowerBound.equals(upperBound)) { lowerBound = (Float) min; } if ((Float) min > upperBound || (Float) max < upperBound || lowerBound.equals(upperBound)) { upperBound = (Float) max; } range = new Range(lowerBound, upperBound); } public boolean init(Graph graph) { values = new ArrayList<Float>(graph.getEdgeCount()); min = Float.POSITIVE_INFINITY; max = Float.NEGATIVE_INFINITY; return true; } public boolean evaluate(Graph graph, Edge edge) { float weight = edge.getWeight(); min = Math.min(min, weight); max = Math.max(max, weight); values.add(new Float(weight)); return range.isInRange(weight); } public void finish() { refreshRange(); } public Object[] getValues() { if (values == null) { GraphModel gm = Lookup.getDefault().lookup(GraphController.class).getModel(); Graph graph = gm.getGraph(); Float[] weights = new Float[graph.getEdgeCount()]; int i = 0; min = Float.MAX_VALUE; max = Float.MIN_VALUE; for (Edge e : graph.getEdges()) { float weight = e.getWeight(); min = Math.min(min, weight); max = Math.max(max, weight); weights[i++] = weight; } refreshRange(); return weights; } else { - return values.toArray(new Integer[0]); + return values.toArray(new Float[0]); } } public FilterProperty[] getProperties() { try { return new FilterProperty[]{ FilterProperty.createProperty(this, Range.class, "range") }; } catch (Exception ex) { Exceptions.printStackTrace(ex); } return new FilterProperty[0]; } public FilterProperty getRangeProperty() { return getProperties()[0]; } public Object getMinimum() { return min; } public Object getMaximum() { return max; } public Range getRange() { return range; } public void setRange(Range range) { this.range = range; } } }
true
true
public Object[] getValues() { if (values == null) { GraphModel gm = Lookup.getDefault().lookup(GraphController.class).getModel(); Graph graph = gm.getGraph(); Float[] weights = new Float[graph.getEdgeCount()]; int i = 0; min = Float.MAX_VALUE; max = Float.MIN_VALUE; for (Edge e : graph.getEdges()) { float weight = e.getWeight(); min = Math.min(min, weight); max = Math.max(max, weight); weights[i++] = weight; } refreshRange(); return weights; } else { return values.toArray(new Integer[0]); } }
public Object[] getValues() { if (values == null) { GraphModel gm = Lookup.getDefault().lookup(GraphController.class).getModel(); Graph graph = gm.getGraph(); Float[] weights = new Float[graph.getEdgeCount()]; int i = 0; min = Float.MAX_VALUE; max = Float.MIN_VALUE; for (Edge e : graph.getEdges()) { float weight = e.getWeight(); min = Math.min(min, weight); max = Math.max(max, weight); weights[i++] = weight; } refreshRange(); return weights; } else { return values.toArray(new Float[0]); } }
diff --git a/src/anchovy/GameEngine.java b/src/anchovy/GameEngine.java index a02dd23..4a2e3c2 100644 --- a/src/anchovy/GameEngine.java +++ b/src/anchovy/GameEngine.java @@ -1,804 +1,804 @@ package anchovy; import java.util.ArrayList; import java.util.Iterator; import java.io.*; import anchovy.Components.*; import anchovy.Pair.Label; import anchovy.io.*; /** * Game Engine for the 'Nuclear Power Plant Simulation Game' Links all the * technical components of the game together - the 'Controller' in the MVC * design * * @author Harrison */ public class GameEngine { public ArrayList<Component> powrPlntComponents = null; // Parser parser; // UI ui = null; Commented out for now MainWindow window; String fileName; /** * Constructor for the game engine. On creation it creates a list to store * the components of the power plant and links to a user interface (what * ever type of user interface that may be) */ public GameEngine() { powrPlntComponents = new ArrayList<Component>(); // ui = new UI(this); Commented out for now // parser = new Parser(this); window = new MainWindow(this); /* * final Timer gameLoop = new Timer(); gameLoop.scheduleAtFixedRate(new * TimerTask(){ boolean stop = false; long timesRoundLoop = 0; * * public void run(){ timesRoundLoop++; if(timesRoundLoop > 10){ stop = * true; } if(!stop){ System.out.println("Hello"); runSimulation(); * }else{ gameLoop.cancel(); } * * } }, 0, 1000); */ } /** * Repairs the given component by calling the repair method of said component. * Then subtracts the repair cost of the repair from the total amount of electricity generated. * If there was not enough Electriciy, the component will not get repaired. * @param component The component to be repaired */ public void repair(Component component) {//Component Repair Costs double pumpCost = 50; double valveCost = 0; double reactorCost = 500; double turbineCost = 100; double generatorCost = 0; double condensorCost = 120; Iterator<Component> cIt = powrPlntComponents.iterator(); Component comp = null; Generator generator = null; double totalPower = 0; while(cIt.hasNext()){ comp = cIt.next(); if(comp instanceof Generator){ generator = (Generator) comp; totalPower += generator.getElectrisityGenerated(); generator.setElectrisityGenerated(0); } } if(generator == null) totalPower = 10000; String componentName = component.getName(); if(componentName.contains("Valve") & totalPower >= valveCost){ totalPower -= valveCost; component.repair(); }else if(componentName.contains("Pump") & totalPower >= pumpCost){ totalPower -= pumpCost; component.repair(); }else if(componentName.contains("Reactor") & totalPower >= reactorCost){ totalPower -= reactorCost; component.repair(); }else if(componentName.contains("Turbine") & totalPower >= turbineCost){ totalPower -= turbineCost; component.repair(); }else if(componentName.contains("Generator") & totalPower >= generatorCost){ totalPower -= generatorCost; component.repair(); }else if(componentName.contains("Condenser") & totalPower >= condensorCost){ totalPower -= condensorCost; component.repair(); } if(generator != null) generator.setElectrisityGenerated(totalPower); } /** * Using a list of Info Packets (generated from loading from file * or elsewhere). Adds each of the components described in the Info Packet * list to the list of components in the power plant then sends the info * packet to that component to initialise all its values. Once all components * of the power plant are in the list and initialized, they are then all * connected together in the way described by the info packets. * * @param allPowerPlantInfo * A list of info packets containing all the information about * all components to be put into the power plant. */ public void setupPowerPlantConfiguration( ArrayList<InfoPacket> allPowerPlantInfo) { Iterator<InfoPacket> infoIt = allPowerPlantInfo.iterator(); InfoPacket currentInfo = null; String currentCompName = null; Component currentNewComponent = null; // Create component list. while (infoIt.hasNext()) { currentInfo = infoIt.next(); currentCompName = getComponentNameFromInfo(currentInfo); // Determine component types we are dealing with. and initialise it. if (currentCompName.contains("Condenser")) { currentNewComponent = new Condenser(currentCompName, currentInfo); } else if (currentCompName.contains("Generator")) { currentNewComponent = new Generator(currentCompName, currentInfo); } else if (currentCompName.contains("Pump")) { currentNewComponent = new Pump(currentCompName, currentInfo); } else if (currentCompName.contains("Reactor")) { currentNewComponent = new Reactor(currentCompName, currentInfo); } else if (currentCompName.contains("Turbine")) { currentNewComponent = new Turbine(currentCompName, currentInfo); } else if (currentCompName.contains("Valve")) { currentNewComponent = new Valve(currentCompName, currentInfo); } else if (currentCompName.contains("Infrastructure")){ currentNewComponent = new Infrastructure(currentCompName, currentInfo); } addComponent(currentNewComponent); // add the component to the power plant /* try { assignInfoToComponent(currentInfo); // send the just added // component its info. } catch (Exception e) { e.printStackTrace(); }*/ } // Connect components together infoIt = allPowerPlantInfo.iterator(); ArrayList<String> inputComponents = new ArrayList<String>(); ArrayList<String> outputComponents = new ArrayList<String>(); Iterator<Pair<?>> pairIt = null; Pair<?> currentPair = null; Label currentLabel = null; Component currentComponent = null; Iterator<String> connectionNameIt = null; Component attachComp = null; //Get info for each of the components while (infoIt.hasNext()) { currentInfo = infoIt.next(); pairIt = currentInfo.namedValues.iterator(); //Get the useful information out of the info. while (pairIt.hasNext()) { currentPair = pairIt.next(); currentLabel = currentPair.getLabel(); switch (currentLabel) { case cNme: currentCompName = (String) currentPair.second(); break; case rcIF: inputComponents.add((String) currentPair.second()); break; case oPto: outputComponents.add((String) currentPair.second()); break; default: break; } } //Get the component that we are going to connect other components to. currentComponent = getPowerPlantComponent(currentCompName); // Attach each input component to the current component. connectionNameIt = inputComponents.iterator(); while (connectionNameIt.hasNext()) { attachComp = getPowerPlantComponent(connectionNameIt.next()); if(!currentComponent.getRecievesInputFrom().contains(attachComp) & !attachComp.getOutputsTo().contains(currentComponent)) connectComponentTo(currentComponent, attachComp, true); } // Attach each output component to the current compoennt connectionNameIt = outputComponents.iterator(); while (connectionNameIt.hasNext()) { attachComp = getPowerPlantComponent(connectionNameIt.next()); if(!currentComponent.getOutputsTo().contains(attachComp) & !attachComp.getRecievesInputFrom().contains(currentComponent)) connectComponentTo(currentComponent, attachComp, false); } inputComponents.clear(); outputComponents.clear(); } } /** * Using the name of a component in the format of a string, returns the * actual Component found in the list of components of the Power Plant * * @param currentCompName The name of a component. * @return The component specified by the given name. */ public Component getPowerPlantComponent(String currentCompName) { Component currentComponent = null; Iterator<Component> compIt; compIt = powrPlntComponents.iterator(); Component c = null; String cName = null; //Find the component we are looking for. while (compIt.hasNext()) { c = compIt.next(); cName = c.getName(); if (cName.equals(currentCompName)) { currentComponent = c; } } if(currentComponent == null) try { throw new Exception("The component: " + currentCompName + " was not found to exist in the power plant"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return currentComponent; } /** * Extracts the first component name out of an info packet. * @param info An info packet for a component * @return The component name contained within the given info packet. */ private String getComponentNameFromInfo(InfoPacket info) { Iterator<Pair<?>> pairIt = info.namedValues.iterator(); Pair<?> pair = null; String name = null; while (pairIt.hasNext() && name == null) { pair = pairIt.next(); if (pair.getLabel() == Label.cNme) { name = (String) pair.second(); } } return name; } /** * Sends an info packet to a component the components is specified by the * name of the component in the info packet. * * @param info Info Packet to be sent to a component */ public void assignInfoToComponent(InfoPacket info) throws Exception { String compToSendTo = null; // Pair<?> pair = null; // Iterator<Pair<?>> pi = info.namedValues.iterator(); // Label label = null; // while(pi.hasNext() && compToSendTo == null){ // pair = pi.next(); // label = pair.getLabel(); // switch (label){ // case cNme: // compToSendTo = (String) pair.second(); // default: // break; // } // } compToSendTo = getComponentNameFromInfo(info); // Iterator<Component> ci = powrPlntComponents.iterator(); // boolean comNotFound = true; Component com = null; // while(ci.hasNext() && comNotFound){ // comNotFound = true; // com = ci.next(); // if(com.getName() == compToSendTo){ // comNotFound = false; // // } // } com = getPowerPlantComponent(compToSendTo); /* * if the component wasn't found throw an exception stating this */ if (com == null) { throw new Exception( "The component you were trying to send info to doesn't exit: " + compToSendTo); } else { com.takeInfo(info); } } /** * Goes through the list of components one by one calling its simulate * method This should be called in a loop to get a continuous simulation. */ public void runSimulation() { Iterator<Component> ci = powrPlntComponents.iterator(); Component comp = null; while (ci.hasNext()) { comp = ci.next(); comp.calculate(); } } /** * Add a component to the list of components * @param component The component to be added to the list of components */ public void addComponent(Component component) { powrPlntComponents.add(component); } /** * Connect two components together, in the given order. * * @param comp1 The component that we are working with * @param comp2 The component that will be added to comp1 * @param input_output Denoted whether it is an input or an output; in = true, out = false */ public void connectComponentTo(Component comp1, Component comp2, boolean input_ouput) { if (input_ouput) { comp1.connectToInput(comp2); comp2.connectToOutput(comp1); } else { comp1.connectToOutput(comp2); comp2.connectToInput(comp1); } } /** * Saves the contents of the given infoPacket to the given file. * uses '&' internally so it cannon be used in component names or pair labels * @param packets The information to be saved. * @param FileName The name of the file the data will be saved to * @return Returns a string that will be written into the console output */ public String saveGameState(ArrayList<InfoPacket> packets, String FileName) { String output = new String(); fileName = FileName; Iterator<InfoPacket> packetIter = packets.iterator(); InfoPacket pckt = null; while (packetIter.hasNext()) { pckt = packetIter.next(); Iterator<Pair<?>> namedValueIter = pckt.namedValues.iterator(); while (namedValueIter.hasNext()) { Pair<?> pair = namedValueIter.next(); System.out.println(pair.first() + '&' + pair.second().toString() + '\n'); output += pair.first() + '&' + pair.second().toString() + '\n'; } } try { BufferedWriter out = new BufferedWriter(new FileWriter("saves/" + FileName + ".fg")); out.write(output); System.out.println(output); out.close(); } catch (IOException e) { return "Saving failed."; } return "File saved"; } /** * Reads in the contents of a given file to the game. This is done by reading each line and adding it to the appropriate * infoPacket then using the info packets to setup the state of the game and power plant. * uses '&' internally so it cannon be used in component names or pair labels * @param file The filename of the file to be read in. * @throws FileNotFoundException */ public void readfile(String file) throws FileNotFoundException { // FileReader fr=new FileReader(path); // BufferedReader br=new BufferedReader(fr); String path = new java.io.File("").getAbsolutePath() + "/saves/"; FileInputStream fstream = new FileInputStream(path + file + ".fg"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); clearPowerPlant(); ArrayList<String> data = new ArrayList<String>(); ArrayList<InfoPacket> infoList = new ArrayList<InfoPacket>(); String temp; try { while ((temp = br.readLine()) != null) { data.add(temp); } br.close(); String textData[] = new String[data.size()]; textData= data.toArray(new String[0]); InfoPacket info = new InfoPacket(); int i = 0; while (i < data.size()) { String ch = textData[i].substring(0, textData[i].indexOf("&")); String d = textData[i].substring(textData[i].indexOf("&") + 1, textData[i].length()); if (ch.equals(Label.cNme.toString())) { if(i != 0) { infoList.add(info); info = new InfoPacket(); } info.namedValues.add(new Pair<String>(Label.cNme, d)); //System.out.println(ch + "=" + c1); } else if (ch.equals(Label.falT.toString())) { Double i1 = Double.parseDouble(d); info.namedValues.add(new Pair<Double>(Label.falT, i1)); //System.out.println(ch + "=" + i1); } else if (ch.equals(Label.OPFL.toString())) { - Float i1 = Float.parseFloat(d); - info.namedValues.add(new Pair<Float>(Label.OPFL, i1)); + Double i1 = Double.parseDouble(d); + info.namedValues.add(new Pair<Double>(Label.OPFL, i1)); System.out.println(ch + "=" + i1); } else if (ch.equals(Label.psit.toString())) { boolean ok = Boolean.parseBoolean(d); info.namedValues.add(new Pair<Boolean>(Label.psit, ok)); //System.out.println(ch + "=" + ok); } else if (ch.equals(Label.oPto.toString())) { info.namedValues.add(new Pair<String>(Label.oPto, d)); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.rcIF.toString())) { info.namedValues.add(new Pair<String>(Label.rcIF, d)); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.pres.toString())) { info.namedValues.add(new Pair<Double>(Label.pres, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.Vlme.toString())) { info.namedValues.add(new Pair<Double>(Label.Vlme, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.pres.toString())) { info.namedValues.add(new Pair<Double>(Label.pres, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.RPMs.toString())) { info.namedValues.add(new Pair<Double>(Label.RPMs, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.temp.toString())) { info.namedValues.add(new Pair<Double>(Label.temp, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.wLvl.toString())) { info.namedValues.add(new Pair<Double>(Label.wLvl, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.Amnt.toString())) { info.namedValues.add(new Pair<Double>(Label.Amnt, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.coRL.toString())) { info.namedValues.add(new Pair<Double>(Label.coRL, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } i++; } infoList.add(info); } catch (IOException e) { System.out.println("Cannot load file"); } setupPowerPlantConfiguration(infoList); } /** * Finds save files for the game. * @return Returns all available save games */ public String findAvailableSaves() { String path = new java.io.File("").getAbsolutePath() + "/saves"; String files; String result = new String(); File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { files = listOfFiles[i].getName(); if (files.endsWith(".fg") || files.endsWith(".FG")) { result += files.substring(0, files.lastIndexOf('.')) + '\n'; } } } return result; } /** * Get all the info from all the components within the power plant. Used for * saving and displaying info to UI. * @return List of InfoPackets for ALL components in the power plant. */ public ArrayList<InfoPacket> getAllComponentInfo() { ArrayList<InfoPacket> allInfo = new ArrayList<InfoPacket>(); Iterator<Component> ci = powrPlntComponents.iterator(); Component comp = null; while (ci.hasNext()) { comp = ci.next(); allInfo.add(comp.getInfo()); } return allInfo; } /** * Resets the components of the power plant to an empty list. Will be needed * for loading a power plant from file. */ public void clearPowerPlant() { powrPlntComponents = new ArrayList<Component>(); } /** * Loops through the list of components in the power plant and calls the calculate method in each of them. * Resulting in the power plant moving to its next state. */ public void calculateAllComponents(){ Iterator<Component> compIt = powrPlntComponents.iterator(); while(compIt.hasNext()){ compIt.next().calculate(); } } /** * Updates interface with the latest changes to all the components. Sorts all the info * into modifiable components and non modifiable components * @param packets Info about all the components in the game */ public void updateInterfaceComponents(ArrayList<InfoPacket> packets) { String nonmodifiable = new String(); String modifiable = new String(); Iterator<InfoPacket> packetIter = packets.iterator(); InfoPacket pckt = null; // All info gathered about a component String componentName = new String(); String componentDescriptionModi = new String(); String componentDescriptionNon = new String(); while (packetIter.hasNext()) { pckt = packetIter.next(); Iterator<Pair<?>> namedValueIter = pckt.namedValues.iterator(); while (namedValueIter.hasNext()) { Pair<?> pair = namedValueIter.next(); Label currentLabel = pair.getLabel(); switch (currentLabel) { case cNme: componentName = (String) pair.second() + '\n'; break; /*case rcIF: componentDescriptionNon += "Gets inputs from: " + pair.second().toString() + '\n'; break; case oPto: componentDescriptionNon += "Outputs to: " + pair.second().toString() + '\n'; break;*/ case temp: componentDescriptionNon += "Temperature: " + pair.second().toString() + '\n'; break; case pres: componentDescriptionNon += "Pressure: " + pair.second().toString() + '\n'; break; case coRL: componentDescriptionModi += "Control rod level: " + pair.second().toString() + '\n'; break; case wLvl: componentDescriptionNon += "Water level: " + pair.second().toString() + '\n'; break; case RPMs: componentDescriptionModi += "RPMs: " + pair.second().toString() + '\n'; break; case psit: componentDescriptionModi += "Position: " + pair.second().toString() + '\n'; break; case elec: componentDescriptionNon += "Electricity generated: " + pair.second().toString() + '\n'; break; case OPFL: componentDescriptionNon += "Output flow rate: " + pair.second().toString() + '\n'; break; default: break; } } if (componentDescriptionNon.length() != 0 && componentName.length() != 0) nonmodifiable += componentName + componentDescriptionNon + '\n'; if (componentDescriptionModi.length() != 0 && componentName.length() != 0) modifiable += componentName + componentDescriptionModi + '\n'; componentName = ""; componentDescriptionNon = ""; componentDescriptionModi = ""; } window.updateLeftPanel(nonmodifiable); window.updateRightPanel(modifiable); } /** * Checks if a file name is already stored in the system (happens if the game was started using load or if save as command was previously used) * and can be used for further save games * @param packets the state of the power plant that needs to be save * @return returns what should be out put to the console */ public String save(ArrayList<InfoPacket> packets) { if (fileName != null) { saveGameState(packets, fileName); return "File saved"; } else { return "Use save as command, because there is no valid filename"; } } public static void main(String[] args) { GameEngine gameEngine = new GameEngine(); ArrayList<InfoPacket> infoList = new ArrayList<InfoPacket>(); InfoPacket info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Valve 1")); info.namedValues.add(new Pair<Boolean>(Label.psit, true)); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<String>(Label.rcIF, "Valve 2")); info.namedValues.add(new Pair<String>(Label.oPto, "Valve 2")); infoList.add(info); info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Valve 2")); info.namedValues.add(new Pair<Boolean>(Label.psit, true)); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<String>(Label.oPto, "Valve 1")); info.namedValues.add(new Pair<String>(Label.rcIF, "Valve 1")); infoList.add(info); info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Pump 1")); info.namedValues.add(new Pair<Boolean>(Label.psit, true)); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<Double>(Label.RPMs, 5.00)); info.namedValues.add(new Pair<String>(Label.oPto, "Valve 3")); info.namedValues.add(new Pair<String>(Label.rcIF, "Condenser")); infoList.add(info); info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Valve 3")); info.namedValues.add(new Pair<Boolean>(Label.psit, true)); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<String>(Label.oPto, "Pump 1")); info.namedValues.add(new Pair<String>(Label.rcIF, "Pump 1")); infoList.add(info); info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Pump 2")); info.namedValues.add(new Pair<Boolean>(Label.psit, true)); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<Double>(Label.RPMs, 5.00)); info.namedValues.add(new Pair<String>(Label.oPto, "Valve 4")); info.namedValues.add(new Pair<String>(Label.rcIF, "Condenser")); infoList.add(info); info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Valve 4")); info.namedValues.add(new Pair<Boolean>(Label.psit, true)); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<String>(Label.oPto, "Pump 2")); info.namedValues.add(new Pair<String>(Label.rcIF, "Pump 2")); infoList.add(info); // /////////// info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Condenser")); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<Double>(Label.temp, 10.00)); info.namedValues.add(new Pair<Double>(Label.pres, 10.00)); info.namedValues.add(new Pair<Double>(Label.wLvl, 10.00)); info.namedValues.add(new Pair<String>(Label.oPto, "Pump 1")); info.namedValues.add(new Pair<String>(Label.oPto, "Pump 2")); info.namedValues.add(new Pair<String>(Label.rcIF, "Coolant Pump")); // info.namedValues.add(new Pair<String>(Label.rcIF, "Turbine")); // //doesn't exist yet info.namedValues.add(new Pair<String>(Label.rcIF, "Valve 2")); infoList.add(info); info = new InfoPacket(); info.namedValues.add(new Pair<String>(Label.cNme, "Coolant Pump")); info.namedValues.add(new Pair<Boolean>(Label.psit, true)); info.namedValues.add(new Pair<Double>(Label.OPFL, 12.34)); info.namedValues.add(new Pair<Double>(Label.RPMs, 5.00)); info.namedValues.add(new Pair<String>(Label.oPto, "Condenser")); info.namedValues.add(new Pair<String>(Label.rcIF, "Coolant Pump")); infoList.add(info); // /////////// gameEngine.clearPowerPlant(); assert (gameEngine.getAllComponentInfo().isEmpty()); gameEngine.setupPowerPlantConfiguration(infoList); gameEngine.updateInterfaceComponents(gameEngine.getAllComponentInfo()); System.out.println("HellO"); //The Game control loop int autosaveTime = 0; while(true){ autosaveTime++; gameEngine.updateInterfaceComponents(gameEngine.getAllComponentInfo()); //Update the Screen with the current Values after the wait. gameEngine.calculateAllComponents(); //Calculate new Values. gameEngine.updateInterfaceComponents(gameEngine.getAllComponentInfo()); //Update the screen with the new values. if(autosaveTime == 10){ //gameEngine.saveGameState(gameEngine.getAllComponentInfo(), "autosave"); //Save the game state to autosave file //Doesnt currently work due to null values in components - adding defaul values should fix autosaveTime = 0; } try { Thread.sleep(700); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } } } }
true
true
public void readfile(String file) throws FileNotFoundException { // FileReader fr=new FileReader(path); // BufferedReader br=new BufferedReader(fr); String path = new java.io.File("").getAbsolutePath() + "/saves/"; FileInputStream fstream = new FileInputStream(path + file + ".fg"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); clearPowerPlant(); ArrayList<String> data = new ArrayList<String>(); ArrayList<InfoPacket> infoList = new ArrayList<InfoPacket>(); String temp; try { while ((temp = br.readLine()) != null) { data.add(temp); } br.close(); String textData[] = new String[data.size()]; textData= data.toArray(new String[0]); InfoPacket info = new InfoPacket(); int i = 0; while (i < data.size()) { String ch = textData[i].substring(0, textData[i].indexOf("&")); String d = textData[i].substring(textData[i].indexOf("&") + 1, textData[i].length()); if (ch.equals(Label.cNme.toString())) { if(i != 0) { infoList.add(info); info = new InfoPacket(); } info.namedValues.add(new Pair<String>(Label.cNme, d)); //System.out.println(ch + "=" + c1); } else if (ch.equals(Label.falT.toString())) { Double i1 = Double.parseDouble(d); info.namedValues.add(new Pair<Double>(Label.falT, i1)); //System.out.println(ch + "=" + i1); } else if (ch.equals(Label.OPFL.toString())) { Float i1 = Float.parseFloat(d); info.namedValues.add(new Pair<Float>(Label.OPFL, i1)); System.out.println(ch + "=" + i1); } else if (ch.equals(Label.psit.toString())) { boolean ok = Boolean.parseBoolean(d); info.namedValues.add(new Pair<Boolean>(Label.psit, ok)); //System.out.println(ch + "=" + ok); } else if (ch.equals(Label.oPto.toString())) { info.namedValues.add(new Pair<String>(Label.oPto, d)); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.rcIF.toString())) { info.namedValues.add(new Pair<String>(Label.rcIF, d)); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.pres.toString())) { info.namedValues.add(new Pair<Double>(Label.pres, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.Vlme.toString())) { info.namedValues.add(new Pair<Double>(Label.Vlme, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.pres.toString())) { info.namedValues.add(new Pair<Double>(Label.pres, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.RPMs.toString())) { info.namedValues.add(new Pair<Double>(Label.RPMs, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.temp.toString())) { info.namedValues.add(new Pair<Double>(Label.temp, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.wLvl.toString())) { info.namedValues.add(new Pair<Double>(Label.wLvl, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.Amnt.toString())) { info.namedValues.add(new Pair<Double>(Label.Amnt, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.coRL.toString())) { info.namedValues.add(new Pair<Double>(Label.coRL, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } i++; } infoList.add(info); } catch (IOException e) { System.out.println("Cannot load file"); } setupPowerPlantConfiguration(infoList); }
public void readfile(String file) throws FileNotFoundException { // FileReader fr=new FileReader(path); // BufferedReader br=new BufferedReader(fr); String path = new java.io.File("").getAbsolutePath() + "/saves/"; FileInputStream fstream = new FileInputStream(path + file + ".fg"); // Get the object of DataInputStream DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); clearPowerPlant(); ArrayList<String> data = new ArrayList<String>(); ArrayList<InfoPacket> infoList = new ArrayList<InfoPacket>(); String temp; try { while ((temp = br.readLine()) != null) { data.add(temp); } br.close(); String textData[] = new String[data.size()]; textData= data.toArray(new String[0]); InfoPacket info = new InfoPacket(); int i = 0; while (i < data.size()) { String ch = textData[i].substring(0, textData[i].indexOf("&")); String d = textData[i].substring(textData[i].indexOf("&") + 1, textData[i].length()); if (ch.equals(Label.cNme.toString())) { if(i != 0) { infoList.add(info); info = new InfoPacket(); } info.namedValues.add(new Pair<String>(Label.cNme, d)); //System.out.println(ch + "=" + c1); } else if (ch.equals(Label.falT.toString())) { Double i1 = Double.parseDouble(d); info.namedValues.add(new Pair<Double>(Label.falT, i1)); //System.out.println(ch + "=" + i1); } else if (ch.equals(Label.OPFL.toString())) { Double i1 = Double.parseDouble(d); info.namedValues.add(new Pair<Double>(Label.OPFL, i1)); System.out.println(ch + "=" + i1); } else if (ch.equals(Label.psit.toString())) { boolean ok = Boolean.parseBoolean(d); info.namedValues.add(new Pair<Boolean>(Label.psit, ok)); //System.out.println(ch + "=" + ok); } else if (ch.equals(Label.oPto.toString())) { info.namedValues.add(new Pair<String>(Label.oPto, d)); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.rcIF.toString())) { info.namedValues.add(new Pair<String>(Label.rcIF, d)); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.pres.toString())) { info.namedValues.add(new Pair<Double>(Label.pres, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.Vlme.toString())) { info.namedValues.add(new Pair<Double>(Label.Vlme, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.pres.toString())) { info.namedValues.add(new Pair<Double>(Label.pres, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.RPMs.toString())) { info.namedValues.add(new Pair<Double>(Label.RPMs, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.temp.toString())) { info.namedValues.add(new Pair<Double>(Label.temp, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.wLvl.toString())) { info.namedValues.add(new Pair<Double>(Label.wLvl, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.Amnt.toString())) { info.namedValues.add(new Pair<Double>(Label.Amnt, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } else if (ch.equals(Label.coRL.toString())) { info.namedValues.add(new Pair<Double>(Label.coRL, Double.parseDouble(d))); //System.out.println(ch + "=" + d); } i++; } infoList.add(info); } catch (IOException e) { System.out.println("Cannot load file"); } setupPowerPlantConfiguration(infoList); }
diff --git a/src/com/tactfactory/mda/symfony/template/WebGenerator.java b/src/com/tactfactory/mda/symfony/template/WebGenerator.java index dc1914bb..857c2e4d 100644 --- a/src/com/tactfactory/mda/symfony/template/WebGenerator.java +++ b/src/com/tactfactory/mda/symfony/template/WebGenerator.java @@ -1,205 +1,205 @@ package com.tactfactory.mda.symfony.template; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import com.google.common.base.CaseFormat; import com.tactfactory.mda.ConsoleUtils; import com.tactfactory.mda.ConsoleUtils.ProcessToConsoleBridge; import com.tactfactory.mda.meta.ClassMetadata; import com.tactfactory.mda.plateforme.BaseAdapter; import com.tactfactory.mda.symfony.adapter.SymfonyAdapter; import com.tactfactory.mda.template.BaseGenerator; import com.tactfactory.mda.template.TagConstant; import com.tactfactory.mda.utils.FileUtils; public class WebGenerator extends BaseGenerator{ private static final int GENERATE_ENTITIES = 0x00; private static final int INSTALL_SYMFONY = 0x01; private static final int INSTALL_BUNDLES = 0x02; private static final int INIT_PROJECT = 0x03; private SymfonyAdapter symfonyAdapter; private String projectName; public WebGenerator(BaseAdapter adapter, SymfonyAdapter sAdapter) throws Exception { super(adapter); this.datamodel = this.appMetas.toMap(this.adapter); this.symfonyAdapter = sAdapter; this.projectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.appMetas.name); } public void generateEntities(){ for(ClassMetadata cm : this.appMetas.entities.values()){ if(cm.options.containsKey("rest") && cm.fields.size()>0){ this.datamodel.put(TagConstant.CURRENT_ENTITY, cm.getName()); makeEntity(cm.name); } } this.launchCommand(GENERATE_ENTITIES); } public void generateWebControllers(){ for(ClassMetadata cm : this.appMetas.entities.values()){ if(cm.options.containsKey("rest") && cm.fields.size()>0){ this.datamodel.put(TagConstant.CURRENT_ENTITY, cm.getName()); makeController(cm.name); } } } public void installSymfony(){ // Copy composer.phar : this.copyFile(this.symfonyAdapter.getWebTemplatePath()+"composer.phar", this.symfonyAdapter.getWebRootPath()); // Execute composer.phar to download symfony : this.launchCommand(INSTALL_SYMFONY); } public void installBundles(){ //Copy composer.json to symfony's path this.copyFile(this.symfonyAdapter.getWebTemplatePath()+"composer.json", this.symfonyAdapter.getWebPath()); //Execute composer.phar to download and install fosrestbundle: this.launchCommand(INSTALL_BUNDLES); File configTplFile = new File(this.symfonyAdapter.getWebTemplateConfigPath()+"config.yml"); StringBuffer sb = FileUtils.FileToStringBuffer(configTplFile); //this.addToFile(sb.toString(), this.symfonyPath+"/Symfony/app/config/config.yml"); File configFile = new File(this.symfonyAdapter.getWebPath()+"app/config/config.yml"); FileUtils.appendToFile(sb.toString(), configFile); String restBundleLoad = "\n\t\tnew FOS\\RestBundle\\FOSRestBundle(),"; this.addAfter(restBundleLoad, "$bundles = array(", this.symfonyAdapter.getWebPath()+"app/AppKernel.php"); String serializerBundleLoad = "\n\t\tnew JMS\\SerializerBundle\\JMSSerializerBundle(),"; this.addAfter(serializerBundleLoad, restBundleLoad, this.symfonyAdapter.getWebPath()+"app/AppKernel.php"); } public void initProject(){ this.launchCommand(INIT_PROJECT); } protected void makeEntity(String entityName){ String fullFilePath = this.symfonyAdapter.getWebBundleYmlEntitiesPath(this.projectName) + entityName+".orm.yml"; String fullTemplatePath = this.symfonyAdapter.getWebTemplateEntityPath().substring(1)+"entity.yml"; super.makeSource(fullTemplatePath, fullFilePath, true); } protected void makeController(String entityName){ String fullFilePath = this.symfonyAdapter.getWebControllerPath(this.projectName)+"Rest"+entityName+"Controller.php"; String fullTemplatePath = this.symfonyAdapter.getWebTemplateControllerPath().substring(1)+"RestTemplateController.php"; super.makeSource(fullTemplatePath, fullFilePath, true); fullFilePath = this.symfonyAdapter.getWebPath()+"app/config/routing.yml"; fullTemplatePath = this.symfonyAdapter.getWebTemplateConfigPath()+"routing.yml"; super.appendSource(fullTemplatePath, fullFilePath); } protected void launchCommand(int command){ try { ProcessBuilder pb = new ProcessBuilder(this.getCommand(command)); Process exec = pb.start(); ProcessToConsoleBridge bridge = new ProcessToConsoleBridge(exec); bridge.start(); try { exec.waitFor(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } bridge.stop(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void copyFile(String srcPath, String destPath){ File srcFile; File destDir; try { destDir = new File(destPath); srcFile = new File(srcPath); FileUtils.copyFileToDirectory(srcFile, destDir); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void addToFile(String content, String filePath){ try{ File f = new File(filePath); BufferedWriter bw = new BufferedWriter(new FileWriter(f, true)); bw.write(content); bw.close(); }catch(IOException e){ ConsoleUtils.displayError(e.getMessage()); } } protected void addAfter(String content, String after, String filePath){ File file = new File(filePath); FileUtils.addToFile(content, after, file); } private ArrayList<String> getCommand(int command){ String projectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.appMetas.name); ArrayList<String> commandArgs = new ArrayList<String>(); switch(command){ case INSTALL_SYMFONY: commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebRootPath()+"/composer.phar"); // Composer path commandArgs.add("create-project"); commandArgs.add("symfony/framework-standard-edition"); // Project to install commandArgs.add(this.symfonyAdapter.getWebPath()); // Installation folder - commandArgs.add("dev-master"); // Version + commandArgs.add("2.1.7"); // Version break; case INSTALL_BUNDLES: //"php "+this.symfonyPath+"/composer.phar update -d "+this.symfonyPath+"/Symfony" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebRootPath()+"composer.phar"); // Composer path commandArgs.add("update"); commandArgs.add("-d"); commandArgs.add(this.symfonyAdapter.getWebPath()); // Installation folder break; case INIT_PROJECT: //"php "+this.symfonyPath+"/Symfony/app/console generate:bundle --namespace="+name+"/ApiBundle --dir="+this.symfonyPath+"/Symfony/src"+" --bundle-name="+name+"ApiBundle --format=yml --structure=yes --no-interaction" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebPath()+"app/console"); // Symfony console path commandArgs.add("generate:bundle"); commandArgs.add("--namespace="+projectName+"/ApiBundle"); // Namespace commandArgs.add("--dir="+this.symfonyAdapter.getWebPath()+"src"); // Bundle folder commandArgs.add("--bundle-name="+projectName+"ApiBundle"); // Bundle name commandArgs.add("--format=yml"); // Format commandArgs.add("--structure=yes"); // Generate project folder structure commandArgs.add("--no-interaction"); // Silent mode break; case GENERATE_ENTITIES: //"php "+this.symfonyPath+"/Symfony/app/console doctrine:generate:entities "+name+"ApiBundle" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebPath()+"app/console"); // Symfony console path commandArgs.add("doctrine:generate:entities"); commandArgs.add(projectName+"ApiBundle"); // Bundle Namespace break; } return commandArgs; } }
true
true
private ArrayList<String> getCommand(int command){ String projectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.appMetas.name); ArrayList<String> commandArgs = new ArrayList<String>(); switch(command){ case INSTALL_SYMFONY: commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebRootPath()+"/composer.phar"); // Composer path commandArgs.add("create-project"); commandArgs.add("symfony/framework-standard-edition"); // Project to install commandArgs.add(this.symfonyAdapter.getWebPath()); // Installation folder commandArgs.add("dev-master"); // Version break; case INSTALL_BUNDLES: //"php "+this.symfonyPath+"/composer.phar update -d "+this.symfonyPath+"/Symfony" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebRootPath()+"composer.phar"); // Composer path commandArgs.add("update"); commandArgs.add("-d"); commandArgs.add(this.symfonyAdapter.getWebPath()); // Installation folder break; case INIT_PROJECT: //"php "+this.symfonyPath+"/Symfony/app/console generate:bundle --namespace="+name+"/ApiBundle --dir="+this.symfonyPath+"/Symfony/src"+" --bundle-name="+name+"ApiBundle --format=yml --structure=yes --no-interaction" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebPath()+"app/console"); // Symfony console path commandArgs.add("generate:bundle"); commandArgs.add("--namespace="+projectName+"/ApiBundle"); // Namespace commandArgs.add("--dir="+this.symfonyAdapter.getWebPath()+"src"); // Bundle folder commandArgs.add("--bundle-name="+projectName+"ApiBundle"); // Bundle name commandArgs.add("--format=yml"); // Format commandArgs.add("--structure=yes"); // Generate project folder structure commandArgs.add("--no-interaction"); // Silent mode break; case GENERATE_ENTITIES: //"php "+this.symfonyPath+"/Symfony/app/console doctrine:generate:entities "+name+"ApiBundle" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebPath()+"app/console"); // Symfony console path commandArgs.add("doctrine:generate:entities"); commandArgs.add(projectName+"ApiBundle"); // Bundle Namespace break; } return commandArgs; }
private ArrayList<String> getCommand(int command){ String projectName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.appMetas.name); ArrayList<String> commandArgs = new ArrayList<String>(); switch(command){ case INSTALL_SYMFONY: commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebRootPath()+"/composer.phar"); // Composer path commandArgs.add("create-project"); commandArgs.add("symfony/framework-standard-edition"); // Project to install commandArgs.add(this.symfonyAdapter.getWebPath()); // Installation folder commandArgs.add("2.1.7"); // Version break; case INSTALL_BUNDLES: //"php "+this.symfonyPath+"/composer.phar update -d "+this.symfonyPath+"/Symfony" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebRootPath()+"composer.phar"); // Composer path commandArgs.add("update"); commandArgs.add("-d"); commandArgs.add(this.symfonyAdapter.getWebPath()); // Installation folder break; case INIT_PROJECT: //"php "+this.symfonyPath+"/Symfony/app/console generate:bundle --namespace="+name+"/ApiBundle --dir="+this.symfonyPath+"/Symfony/src"+" --bundle-name="+name+"ApiBundle --format=yml --structure=yes --no-interaction" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebPath()+"app/console"); // Symfony console path commandArgs.add("generate:bundle"); commandArgs.add("--namespace="+projectName+"/ApiBundle"); // Namespace commandArgs.add("--dir="+this.symfonyAdapter.getWebPath()+"src"); // Bundle folder commandArgs.add("--bundle-name="+projectName+"ApiBundle"); // Bundle name commandArgs.add("--format=yml"); // Format commandArgs.add("--structure=yes"); // Generate project folder structure commandArgs.add("--no-interaction"); // Silent mode break; case GENERATE_ENTITIES: //"php "+this.symfonyPath+"/Symfony/app/console doctrine:generate:entities "+name+"ApiBundle" commandArgs.add("php"); commandArgs.add(this.symfonyAdapter.getWebPath()+"app/console"); // Symfony console path commandArgs.add("doctrine:generate:entities"); commandArgs.add(projectName+"ApiBundle"); // Bundle Namespace break; } return commandArgs; }
diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java index 6cc7f745..ad841845 100644 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java +++ b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJDeclarationsConverter.java @@ -1,766 +1,769 @@ /* Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved This file is part of JNAerator (http://jnaerator.googlecode.com/). JNAerator 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. JNAerator 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 JNAerator. If not, see <http://www.gnu.org/licenses/>. */ package com.ochafik.lang.jnaerator; import org.bridj.ann.Name; import org.bridj.BridJ; import org.bridj.FlagSet; import org.bridj.IntValuedEnum; import org.bridj.StructObject; import org.bridj.cpp.CPPObject; import org.bridj.cpp.com.IUnknown; import com.ochafik.lang.jnaerator.BridJTypeConversion.NL4JConversion; import com.ochafik.lang.jnaerator.TypeConversion.ConvType; //import org.bridj.structs.StructIO; //import org.bridj.structs.Array; import java.io.IOException; import java.util.*; import com.ochafik.lang.jnaerator.parser.*; import com.ochafik.lang.jnaerator.parser.Enum; import com.ochafik.lang.jnaerator.parser.Statement.Block; import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; import com.ochafik.lang.jnaerator.parser.Struct.MemberVisibility; import com.ochafik.lang.jnaerator.parser.TypeRef.*; import com.ochafik.lang.jnaerator.parser.Expression.*; import com.ochafik.lang.jnaerator.parser.Function.Type; import com.ochafik.lang.jnaerator.parser.DeclarationsHolder.ListWrapper; import com.ochafik.lang.jnaerator.parser.Declarator.*; import com.ochafik.util.listenable.Pair; import com.ochafik.util.string.StringUtils; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; import com.ochafik.lang.jnaerator.parser.Function.SignatureType; import com.sun.jna.win32.StdCallLibrary; import org.bridj.*; import org.bridj.ann.Convention; import org.bridj.objc.NSObject; public class BridJDeclarationsConverter extends DeclarationsConverter { public BridJDeclarationsConverter(Result result) { super(result); } public void annotateActualName(ModifiableElement e, Identifier name) { e.addAnnotation(new Annotation(Name.class, expr(name.toString()))); } @Override public Struct convertCallback(FunctionSignature functionSignature, Signatures signatures, Identifier callerLibraryName) { Struct decl = super.convertCallback(functionSignature, signatures, callerLibraryName); if (decl != null) { decl.setParents(Arrays.asList((SimpleTypeRef)( FunctionSignature.Type.ObjCBlock.equals(functionSignature.getType()) ? result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ObjCBlock) : (SimpleTypeRef)typeRef(ident(result.config.runtime.callbackClass, expr(typeRef(decl.getTag().clone())))) ))); //addCallingConventionAnnotation(functionSignature.getFunction(), decl); } return decl; } @Override public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) return; Identifier rawEnumName = getActualTaggedTypeName(e); List<EnumItemResult> results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) return; signatures = new Signatures(); Enum en = new Enum(); if (!result.config.noComments) en.importComments(e, "enum values", getFileCommentContent(e)); if (!rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName))) ))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef() ), MemberRefStyle.Dot, "iterator" ) ) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values" ) ) ) )).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) cc = Convention.Style.StdCall; else if (originalFunction.hasModifier(ModifierType.__fastcall)) cc = Convention.Style.FastCall; else if (originalFunction.hasModifier(ModifierType.__thiscall)) cc = Convention.Style.ThisCall; else if (originalFunction.hasModifier(ModifierType.__pascal)) cc = Convention.Style.Pascal; if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) return; boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) nativeMethod.addModifiers(ModifierType.Synchronized); addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); if (mgc != null) { nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); } } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block)bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) out.addDeclaration(d); } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); out.addDeclaration(nativeMethod); boolean generateStaticMethod = isStatic || !isCallback && !isInStruct; if (convertedBody == null) { boolean forwardedToRaw = false; if (result.config.genRawBindings && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers(ModifierType.Protected, ModifierType.Native); if (generateStaticMethod) rawMethod.addModifiers(ModifierType.Static); if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { out.addDeclaration(rawMethod); List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } + if (varArgType != null) { + followedArgs.add(varRef(varArgName)); + } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) nativeMethod.setBody(block(stat(followedCall))); else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) followedCall = new New(nativeMethod.getValueType(), followedCall); else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); if (returnType.targetTypeConversion == null || returnType.targetTypeConversion.type == ConvType.Void) followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); else followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); } else nativeMethod.setBody(convertedBody); nativeMethod.addModifiers( isProtected ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null ); } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } if (!isCallback && !javaMethodName.equals(functionName)) annotateActualName(nativeMethod, functionName); } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) return null; //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) return null; if (!signatures.addClass(structName)) return null; boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant)struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[] { parentFieldsCount }; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) structJavaClass.addDeclaration(defaultConstructor); if (isUnion) structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef)d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof FunctionSignature) { convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) continue; // default constructor was already generated String library = result.getLibrary(struct); if (library == null) continue; List<Declaration> decls = new ArrayList<Declaration>(); convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) continue; Function method = (Function) md; boolean commentOut = false; if (isVirtual) method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) commentOut = true; if (commentOut) structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); else structJavaClass.addDeclaration(method); } if (isVirtual) iVirtual++; if (isConstructor) iConstructor++; } } } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) structJavaClass.addDeclaration(castConstructor); return structJavaClass; } Map<Identifier, Boolean> structsVirtuality = new HashMap<Identifier, Boolean>(); public boolean isVirtual(Struct struct) { Identifier name = getActualTaggedTypeName(struct); Boolean bVirtual = structsVirtuality.get(name); if (bVirtual == null) { boolean hasVirtualParent = false, hasVirtualMembers = false; for (SimpleTypeRef parentName : struct.getParents()) { Struct parentStruct = result.structsByName.get(parentName.getName()); if (parentStruct == null) { if (result.config.verbose) System.out.println("Failed to resolve parent '" + parentName + "' for struct '" + name + "'"); continue; } if (isVirtual(parentStruct)) { hasVirtualParent = true; break; } } for (Declaration mb : struct.getDeclarations()) { if (mb.hasModifier(ModifierType.Virtual)) { hasVirtualMembers = true; break; } } bVirtual = hasVirtualMembers && !hasVirtualParent; structsVirtuality.put(name, bVirtual); } return bVirtual; } protected String ioVarName = "io", ioStaticVarName = "IO"; public List<Declaration> convertVariablesDeclarationToBridJ(String name, TypeRef mutatedType, int[] iChild, int bits, boolean isGlobal, Identifier holderName, Identifier callerLibraryName, String callerLibrary, Element... toImportDetailsFrom) throws UnsupportedConversionException { name = result.typeConverter.getValidJavaArgumentName(ident(name)).toString(); //convertVariablesDeclaration(name, mutatedType, out, iChild, callerLibraryName); final boolean useRawTypes = false; //Expression initVal = null; int fieldIndex = iChild[0]; //convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structPeerExpr, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { NL4JConversion conv = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J( mutatedType, callerLibraryName, thisField("io"), varRef(name), fieldIndex, bits ); if (conv == null) { throw new UnsupportedConversionException(mutatedType, "failed to convert type to Java"); } else if ("void".equals(String.valueOf(conv.getTypeRef(useRawTypes)))) { throw new UnsupportedConversionException(mutatedType, "void type !"); //out.add(new EmptyDeclaration("SKIPPED:", v.formatComments("", true, true, false), v.toString())); } Function convDecl = new Function(); conv.annotateTypedType(convDecl, useRawTypes); convDecl.setType(Type.JavaMethod); convDecl.addModifiers(ModifierType.Public); if (conv.arrayLengths != null) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Length), "({" + StringUtils.implode(conv.arrayLengths, ", ") + "})")); if (conv.bits != null) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), conv.bits)); if (conv.byValue) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.ByValue))); for (Element e : toImportDetailsFrom) convDecl.importDetails(e, false); convDecl.importDetails(mutatedType, true); //convDecl.importDetails(javaType, true); // convDecl.importDetails(v, false); // convDecl.importDetails(vs, false); // convDecl.importDetails(valueType, false); // valueType.stripDetails(); convDecl.moveAllCommentsBefore(); convDecl.setName(ident(name)); if (!isGlobal) convDecl.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Field), expr(fieldIndex))); convDecl.setValueType(conv.getTypeRef(useRawTypes)); TypeRef javaType = convDecl.getValueType(); String pointerGetSetMethodSuffix = StringUtils.capitalize(javaType.toString()); Expression getGlobalPointerExpr = null; if (isGlobal) { getGlobalPointerExpr = methodCall(methodCall(methodCall(expr(typeRef(BridJ.class)), "getNativeLibrary", expr(callerLibrary)), "getSymbolPointer", expr(name)), "as", result.typeConverter.typeLiteral(javaType.clone())); } List<Declaration> out = new ArrayList<Declaration>(); if (conv.getExpr != null) { Function getter = convDecl.clone(); if (isGlobal) { getter.setBody(block( tryRethrow(new Statement.Return(cast(javaType.clone(), methodCall(getGlobalPointerExpr, "get")))) )); } else { getter.setBody(block( new Statement.Return(conv.getExpr) )); } out.add(getter); } if (!conv.readOnly && conv.setExpr != null) { Function setter = convDecl.clone(); setter.setValueType(typeRef(holderName.clone()));//Void.TYPE)); setter.addArg(new Arg(name, javaType)); //setter.addModifiers(ModifierType.Native); if (isGlobal) { setter.setBody(block( tryRethrow(block( stat(methodCall(getGlobalPointerExpr, "set", varRef(name))), new Statement.Return(thisRef()) )) )); } else { setter.setBody(block( stat(conv.setExpr), new Statement.Return(thisRef()) )); } out.add(setter); if (result.config.scalaStructSetters) { setter = new Function(); setter.setType(Type.JavaMethod); setter.setName(ident(name + "_$eq")); setter.setValueType(javaType.clone()); setter.addArg(new Arg(name, javaType.clone())); setter.addModifiers(ModifierType.Public, ModifierType.Final); setter.setBody(block( stat(methodCall(name, varRef(name))), new Statement.Return(varRef(name)) )); out.add(setter); } } return out; } @Override public void convertVariablesDeclaration(VariablesDeclaration v, Signatures signatures, DeclarationsHolder out, int[] iChild, boolean isGlobal, Identifier holderName, Identifier callerLibraryClass, String callerLibrary) { try { TypeRef valueType = v.getValueType(); for (Declarator vs : v.getDeclarators()) { if (vs.getDefaultValue() != null) continue; String name = vs.resolveName(); if (name == null || name.length() == 0) { name = "anonymous" + (nextAnonymousFieldId++); } TypeRef mutatedType = valueType; if (!(vs instanceof DirectDeclarator)) { mutatedType = (TypeRef)vs.mutateTypeKeepingParent(valueType); vs = new DirectDeclarator(vs.resolveName()); } //Declarator d = v.getDeclarators().get(0); List<Declaration> vds = convertVariablesDeclarationToBridJ(name, mutatedType, iChild, vs.getBits(), isGlobal, holderName, callerLibraryClass, callerLibrary, v, vs); if (vs.getBits() > 0) for (Declaration vd : vds) vd.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Bits), expr(vs.getBits()))); for (Declaration vd : vds) { if (vd instanceof Function) { if (!signatures.addMethod((Function)vd)) continue; } vd.importDetails(mutatedType, true); vd.moveAllCommentsBefore(); if (!(mutatedType instanceof Primitive) && !result.config.noComments) vd.addToCommentBefore("C type : " + mutatedType); out.addDeclaration(vd); } //} iChild[0]++; } } catch (Throwable e) { if (!(e instanceof UnsupportedConversionException)) e.printStackTrace(); if (!result.config.limitComments) out.addDeclaration(new EmptyDeclaration(e.toString())); } } int nextAnonymousFieldId; @Override protected void configureCallbackStruct(Struct callbackStruct) { callbackStruct.setType(Struct.Type.JavaClass); callbackStruct.addModifiers(ModifierType.Public, ModifierType.Static, ModifierType.Abstract); } @Override protected Struct createFakePointerClass(Identifier fakePointer) { Struct ptClass = result.declarationsConverter.publicStaticClass(fakePointer, ident(TypedPointer.class), Struct.Type.JavaClass, null); String addressVarName = "address"; ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(long.class)) ).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName))))) ); ptClass.addDeclaration(new Function(Function.Type.JavaMethod, fakePointer, null, new Arg(addressVarName, typeRef(org.bridj.Pointer.class)) ).addModifiers(ModifierType.Public).setBody( block(stat(methodCall("super", varRef(addressVarName))))) ); return ptClass; } }
true
true
public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) return; Identifier rawEnumName = getActualTaggedTypeName(e); List<EnumItemResult> results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) return; signatures = new Signatures(); Enum en = new Enum(); if (!result.config.noComments) en.importComments(e, "enum values", getFileCommentContent(e)); if (!rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName))) ))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef() ), MemberRefStyle.Dot, "iterator" ) ) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values" ) ) ) )).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) cc = Convention.Style.StdCall; else if (originalFunction.hasModifier(ModifierType.__fastcall)) cc = Convention.Style.FastCall; else if (originalFunction.hasModifier(ModifierType.__thiscall)) cc = Convention.Style.ThisCall; else if (originalFunction.hasModifier(ModifierType.__pascal)) cc = Convention.Style.Pascal; if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) return; boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) nativeMethod.addModifiers(ModifierType.Synchronized); addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); if (mgc != null) { nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); } } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block)bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) out.addDeclaration(d); } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); out.addDeclaration(nativeMethod); boolean generateStaticMethod = isStatic || !isCallback && !isInStruct; if (convertedBody == null) { boolean forwardedToRaw = false; if (result.config.genRawBindings && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers(ModifierType.Protected, ModifierType.Native); if (generateStaticMethod) rawMethod.addModifiers(ModifierType.Static); if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { out.addDeclaration(rawMethod); List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) nativeMethod.setBody(block(stat(followedCall))); else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) followedCall = new New(nativeMethod.getValueType(), followedCall); else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); if (returnType.targetTypeConversion == null || returnType.targetTypeConversion.type == ConvType.Void) followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); else followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); } else nativeMethod.setBody(convertedBody); nativeMethod.addModifiers( isProtected ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null ); } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } if (!isCallback && !javaMethodName.equals(functionName)) annotateActualName(nativeMethod, functionName); } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) return null; //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) return null; if (!signatures.addClass(structName)) return null; boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant)struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[] { parentFieldsCount }; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) structJavaClass.addDeclaration(defaultConstructor); if (isUnion) structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef)d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof FunctionSignature) { convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) continue; // default constructor was already generated String library = result.getLibrary(struct); if (library == null) continue; List<Declaration> decls = new ArrayList<Declaration>(); convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) continue; Function method = (Function) md; boolean commentOut = false; if (isVirtual) method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) commentOut = true; if (commentOut) structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); else structJavaClass.addDeclaration(method); } if (isVirtual) iVirtual++; if (isConstructor) iConstructor++; } } } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) structJavaClass.addDeclaration(castConstructor); return structJavaClass; }
public void convertEnum(Enum e, Signatures signatures, DeclarationsHolder out, Identifier libraryClassName) { if (e.isForwardDeclaration()) return; Identifier rawEnumName = getActualTaggedTypeName(e); List<EnumItemResult> results = getEnumValuesAndCommentsByName(e, signatures, libraryClassName); boolean hasEnumClass = false; if (rawEnumName != null && rawEnumName.resolveLastSimpleIdentifier().getName() != null) { hasEnumClass = true; Identifier enumName = result.typeConverter.getValidJavaIdentifier(rawEnumName); if (!signatures.addClass(enumName)) return; signatures = new Signatures(); Enum en = new Enum(); if (!result.config.noComments) en.importComments(e, "enum values", getFileCommentContent(e)); if (!rawEnumName.equals(enumName)) annotateActualName(en, rawEnumName); en.setType(Enum.Type.Java); en.setTag(enumName.clone()); en.addModifiers(ModifierType.Public); out.addDeclaration(new TaggedTypeRefDeclaration(en)); Struct body = new Struct(); en.setBody(body); boolean hasValidItem = false; for (EnumItemResult er : results) { if (er.errorElement != null) { out.addDeclaration(er.errorElement); continue; } String itemName = result.typeConverter.getValidJavaIdentifierString(ident(er.originalItem.getName())); Enum.EnumItem item = new Enum.EnumItem(itemName, er.convertedValue); en.addItem(item); hasValidItem = true; if (!result.config.noComments) if (item != null) {// && hasEnumClass) { item.importComments(er.originalItem); } } if (hasValidItem) { en.addInterface(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))); String valueArgName = "value"; body.addDeclaration(new Function(Type.JavaMethod, enumName.clone(), null, new Arg(valueArgName, typeRef(Long.TYPE))).setBody(block( stat(expr(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName), AssignmentOperator.Equal, varRef(valueArgName))) ))); body.addDeclaration(new VariablesDeclaration(typeRef(Long.TYPE), new DirectDeclarator(valueArgName)).addModifiers(ModifierType.Public, ModifierType.Final)); body.addDeclaration(new Function(Type.JavaMethod, ident(valueArgName), typeRef(Long.TYPE)).setBody(block( new Statement.Return(memberRef(thisRef(), MemberRefStyle.Dot, valueArgName)) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("iterator"), typeRef(ident(Iterator.class, expr(typeRef(enumName.clone()))))).setBody(block( new Statement.Return( methodCall( methodCall( expr(typeRef(Collections.class)), MemberRefStyle.Dot, "singleton", thisRef() ), MemberRefStyle.Dot, "iterator" ) ) )).addModifiers(ModifierType.Public)); body.addDeclaration(new Function(Type.JavaMethod, ident("fromValue"), typeRef(ident(IntValuedEnum.class, expr(typeRef(enumName.clone())))), new Arg(valueArgName, typeRef(Integer.TYPE))).setBody(block( new Statement.Return( methodCall( expr(typeRef(FlagSet.class)), MemberRefStyle.Dot, "fromValue", varRef(valueArgName), methodCall( "values" ) ) ) )).addModifiers(ModifierType.Public, ModifierType.Static)); } } else { outputEnumItemsAsConstants(results, out, signatures, libraryClassName, hasEnumClass); } } void addCallingConventionAnnotation(Function originalFunction, ModifiableElement target) { Convention.Style cc = null; if (originalFunction.hasModifier(ModifierType.__stdcall)) cc = Convention.Style.StdCall; else if (originalFunction.hasModifier(ModifierType.__fastcall)) cc = Convention.Style.FastCall; else if (originalFunction.hasModifier(ModifierType.__thiscall)) cc = Convention.Style.ThisCall; else if (originalFunction.hasModifier(ModifierType.__pascal)) cc = Convention.Style.Pascal; if (cc != null) { target.addAnnotation(new Annotation(typeRef(Convention.class), enumRef(cc))); } } @Override public void convertFunction(Function function, Signatures signatures, boolean isCallback, DeclarationsHolder out, Identifier libraryClassName, String sig, Identifier functionName, String library, int iConstructor) throws UnsupportedConversionException { Element parent = function.getParentElement(); MemberVisibility visibility = function.getVisibility(); boolean isPublic = visibility == MemberVisibility.Public || function.hasModifier(ModifierType.Public); boolean isPrivate = visibility == MemberVisibility.Private || function.hasModifier(ModifierType.Private); boolean isProtected = visibility == MemberVisibility.Protected || function.hasModifier(ModifierType.Protected); boolean isInStruct = parent instanceof Struct; if (isInStruct && result.config.skipPrivateMembers && (isPrivate || !isPublic && !isProtected)) return; boolean isStatic = function.hasModifier(ModifierType.Static); boolean isConstructor = iConstructor != -1; Function nativeMethod = new Function(Type.JavaMethod, ident(functionName), null); if (result.config.synchronizedMethods && !isCallback) nativeMethod.addModifiers(ModifierType.Synchronized); addCallingConventionAnnotation(function, nativeMethod); if (function.getName() != null && !functionName.toString().equals(function.getName().toString()) && !isCallback) { TypeRef mgc = result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Name); if (mgc != null) { nativeMethod.addAnnotation(new Annotation(mgc, "(\"" + function.getName() + "\")")); } } Function rawMethod = nativeMethod.clone(); //Map<String, NL4JConversion> argTypes = new LinkedHashMap<String, NL4JConversion>(); boolean isObjectiveC = function.getType() == Type.ObjCMethod; int iArg = 1; Set<String> argNames = new TreeSet<String>(); List<Expression> superConstructorArgs = null; if (isConstructor) { superConstructorArgs = new ArrayList<Expression>(); superConstructorArgs.add(cast(typeRef(Void.class), nullExpr())); superConstructorArgs.add(expr(iConstructor)); } Identifier varArgType = null; String varArgName = null; NL4JConversion returnType = null; List<NL4JConversion> paramTypes = new ArrayList<NL4JConversion>(); List<String> paramNames = new ArrayList<String>(); if (!isConstructor) { returnType = ((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(function.getValueType(), libraryClassName, null, null, -1, -1); } for (Arg arg : function.getArgs()) { String paramName; if (arg.isVarArg()) { assert arg.getValueType() == null; paramName = varArgName = chooseJavaArgName("varargs", iArg, argNames); varArgType = ident(isObjectiveC ? NSObject.class : Object.class); } else { paramName = chooseJavaArgName(arg.getName(), iArg, argNames); paramTypes.add(((BridJTypeConversion)result.typeConverter).convertTypeToNL4J(arg.getValueType(), libraryClassName, null, null, -1, -1)); } paramNames.add(paramName); if (isConstructor) { superConstructorArgs.add(varRef(paramName)); } iArg++; } fillIn(signatures, functionName, nativeMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, false); Block convertedBody = null; if (isConstructor) { convertedBody = block(stat(methodCall("super", superConstructorArgs.toArray(new Expression[superConstructorArgs.size()])))); } else if (result.config.convertBodies && function.getBody() != null) { try { Pair<Element, List<Declaration>> bodyAndExtraDeclarations = result.bridjer.convertToJava(function.getBody(), libraryClassName); convertedBody = (Block)bodyAndExtraDeclarations.getFirst(); for (Declaration d : bodyAndExtraDeclarations.getSecond()) out.addDeclaration(d); } catch (Exception ex) { ex.printStackTrace(System.out); nativeMethod.addToCommentBefore("TRANSLATION OF BODY FAILED: " + ex); } } if (!result.config.noComments) nativeMethod.importComments(function, isCallback ? null : getFileCommentContent(function)); out.addDeclaration(nativeMethod); boolean generateStaticMethod = isStatic || !isCallback && !isInStruct; if (convertedBody == null) { boolean forwardedToRaw = false; if (result.config.genRawBindings && !isCallback) { // Function rawMethod = nativeMethod.clone(); rawMethod.setArgs(Collections.EMPTY_LIST); fillIn(signatures, functionName, rawMethod, returnType, paramTypes, paramNames, varArgType, varArgName, isCallback, true); rawMethod.addModifiers(ModifierType.Protected, ModifierType.Native); if (generateStaticMethod) rawMethod.addModifiers(ModifierType.Static); if (!nativeMethod.computeSignature(SignatureType.ArgsAndRet).equals(rawMethod.computeSignature(SignatureType.ArgsAndRet))) { out.addDeclaration(rawMethod); List<Expression> followedArgs = new ArrayList<Expression>(); for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); Expression followedArg; switch (paramType.type) { case Pointer: followedArg = methodCall(expr(typeRef(org.bridj.Pointer.class)), "getPeer", varRef(paramName)); break; case Enum: followedArg = cast(typeRef(int.class), methodCall(varRef(paramName), "value")); break; // case NativeSize: // case NativeLong: // followedArg = methodCall(varRef(paramName), "longValue"); // break; default: followedArg = varRef(paramName); break; } followedArgs.add(followedArg); } if (varArgType != null) { followedArgs.add(varRef(varArgName)); } Expression followedCall = methodCall(rawMethod.getName().toString(), followedArgs.toArray(new Expression[followedArgs.size()])); boolean isVoid = "void".equals(String.valueOf(nativeMethod.getValueType())); if (isVoid) nativeMethod.setBody(block(stat(followedCall))); else { switch (returnType.type) { case Pointer: if (returnType.isTypedPointer) followedCall = new New(nativeMethod.getValueType(), followedCall); else { Expression ptrExpr = expr(typeRef(org.bridj.Pointer.class)); if (returnType.targetTypeConversion == null || returnType.targetTypeConversion.type == ConvType.Void) followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall); else followedCall = methodCall(ptrExpr, "pointerToAddress", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); } break; case Enum: followedCall = methodCall(expr(typeRef(org.bridj.FlagSet.class)), "fromValue", followedCall, result.typeConverter.typeLiteral(getSingleTypeParameter(nativeMethod.getValueType()))); break; case NativeLong: case NativeSize: if (!rawMethod.getValueType().toString().equals("long")) { followedCall = new New(nativeMethod.getValueType().clone(), followedCall); } default: break; } nativeMethod.setBody(block(new Statement.Return(followedCall))); } forwardedToRaw = true; } } if (!forwardedToRaw) nativeMethod.addModifiers(isCallback ? ModifierType.Abstract : ModifierType.Native); } else nativeMethod.setBody(convertedBody); nativeMethod.addModifiers( isProtected ? ModifierType.Protected : ModifierType.Public, generateStaticMethod ? ModifierType.Static : null ); } private void fillIn(Signatures signatures, Identifier functionName, Function nativeMethod, NL4JConversion returnType, List<NL4JConversion> paramTypes, List<String> paramNames, Identifier varArgType, String varArgName, boolean isCallback, boolean useRawTypes) { for (int i = 0, n = paramTypes.size(); i < n; i++) { NL4JConversion paramType = paramTypes.get(i); String paramName = paramNames.get(i); nativeMethod.addArg(paramType.annotateTypedType(new Arg(paramName, paramType.getTypeRef(useRawTypes)), useRawTypes));//.getTypedTypeRef()))); } if (varArgType != null) nativeMethod.addArg(new Arg(varArgName, typeRef(varArgType.clone()))).setVarArg(true); if (returnType != null) { returnType.annotateTypedType(nativeMethod, useRawTypes); nativeMethod.setValueType(returnType.getTypeRef(useRawTypes)); } String natSig = nativeMethod.computeSignature(SignatureType.JavaStyle); Identifier javaMethodName = signatures == null ? functionName : signatures.findNextMethodName(natSig, functionName); if (!javaMethodName.equals(functionName)) { nativeMethod.setName(javaMethodName); } if (!isCallback && !javaMethodName.equals(functionName)) annotateActualName(nativeMethod, functionName); } @Override public Struct convertStruct(Struct struct, Signatures signatures, Identifier callerLibraryClass, String callerLibrary, boolean onlyFields) throws IOException { Identifier structName = getActualTaggedTypeName(struct); if (structName == null) return null; //if (structName.toString().contains("MonoObject")) // structName.toString(); if (struct.isForwardDeclaration())// && !result.structsByName.get(structName).isForwardDeclaration()) return null; if (!signatures.addClass(structName)) return null; boolean isUnion = struct.getType() == Struct.Type.CUnion; boolean inheritsFromStruct = false; Identifier baseClass = null; int parentFieldsCount = 0; List<String> preComments = new ArrayList<String>(); for (SimpleTypeRef parentName : struct.getParents()) { Struct parent = result.structsByName.get(parentName.getName()); if (parent == null) { // TODO report error continue; } try { parentFieldsCount += countFieldsInStruct(parent); } catch (UnsupportedConversionException ex) { preComments.add("Error: " + ex); } baseClass = result.typeConverter.getTaggedTypeIdentifierInJava(parent); if (baseClass != null) { inheritsFromStruct = true; break; // TODO handle multiple and virtual inheritage } } boolean hasMemberFunctions = false; for (Declaration d : struct.getDeclarations()) { if (d instanceof Function) { hasMemberFunctions = true; break; } } Constant uuid = (Constant)struct.getModifierValue(ModifierType.UUID); if (baseClass == null) { switch (struct.getType()) { case CStruct: case CUnion: if (!hasMemberFunctions) { baseClass = ident(StructObject.class); break; } case CPPClass: baseClass = ident(uuid == null ? CPPObject.class : IUnknown.class); result.hasCPlusPlus = true; break; default: throw new UnsupportedOperationException(); } } Struct structJavaClass = publicStaticClass(structName, baseClass, Struct.Type.JavaClass, struct); //if (result.config.microsoftCOM) { if (uuid != null) { structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.IID), uuid)); } structJavaClass.addToCommentBefore(preComments); //System.out.println("parentFieldsCount(structName = " + structName + ") = " + parentFieldsCount); final int iChild[] = new int[] { parentFieldsCount }; //cl.addDeclaration(new EmptyDeclaration()) Signatures childSignatures = new Signatures(); /*if (isVirtual(struct) && !onlyFields) { String vptrName = DEFAULT_VPTR_NAME; VariablesDeclaration vptr = new VariablesDeclaration(typeRef(VirtualTablePointer.class), new Declarator.DirectDeclarator(vptrName)); vptr.addModifiers(ModifierType.Public); structJavaClass.addDeclaration(vptr); childSignatures.variablesSignatures.add(vptrName); // TODO add vptr grabber to constructor ! }*/ // private static StructIO<MyStruct> io = StructIO.getInstance(MyStruct.class); Function defaultConstructor = new Function(Type.JavaMethod, ident(structName), null).setBody(block(stat(methodCall("super")))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(defaultConstructor)) structJavaClass.addDeclaration(defaultConstructor); if (isUnion) structJavaClass.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Union))); int iVirtual = 0, iConstructor = 0; //List<Declaration> children = new ArrayList<Declaration>(); for (Declaration d : struct.getDeclarations()) { //if (isUnion) // iChild[0] = 0; if (d instanceof VariablesDeclaration) { convertVariablesDeclaration((VariablesDeclaration)d, childSignatures, structJavaClass, iChild, false, structName, callerLibraryClass, callerLibrary); } else if (!onlyFields) { if (d instanceof TaggedTypeRefDeclaration) { TaggedTypeRef tr = ((TaggedTypeRefDeclaration) d).getTaggedTypeRef(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof Enum) { convertEnum((Enum)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (d instanceof TypeDef) { TypeDef td = (TypeDef)d; TypeRef tr = td.getValueType(); if (tr instanceof Struct) { outputConvertedStruct((Struct)tr, childSignatures, structJavaClass, callerLibraryClass, callerLibrary, false); } else if (tr instanceof FunctionSignature) { convertCallback((FunctionSignature)tr, childSignatures, structJavaClass, callerLibraryClass); } } else if (result.config.genCPlusPlus && d instanceof Function) { Function f = (Function) d; boolean isVirtual = f.hasModifier(ModifierType.Virtual); boolean isConstructor = f.getName().equals(structName) && (f.getValueType() == null || f.getValueType().toString().equals("void")); if (isConstructor && f.getArgs().isEmpty()) continue; // default constructor was already generated String library = result.getLibrary(struct); if (library == null) continue; List<Declaration> decls = new ArrayList<Declaration>(); convertFunction(f, childSignatures, false, new ListWrapper(decls), callerLibraryClass, isConstructor ? iConstructor : -1); for (Declaration md : decls) { if (!(md instanceof Function)) continue; Function method = (Function) md; boolean commentOut = false; if (isVirtual) method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Virtual), expr(iVirtual))); else if (method.getValueType() == null) { method.addAnnotation(new Annotation(result.config.runtime.typeRef(JNAeratorConfig.Runtime.Ann.Constructor), expr(iConstructor))); isConstructor = true; } if (method.getName().toString().equals("operator")) commentOut = true; if (commentOut) structJavaClass.addDeclaration(new EmptyDeclaration(method.toString())); else structJavaClass.addDeclaration(method); } if (isVirtual) iVirtual++; if (isConstructor) iConstructor++; } } } String ptrName = "pointer"; Function castConstructor = new Function(Type.JavaMethod, ident(structName), null, new Arg(ptrName, typeRef(result.config.runtime.pointerClass))).setBody(block(stat(methodCall("super", varRef(ptrName))))).addModifiers(ModifierType.Public); if (childSignatures.addMethod(castConstructor)) structJavaClass.addDeclaration(castConstructor); return structJavaClass; }
diff --git a/src/main/java/uk/co/caprica/vlcj/player/MediaResourceLocator.java b/src/main/java/uk/co/caprica/vlcj/player/MediaResourceLocator.java index 5561a427..d8085e8a 100644 --- a/src/main/java/uk/co/caprica/vlcj/player/MediaResourceLocator.java +++ b/src/main/java/uk/co/caprica/vlcj/player/MediaResourceLocator.java @@ -1,132 +1,132 @@ /* * This file is part of VLCJ. * * VLCJ 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. * * VLCJ 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 VLCJ. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2009, 2010, 2011, 2012, 2013 Caprica Software Limited. */ package uk.co.caprica.vlcj.player; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.regex.Pattern; import uk.co.caprica.vlcj.logger.Logger; /** * Utility class to help detect the type of media resource locator. * <p> * This is needed since local files must be played differently to non-local MRLs * like streaming URLs or "screen://". * <p> * This is essentially an internal class. */ public final class MediaResourceLocator { /** * Simple pattern to detect locations. */ private static final Pattern MRL_LOCATION_PATTERN = Pattern.compile(".+://.*"); /** * Private constructor to prevent direct instantiation. */ private MediaResourceLocator() { } /** * Does the MRL represent a "location"? * * @param mrl media resource locator * @return <code>true</code> if the supplied MRL should be treated as a "location"; <code>false</code> for a file */ public static boolean isLocation(String mrl) { return MRL_LOCATION_PATTERN.matcher(mrl).matches(); } /** * Encode, if needed, a local file MRL that may contain Unicode characters as a file URL with * "percent" encoding. * <p> * This method deals only with the special case of an MRL for a local file name containing * Unicode characters. Such MRLs must be encoded as file URLs, by adding a "file://" prefix * before percent-encoding the filename. * <p> * Without this, vlc will not be able to play the file since it is using native API that can * not handle unencoded Unicode characters. * <p> * This method does not deal with any MRLs that are URLs since Unicode characters are forbidden * by specification for any URL. * <p> * What this means in practical terms is that if an MRL is specified that contains a "scheme" * like "http", or "file" then that MRL will <em>not</em> be encoded by this method, even if it * contains Unicode characters. This situation, if it arises, is considered a client * application vaildation failure. * * @param mrl MRL * @return the original MRL if no encoding is required, or a percent-encoded file URL */ public static String encodeMrl(String mrl) { Logger.debug("encodeMrl(mrl={})", mrl); // Assume no change needed String result = mrl; // If the supplied MRL contains any Unicode characters... if (containsUnicode(mrl)) { Logger.debug("MRL contains Unicode characters"); try { URI uri = new URI(mrl); Logger.debug("uri={}", uri); String scheme = uri.getScheme(); Logger.debug("scheme={}", uri.getScheme()); // If there is no URI scheme, then this is a local file... if (scheme == null) { Logger.debug("MRL has no scheme, assuming a local file name that should be encoded"); // Encode the local file as ASCII, and fix the scheme prefix result = new File(mrl).toURI().toASCIIString().replaceFirst("file:/", "file:///"); } else { Logger.debug("Ignoring MRL with scheme '{}'", scheme); } } catch(URISyntaxException e) { // Can't do anything, return the original string Logger.debug("Can not obtain a valid URI from the MRL"); } } else { - Logger.debug("MRL does contain any Unicode characters"); + Logger.debug("MRL does not contain any Unicode characters"); } Logger.debug("result={}", result); return result; } /** * Does a String contain any Unicode characters? * * @param value string to test * @return <code>true</code> if the supplied String contains any Unicode characters; <code>false</code> if it does not */ private static boolean containsUnicode(String value) { boolean result = false; for (int i = 0; i < value.length(); i++) { if (value.charAt(i) >= '\u0080') { result = true; break; } } return result; } }
true
true
public static String encodeMrl(String mrl) { Logger.debug("encodeMrl(mrl={})", mrl); // Assume no change needed String result = mrl; // If the supplied MRL contains any Unicode characters... if (containsUnicode(mrl)) { Logger.debug("MRL contains Unicode characters"); try { URI uri = new URI(mrl); Logger.debug("uri={}", uri); String scheme = uri.getScheme(); Logger.debug("scheme={}", uri.getScheme()); // If there is no URI scheme, then this is a local file... if (scheme == null) { Logger.debug("MRL has no scheme, assuming a local file name that should be encoded"); // Encode the local file as ASCII, and fix the scheme prefix result = new File(mrl).toURI().toASCIIString().replaceFirst("file:/", "file:///"); } else { Logger.debug("Ignoring MRL with scheme '{}'", scheme); } } catch(URISyntaxException e) { // Can't do anything, return the original string Logger.debug("Can not obtain a valid URI from the MRL"); } } else { Logger.debug("MRL does contain any Unicode characters"); } Logger.debug("result={}", result); return result; }
public static String encodeMrl(String mrl) { Logger.debug("encodeMrl(mrl={})", mrl); // Assume no change needed String result = mrl; // If the supplied MRL contains any Unicode characters... if (containsUnicode(mrl)) { Logger.debug("MRL contains Unicode characters"); try { URI uri = new URI(mrl); Logger.debug("uri={}", uri); String scheme = uri.getScheme(); Logger.debug("scheme={}", uri.getScheme()); // If there is no URI scheme, then this is a local file... if (scheme == null) { Logger.debug("MRL has no scheme, assuming a local file name that should be encoded"); // Encode the local file as ASCII, and fix the scheme prefix result = new File(mrl).toURI().toASCIIString().replaceFirst("file:/", "file:///"); } else { Logger.debug("Ignoring MRL with scheme '{}'", scheme); } } catch(URISyntaxException e) { // Can't do anything, return the original string Logger.debug("Can not obtain a valid URI from the MRL"); } } else { Logger.debug("MRL does not contain any Unicode characters"); } Logger.debug("result={}", result); return result; }
diff --git a/src/com/kill3rtaco/tacoserialization/PlayerStatsSerialization.java b/src/com/kill3rtaco/tacoserialization/PlayerStatsSerialization.java index 3316ee3..2f51872 100644 --- a/src/com/kill3rtaco/tacoserialization/PlayerStatsSerialization.java +++ b/src/com/kill3rtaco/tacoserialization/PlayerStatsSerialization.java @@ -1,156 +1,156 @@ package com.kill3rtaco.tacoserialization; import org.bukkit.GameMode; import org.bukkit.entity.Player; import org.json.JSONException; import org.json.JSONObject; /** * A class to help with the serialization of player stats, like exp level and health. * <br/><br/> * This serialization class supports optional serialization.<br/> * TacoSerialization will create a folder in your server plugins directory (wherever that may be) called * 'TacoSerialization'. Inside the folder will be a config.yml file. Various values can be turned off to * prevent some keys from being generated. * @author KILL3RTACO * */ public class PlayerStatsSerialization { protected PlayerStatsSerialization() {} /** * Serialize a player's stats * @param player The player whose stats to serialize * @return The serialized stats */ public static JSONObject serializePlayerStats(Player player){ try { JSONObject root = new JSONObject(); if(shouldSerialize("can-fly")) root.put("can-fly", player.getAllowFlight()); if(shouldSerialize("display-name")) root.put("display-name", player.getDisplayName()); if(shouldSerialize("exhaustion")) root.put("exhaustion", player.getExhaustion()); if(shouldSerialize("exp")) root.put("exp", player.getExp()); if(shouldSerialize("flying")) root.put("flying", player.isFlying()); if(shouldSerialize("food")) root.put("food", player.getFoodLevel()); if(shouldSerialize("gamemode")) root.put("gamemode", player.getGameMode().ordinal()); if(shouldSerialize("health")) root.put("health", player.getHealthScale()); if(shouldSerialize("level")) root.put("level", player.getLevel()); - if(shouldSerialize("ppotion-effects")) + if(shouldSerialize("potion-effects")) root.put("potion-effects", PotionEffectSerialization.serializeEffects(player.getActivePotionEffects())); if(shouldSerialize("saturation")) root.put("saturation", player.getSaturation()); return root; } catch (JSONException e) { e.printStackTrace(); return null; } } /** * Serialize a player's stats as a string * @param player The player whose stats to serialize * @return The serialization string */ public static String serializePlayerStatsAsString(Player player){ return serializePlayerStatsAsString(player, false); } /** * Serialize a player's stats as a string * @param player The player whose stats to serialize * @param pretty Whether the resulting string should be 'pretty' or not * @return The serialization string */ public static String serializePlayerStatsAsString(Player player, boolean pretty){ return serializePlayerStatsAsString(player, pretty, 5); } /** * Serialize a player's stats as a string * @param player The player whose stats to serialize * @param pretty Whether the resulting string should be 'pretty' or not * @param indentFactor The amount of spaces in a tab * @return The serialization string */ public static String serializePlayerStatsAsString(Player player, boolean pretty, int indentFactor){ try{ if(pretty){ return serializePlayerStats(player).toString(indentFactor); }else{ return serializePlayerStats(player).toString(); } } catch(JSONException e){ e.printStackTrace(); return null; } } /** * Apply stats to a player * @param player The player to affect * @param stats The stats to apply */ public static void applyPlayerStats(Player player, String stats){ try { applyPlayerStats(player, new JSONObject(stats)); } catch (JSONException e) { e.printStackTrace(); } } /** * Apply stats to a player * @param player The player to affect * @param stats The stats to apply */ public static void applyPlayerStats(Player player, JSONObject stats){ try { if(stats.has("can-fly")) player.setAllowFlight(stats.getBoolean("can-fly")); if(stats.has("display-name")) player.setDisplayName(stats.getString("display-name")); if(stats.has("exhaustion")) player.setExhaustion((float) stats.getDouble("exhaustion")); if(stats.has("exp")) player.setExp((float) stats.getDouble("exp")); if(stats.has("flying")) player.setFlying(stats.getBoolean("flying")); if(stats.has("food")) player.setFoodLevel(stats.getInt("food")); if(stats.has("health")) player.setHealth(stats.getDouble("health")); if(stats.has("gamemode")) player.setGameMode(GameMode.getByValue(stats.getInt("gamemode"))); if(stats.has("level")) player.setLevel(stats.getInt("level")); if(stats.has("potion-effects")) PotionEffectSerialization.setPotionEffects(stats.getString("potion-effects"), player); if(stats.has("saturation")) player.setSaturation((float) stats.getDouble("saturation")); } catch (JSONException e){ e.printStackTrace(); } } /** * Test if a certain key should be serialized * @param key The key to test * @return Whether the key should be serilaized or not */ public static boolean shouldSerialize(String key){ return SerializationConfig.getShouldSerialize("player-stats." + key); } }
true
true
public static JSONObject serializePlayerStats(Player player){ try { JSONObject root = new JSONObject(); if(shouldSerialize("can-fly")) root.put("can-fly", player.getAllowFlight()); if(shouldSerialize("display-name")) root.put("display-name", player.getDisplayName()); if(shouldSerialize("exhaustion")) root.put("exhaustion", player.getExhaustion()); if(shouldSerialize("exp")) root.put("exp", player.getExp()); if(shouldSerialize("flying")) root.put("flying", player.isFlying()); if(shouldSerialize("food")) root.put("food", player.getFoodLevel()); if(shouldSerialize("gamemode")) root.put("gamemode", player.getGameMode().ordinal()); if(shouldSerialize("health")) root.put("health", player.getHealthScale()); if(shouldSerialize("level")) root.put("level", player.getLevel()); if(shouldSerialize("ppotion-effects")) root.put("potion-effects", PotionEffectSerialization.serializeEffects(player.getActivePotionEffects())); if(shouldSerialize("saturation")) root.put("saturation", player.getSaturation()); return root; } catch (JSONException e) { e.printStackTrace(); return null; } }
public static JSONObject serializePlayerStats(Player player){ try { JSONObject root = new JSONObject(); if(shouldSerialize("can-fly")) root.put("can-fly", player.getAllowFlight()); if(shouldSerialize("display-name")) root.put("display-name", player.getDisplayName()); if(shouldSerialize("exhaustion")) root.put("exhaustion", player.getExhaustion()); if(shouldSerialize("exp")) root.put("exp", player.getExp()); if(shouldSerialize("flying")) root.put("flying", player.isFlying()); if(shouldSerialize("food")) root.put("food", player.getFoodLevel()); if(shouldSerialize("gamemode")) root.put("gamemode", player.getGameMode().ordinal()); if(shouldSerialize("health")) root.put("health", player.getHealthScale()); if(shouldSerialize("level")) root.put("level", player.getLevel()); if(shouldSerialize("potion-effects")) root.put("potion-effects", PotionEffectSerialization.serializeEffects(player.getActivePotionEffects())); if(shouldSerialize("saturation")) root.put("saturation", player.getSaturation()); return root; } catch (JSONException e) { e.printStackTrace(); return null; } }
diff --git a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java index e9aebac9a..5edd78136 100644 --- a/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java +++ b/plugins/org.eclipse.birt.report.data.adapter/src/org/eclipse/birt/report/data/adapter/impl/MetaDataPopulator.java @@ -1,394 +1,393 @@ /******************************************************************************* * Copyright (c) 2004, 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.data.adapter.impl; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IResultMetaData; import org.eclipse.birt.report.model.api.ColumnHintHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.JointDataSetHandle; import org.eclipse.birt.report.model.api.OdaDataSetHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.ScriptDataSetHandle; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.elements.structures.ResultSetColumn; /** * Retrieve metaData from resultset property. * */ public class MetaDataPopulator { private static final char RENAME_SEPARATOR = '_';//$NON-NLS-1$ private static final String UNNAME_PREFIX = "UNNAMED"; //$NON-NLS-1$ /** * populate all output columns in viewer display. The output columns is * retrieved from oda dataset handles's RESULT_SET_PROP and * COMPUTED_COLUMNS_PROP. * * @throws BirtException */ public static IResultMetaData retrieveResultMetaData( DataSetHandle dataSetHandle ) throws BirtException { List resultSetList = null; if ( dataSetHandle instanceof OdaDataSetHandle ) { resultSetList = (List) dataSetHandle.getProperty( OdaDataSetHandle.RESULT_SET_PROP ); } else { return null; } List computedList = (List) dataSetHandle.getProperty( OdaDataSetHandle.COMPUTED_COLUMNS_PROP ); List columnMeta = new ArrayList( ); ResultSetColumnDefinition columnDef; int count = 0; // populate result set columns if ( resultSetList != null ) { ResultSetColumn resultSetColumn; HashSet orgColumnNameSet = new HashSet( ); HashSet uniqueColumnNameSet = new HashSet( ); for ( int n = 0; n < resultSetList.size( ); n++ ) { orgColumnNameSet.add( ( (ResultSetColumn) resultSetList.get( n ) ).getColumnName( ) ); } for ( int i = 0; i < resultSetList.size( ); i++ ) { resultSetColumn = (ResultSetColumn) resultSetList.get( i ); String columnName = resultSetColumn.getColumnName( ); String uniqueColumnName = getUniqueName( orgColumnNameSet, uniqueColumnNameSet, columnName, i ); uniqueColumnNameSet.add( uniqueColumnName ); if ( !uniqueColumnName.equals( columnName ) ) { updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 ); } columnDef = new ResultSetColumnDefinition( uniqueColumnName ); columnDef.setDataTypeName( resultSetColumn.getDataType( ) ); columnDef.setDataType( ModelAdapter.adaptModelDataType( resultSetColumn.getDataType( ) ) ); if ( resultSetColumn.getPosition( ) != null ) columnDef.setColumnPosition( resultSetColumn.getPosition( ) .intValue( ) ); if ( resultSetColumn.getNativeDataType( ) != null ) columnDef.setNativeDataType( resultSetColumn.getNativeDataType( ) .intValue( ) ); if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null ) { ColumnHintHandle columnHint = findColumnHint( dataSetHandle, - resultSetColumn.getColumnName( ) ); + uniqueColumnName ); columnDef.setAlias( columnHint.getAlias( ) ); columnDef.setLableName( columnHint.getDisplayName( ) ); } columnDef.setComputedColumn( false ); columnMeta.add( columnDef ); } count += resultSetList.size( ); // populate computed columns if ( computedList != null ) { for ( int n = 0; n < computedList.size( ); n++ ) { orgColumnNameSet.add( ( (ComputedColumn) computedList.get( n ) ).getName( ) ); } ComputedColumn computedColumn; for ( int i = 0; i < computedList.size( ); i++ ) { computedColumn = (ComputedColumn) computedList.get( i ); String columnName = computedColumn.getName( ); String uniqueColumnName = getUniqueName( orgColumnNameSet, uniqueColumnNameSet, columnName, i + count ); uniqueColumnNameSet.add( uniqueColumnName ); if ( !uniqueColumnName.equals( columnName ) ) { updateComputedColumn( dataSetHandle, uniqueColumnName, columnName ); } columnDef = new ResultSetColumnDefinition( uniqueColumnName ); columnDef.setDataTypeName( computedColumn.getDataType( ) ); columnDef.setDataType( ModelAdapter.adaptModelDataType( computedColumn.getDataType( ) ) ); - if ( findColumnHint( dataSetHandle, - computedColumn.getName( ) ) != null ) + if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null ) { ColumnHintHandle columnHint = findColumnHint( dataSetHandle, uniqueColumnName ); columnDef.setAlias( columnHint.getAlias( ) ); columnDef.setLableName( columnHint.getDisplayName( ) ); } columnDef.setComputedColumn( true ); columnMeta.add( columnDef ); } } return new ResultMetaData2( columnMeta ); } return null; } /** * find column hint according to the columnName * * @param columnName * @return */ private static ColumnHintHandle findColumnHint( DataSetHandle dataSetHandle, String columnName ) { Iterator columnHintIter = dataSetHandle.columnHintsIterator( ); if ( columnHintIter != null ) { while ( columnHintIter.hasNext( ) ) { ColumnHintHandle modelColumnHint = (ColumnHintHandle) columnHintIter.next( ); if ( modelColumnHint.getColumnName( ).equals( columnName ) ) return modelColumnHint; } } return null; } /** * Whether need to use resultHint, which stands for resultSetHint, * columnHint or both * * @param dataSetHandle * @return * @throws BirtException */ public static boolean needsUseResultHint( DataSetHandle dataSetHandle, IResultMetaData metaData ) throws BirtException { boolean hasResultSetHint = false; boolean hasColumnHint = false; PropertyHandle handle = dataSetHandle.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP ); if ( handle != null ) hasColumnHint = handle.iterator( ).hasNext( ); hasResultSetHint = populateResultsetHint( dataSetHandle, metaData ); if ( !hasResultSetHint ) { hasResultSetHint = checkHandleType( dataSetHandle ); } return hasResultSetHint || hasColumnHint; } /** * * @param dataSetHandle * @param metaData * @param columnCount * @param hasResultSetHint * @return * @throws BirtException */ private static boolean populateResultsetHint( DataSetHandle dataSetHandle, IResultMetaData metaData ) throws BirtException { boolean hasResultSetHint = false; int columnCount = 0; HashSet orgColumnNameSet = new HashSet( ); HashSet uniqueColumnNameSet = new HashSet( ); if ( metaData != null ) { columnCount = metaData.getColumnCount( ); for ( int n = 0; n < columnCount; n++ ) { orgColumnNameSet.add( metaData.getColumnName( n + 1 ) ); } } for ( int i = 0; i < columnCount; i++ ) { String columnName = metaData.getColumnName( i + 1 ); String uniqueColumnName = getUniqueName( orgColumnNameSet, uniqueColumnNameSet, columnName, i ); uniqueColumnNameSet.add( uniqueColumnName ); if ( !uniqueColumnName.equals( columnName ) ) { updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 ); if ( hasResultSetHint != true ) hasResultSetHint = true; } } return hasResultSetHint; } /** * * @param orgColumnNameSet * @param newColumnNameSet * @param columnName * @param index * @return */ private static String getUniqueName( HashSet orgColumnNameSet, HashSet newColumnNameSet, String columnName, int index ) { String newColumnName; if ( columnName == null || columnName.trim( ).length( ) == 0 || newColumnNameSet.contains( columnName ) ) { // name conflict or no name,give this column a unique name if ( columnName == null || columnName.trim( ).length( ) == 0 ) newColumnName = UNNAME_PREFIX + RENAME_SEPARATOR + String.valueOf( index + 1 ); else newColumnName = columnName + RENAME_SEPARATOR + String.valueOf( index + 1 ); int i = 1; while ( orgColumnNameSet.contains( newColumnName ) || newColumnNameSet.contains( newColumnName ) ) { newColumnName += String.valueOf( RENAME_SEPARATOR ) + i; i++; } } else { newColumnName = columnName; } return newColumnName; } /** * whether need to use result hint * * @param dataSetHandle * @return */ private static boolean checkHandleType( DataSetHandle dataSetHandle ) { if ( dataSetHandle instanceof ScriptDataSetHandle ) return true; else if ( dataSetHandle instanceof JointDataSetHandle ) { List dataSets = ( (JointDataSetHandle) dataSetHandle ).getDataSetNames( ); for ( int i = 0; i < dataSets.size( ); i++ ) { DataSetHandle dsHandle = ( (JointDataSetHandle) dataSetHandle ).getModuleHandle( ) .findDataSet( dataSets.get( i ).toString( ) ); if ( dsHandle != null && dsHandle instanceof ScriptDataSetHandle ) { return true; } else if ( dsHandle instanceof JointDataSetHandle ) { if ( checkHandleType( dsHandle ) ) return true; } } } return false; } /** * * @param ds * @param uniqueColumnName * @param index * @throws BirtException */ private static void updateModelColumn( DataSetHandle ds, String uniqueColumnName, int index ) throws BirtException { PropertyHandle resultSetColumns = ds.getPropertyHandle( DataSetHandle.RESULT_SET_PROP ); if ( resultSetColumns == null ) return; // update result set columns Iterator iterator = resultSetColumns.iterator( ); while ( iterator.hasNext( ) ) { ResultSetColumnHandle rsColumnHandle = (ResultSetColumnHandle) iterator.next( ); assert rsColumnHandle.getPosition( ) != null; if ( rsColumnHandle.getPosition( ).intValue( ) == index ) { if ( rsColumnHandle.getColumnName( ) != null && !rsColumnHandle.getColumnName( ) .equals( uniqueColumnName ) ) { rsColumnHandle.setColumnName( uniqueColumnName ); } break; } } } /** * * @param ds * @param uniqueColumnName * @param index * @throws BirtException */ private static void updateComputedColumn( DataSetHandle ds, String uniqueColumnName, String originalName ) throws BirtException { PropertyHandle computedColumn = ds.getPropertyHandle( DataSetHandle.COMPUTED_COLUMNS_PROP ); if ( computedColumn == null ) return; // update result set columns Iterator iterator = computedColumn.iterator( ); while ( iterator.hasNext( ) ) { ComputedColumnHandle compColumnHandle = (ComputedColumnHandle) iterator.next( ); if ( compColumnHandle.getName( ) != null && compColumnHandle.getName( ).equals( originalName ) ) { compColumnHandle.setName( uniqueColumnName ); } } } }
false
true
public static IResultMetaData retrieveResultMetaData( DataSetHandle dataSetHandle ) throws BirtException { List resultSetList = null; if ( dataSetHandle instanceof OdaDataSetHandle ) { resultSetList = (List) dataSetHandle.getProperty( OdaDataSetHandle.RESULT_SET_PROP ); } else { return null; } List computedList = (List) dataSetHandle.getProperty( OdaDataSetHandle.COMPUTED_COLUMNS_PROP ); List columnMeta = new ArrayList( ); ResultSetColumnDefinition columnDef; int count = 0; // populate result set columns if ( resultSetList != null ) { ResultSetColumn resultSetColumn; HashSet orgColumnNameSet = new HashSet( ); HashSet uniqueColumnNameSet = new HashSet( ); for ( int n = 0; n < resultSetList.size( ); n++ ) { orgColumnNameSet.add( ( (ResultSetColumn) resultSetList.get( n ) ).getColumnName( ) ); } for ( int i = 0; i < resultSetList.size( ); i++ ) { resultSetColumn = (ResultSetColumn) resultSetList.get( i ); String columnName = resultSetColumn.getColumnName( ); String uniqueColumnName = getUniqueName( orgColumnNameSet, uniqueColumnNameSet, columnName, i ); uniqueColumnNameSet.add( uniqueColumnName ); if ( !uniqueColumnName.equals( columnName ) ) { updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 ); } columnDef = new ResultSetColumnDefinition( uniqueColumnName ); columnDef.setDataTypeName( resultSetColumn.getDataType( ) ); columnDef.setDataType( ModelAdapter.adaptModelDataType( resultSetColumn.getDataType( ) ) ); if ( resultSetColumn.getPosition( ) != null ) columnDef.setColumnPosition( resultSetColumn.getPosition( ) .intValue( ) ); if ( resultSetColumn.getNativeDataType( ) != null ) columnDef.setNativeDataType( resultSetColumn.getNativeDataType( ) .intValue( ) ); if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null ) { ColumnHintHandle columnHint = findColumnHint( dataSetHandle, resultSetColumn.getColumnName( ) ); columnDef.setAlias( columnHint.getAlias( ) ); columnDef.setLableName( columnHint.getDisplayName( ) ); } columnDef.setComputedColumn( false ); columnMeta.add( columnDef ); } count += resultSetList.size( ); // populate computed columns if ( computedList != null ) { for ( int n = 0; n < computedList.size( ); n++ ) { orgColumnNameSet.add( ( (ComputedColumn) computedList.get( n ) ).getName( ) ); } ComputedColumn computedColumn; for ( int i = 0; i < computedList.size( ); i++ ) { computedColumn = (ComputedColumn) computedList.get( i ); String columnName = computedColumn.getName( ); String uniqueColumnName = getUniqueName( orgColumnNameSet, uniqueColumnNameSet, columnName, i + count ); uniqueColumnNameSet.add( uniqueColumnName ); if ( !uniqueColumnName.equals( columnName ) ) { updateComputedColumn( dataSetHandle, uniqueColumnName, columnName ); } columnDef = new ResultSetColumnDefinition( uniqueColumnName ); columnDef.setDataTypeName( computedColumn.getDataType( ) ); columnDef.setDataType( ModelAdapter.adaptModelDataType( computedColumn.getDataType( ) ) ); if ( findColumnHint( dataSetHandle, computedColumn.getName( ) ) != null ) { ColumnHintHandle columnHint = findColumnHint( dataSetHandle, uniqueColumnName ); columnDef.setAlias( columnHint.getAlias( ) ); columnDef.setLableName( columnHint.getDisplayName( ) ); } columnDef.setComputedColumn( true ); columnMeta.add( columnDef ); } } return new ResultMetaData2( columnMeta ); } return null; }
public static IResultMetaData retrieveResultMetaData( DataSetHandle dataSetHandle ) throws BirtException { List resultSetList = null; if ( dataSetHandle instanceof OdaDataSetHandle ) { resultSetList = (List) dataSetHandle.getProperty( OdaDataSetHandle.RESULT_SET_PROP ); } else { return null; } List computedList = (List) dataSetHandle.getProperty( OdaDataSetHandle.COMPUTED_COLUMNS_PROP ); List columnMeta = new ArrayList( ); ResultSetColumnDefinition columnDef; int count = 0; // populate result set columns if ( resultSetList != null ) { ResultSetColumn resultSetColumn; HashSet orgColumnNameSet = new HashSet( ); HashSet uniqueColumnNameSet = new HashSet( ); for ( int n = 0; n < resultSetList.size( ); n++ ) { orgColumnNameSet.add( ( (ResultSetColumn) resultSetList.get( n ) ).getColumnName( ) ); } for ( int i = 0; i < resultSetList.size( ); i++ ) { resultSetColumn = (ResultSetColumn) resultSetList.get( i ); String columnName = resultSetColumn.getColumnName( ); String uniqueColumnName = getUniqueName( orgColumnNameSet, uniqueColumnNameSet, columnName, i ); uniqueColumnNameSet.add( uniqueColumnName ); if ( !uniqueColumnName.equals( columnName ) ) { updateModelColumn( dataSetHandle, uniqueColumnName, i + 1 ); } columnDef = new ResultSetColumnDefinition( uniqueColumnName ); columnDef.setDataTypeName( resultSetColumn.getDataType( ) ); columnDef.setDataType( ModelAdapter.adaptModelDataType( resultSetColumn.getDataType( ) ) ); if ( resultSetColumn.getPosition( ) != null ) columnDef.setColumnPosition( resultSetColumn.getPosition( ) .intValue( ) ); if ( resultSetColumn.getNativeDataType( ) != null ) columnDef.setNativeDataType( resultSetColumn.getNativeDataType( ) .intValue( ) ); if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null ) { ColumnHintHandle columnHint = findColumnHint( dataSetHandle, uniqueColumnName ); columnDef.setAlias( columnHint.getAlias( ) ); columnDef.setLableName( columnHint.getDisplayName( ) ); } columnDef.setComputedColumn( false ); columnMeta.add( columnDef ); } count += resultSetList.size( ); // populate computed columns if ( computedList != null ) { for ( int n = 0; n < computedList.size( ); n++ ) { orgColumnNameSet.add( ( (ComputedColumn) computedList.get( n ) ).getName( ) ); } ComputedColumn computedColumn; for ( int i = 0; i < computedList.size( ); i++ ) { computedColumn = (ComputedColumn) computedList.get( i ); String columnName = computedColumn.getName( ); String uniqueColumnName = getUniqueName( orgColumnNameSet, uniqueColumnNameSet, columnName, i + count ); uniqueColumnNameSet.add( uniqueColumnName ); if ( !uniqueColumnName.equals( columnName ) ) { updateComputedColumn( dataSetHandle, uniqueColumnName, columnName ); } columnDef = new ResultSetColumnDefinition( uniqueColumnName ); columnDef.setDataTypeName( computedColumn.getDataType( ) ); columnDef.setDataType( ModelAdapter.adaptModelDataType( computedColumn.getDataType( ) ) ); if ( findColumnHint( dataSetHandle, uniqueColumnName ) != null ) { ColumnHintHandle columnHint = findColumnHint( dataSetHandle, uniqueColumnName ); columnDef.setAlias( columnHint.getAlias( ) ); columnDef.setLableName( columnHint.getDisplayName( ) ); } columnDef.setComputedColumn( true ); columnMeta.add( columnDef ); } } return new ResultMetaData2( columnMeta ); } return null; }
diff --git a/Case/src/org/sleuthkit/autopsy/casemodule/AddImageVisualPanel4.java b/Case/src/org/sleuthkit/autopsy/casemodule/AddImageVisualPanel4.java index 87861b89f..6da6a216e 100644 --- a/Case/src/org/sleuthkit/autopsy/casemodule/AddImageVisualPanel4.java +++ b/Case/src/org/sleuthkit/autopsy/casemodule/AddImageVisualPanel4.java @@ -1,121 +1,121 @@ /* * Autopsy Forensic Browser * * Copyright 2011 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.casemodule; import javax.swing.JPanel; import org.openide.util.Lookup; /** * The "Add Image" wizard panel 3. This class is used to design the "form" of * the panel 3 for "Add Image" wizard panel. * * @author jantonius */ final class AddImageVisualPanel4 extends JPanel { /** Creates new form AddImageVisualPanel4 */ AddImageVisualPanel4() { initComponents(); } /** * Returns the name of the this panel. This name will be shown on the left * panel of the "Add Image" wizard panel. * * @return name the name of this panel */ @Override public String getName() { return "Finish"; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { addImgButton = new javax.swing.JButton(); crDbLabel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); org.openide.awt.Mnemonics.setLocalizedText(addImgButton, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.addImgButton.text")); // NOI18N addImgButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addImgButtonActionPerformed(evt); } }); crDbLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(crDbLabel, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.crDbLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.jLabel1.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.jLabel2.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(crDbLabel) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(addImgButton) .addComponent(jLabel2)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(crDbLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(addImgButton) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents /** * * * @param evt the action event */ private void addImgButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addImgButtonActionPerformed // restart the wizard AddImageAction act = Lookup.getDefault().lookup(AddImageAction.class); act.restart(); }//GEN-LAST:event_addImgButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addImgButton; private javax.swing.JLabel crDbLabel; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { addImgButton = new javax.swing.JButton(); crDbLabel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); org.openide.awt.Mnemonics.setLocalizedText(addImgButton, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.addImgButton.text")); // NOI18N addImgButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addImgButtonActionPerformed(evt); } }); crDbLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(crDbLabel, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.crDbLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.jLabel1.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.jLabel2.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(crDbLabel) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(addImgButton) .addComponent(jLabel2)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(crDbLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(addImgButton) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { addImgButton = new javax.swing.JButton(); crDbLabel = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); org.openide.awt.Mnemonics.setLocalizedText(addImgButton, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.addImgButton.text")); // NOI18N addImgButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addImgButtonActionPerformed(evt); } }); crDbLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(crDbLabel, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.crDbLabel.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.jLabel1.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(AddImageVisualPanel4.class, "AddImageVisualPanel4.jLabel2.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(crDbLabel) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(addImgButton) .addComponent(jLabel2)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(crDbLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(addImgButton) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java b/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java index 1a257cdc..9d288af9 100755 --- a/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java +++ b/src/main/java/de/cismet/cismap/commons/gui/MappingComponent.java @@ -1,5924 +1,5926 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cismap.commons.gui; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import edu.umd.cs.piccolo.PCamera; import edu.umd.cs.piccolo.PCanvas; import edu.umd.cs.piccolo.PLayer; import edu.umd.cs.piccolo.PNode; import edu.umd.cs.piccolo.PRoot; import edu.umd.cs.piccolo.event.PBasicInputEventHandler; import edu.umd.cs.piccolo.event.PInputEventListener; import edu.umd.cs.piccolo.nodes.PPath; import edu.umd.cs.piccolo.util.PBounds; import edu.umd.cs.piccolo.util.PPaintContext; import org.apache.log4j.Logger; import org.jdom.Attribute; import org.jdom.DataConversionException; import org.jdom.Element; import pswing.PSwingCanvas; import java.awt.Color; import java.awt.Cursor; import java.awt.EventQueue; import java.awt.Image; import java.awt.Paint; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JOptionPane; import javax.swing.SwingWorker; import javax.swing.Timer; import de.cismet.cismap.commons.BoundingBox; import de.cismet.cismap.commons.Crs; import de.cismet.cismap.commons.CrsTransformer; import de.cismet.cismap.commons.Debug; import de.cismet.cismap.commons.MappingModel; import de.cismet.cismap.commons.MappingModelListener; import de.cismet.cismap.commons.RetrievalServiceLayer; import de.cismet.cismap.commons.ServiceLayer; import de.cismet.cismap.commons.WorldToScreenTransform; import de.cismet.cismap.commons.XBoundingBox; import de.cismet.cismap.commons.features.Bufferable; import de.cismet.cismap.commons.features.DefaultFeatureCollection; import de.cismet.cismap.commons.features.Feature; import de.cismet.cismap.commons.features.FeatureCollection; import de.cismet.cismap.commons.features.FeatureCollectionEvent; import de.cismet.cismap.commons.features.FeatureCollectionListener; import de.cismet.cismap.commons.features.FeatureGroup; import de.cismet.cismap.commons.features.FeatureGroups; import de.cismet.cismap.commons.features.FeatureWithId; import de.cismet.cismap.commons.features.PureNewFeature; import de.cismet.cismap.commons.features.RasterLayerSupportedFeature; import de.cismet.cismap.commons.features.SearchFeature; import de.cismet.cismap.commons.features.StyledFeature; import de.cismet.cismap.commons.featureservice.DocumentFeatureService; import de.cismet.cismap.commons.featureservice.WebFeatureService; import de.cismet.cismap.commons.gui.layerwidget.ActiveLayerModel; import de.cismet.cismap.commons.gui.piccolo.FixedWidthStroke; import de.cismet.cismap.commons.gui.piccolo.PBoundsWithCleverToString; import de.cismet.cismap.commons.gui.piccolo.PFeature; import de.cismet.cismap.commons.gui.piccolo.PFeatureCoordinatePosition; import de.cismet.cismap.commons.gui.piccolo.PNodeFactory; import de.cismet.cismap.commons.gui.piccolo.PSticky; import de.cismet.cismap.commons.gui.piccolo.XPImage; import de.cismet.cismap.commons.gui.piccolo.eventlistener.AttachFeatureListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.CreateNewGeometryListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.CreateSearchGeometryListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.CustomFeatureActionListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.CustomFeatureInfoListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.DeleteFeatureListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.FeatureMoveListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.GetFeatureInfoClickDetectionListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.JoinPolygonsListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.KeyboardListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.MeasurementListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.MeasurementMoveListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.OverviewModeListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.PanAndMousewheelZoomListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.PrintingFrameListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.RaisePolygonListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.RubberBandZoomListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.SelectionListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.SimpleMoveListener; import de.cismet.cismap.commons.gui.piccolo.eventlistener.SplitPolygonListener; import de.cismet.cismap.commons.gui.printing.PrintingSettingsWidget; import de.cismet.cismap.commons.gui.printing.PrintingWidget; import de.cismet.cismap.commons.gui.printing.Scale; import de.cismet.cismap.commons.gui.progresswidgets.DocumentProgressWidget; import de.cismet.cismap.commons.gui.simplelayerwidget.LayerControl; import de.cismet.cismap.commons.gui.simplelayerwidget.NewSimpleInternalLayerWidget; import de.cismet.cismap.commons.interaction.CismapBroker; import de.cismet.cismap.commons.interaction.CrsChangeListener; import de.cismet.cismap.commons.interaction.events.CrsChangedEvent; import de.cismet.cismap.commons.interaction.events.MapDnDEvent; import de.cismet.cismap.commons.interaction.events.StatusEvent; import de.cismet.cismap.commons.interaction.memento.Memento; import de.cismet.cismap.commons.interaction.memento.MementoInterface; import de.cismet.cismap.commons.preferences.CismapPreferences; import de.cismet.cismap.commons.preferences.GlobalPreferences; import de.cismet.cismap.commons.preferences.LayersPreferences; import de.cismet.cismap.commons.rasterservice.FeatureAwareRasterService; import de.cismet.cismap.commons.rasterservice.MapService; import de.cismet.cismap.commons.rasterservice.RasterMapService; import de.cismet.cismap.commons.retrieval.AbstractRetrievalService; import de.cismet.cismap.commons.retrieval.RetrievalEvent; import de.cismet.cismap.commons.retrieval.RetrievalListener; import de.cismet.tools.CismetThreadPool; import de.cismet.tools.CurrentStackTrace; import de.cismet.tools.StaticDebuggingTools; import de.cismet.tools.collections.MultiMap; import de.cismet.tools.collections.TypeSafeCollections; import de.cismet.tools.configuration.Configurable; import de.cismet.tools.gui.historybutton.DefaultHistoryModel; import de.cismet.tools.gui.historybutton.HistoryModel; /** * DOCUMENT ME! * * @author [email protected] * @version $Revision$, $Date$ */ public class MappingComponent extends PSwingCanvas implements MappingModelListener, FeatureCollectionListener, HistoryModel, Configurable, DropTargetListener, CrsChangeListener { //~ Static fields/initializers --------------------------------------------- /** Wenn false, werden alle debug statements vom compiler wegoptimiert. */ private static final boolean DEBUG = Debug.DEBUG; public static final String PROPERTY_MAP_INTERACTION_MODE = "INTERACTION_MODE"; // NOI18N public static final String MOTION = "MOTION"; // NOI18N public static final String SELECT = "SELECT"; // NOI18N public static final String ZOOM = "ZOOM"; // NOI18N public static final String PAN = "PAN"; // NOI18N public static final String ALKIS_PRINT = "ALKIS_PRINT"; // NOI18N public static final String FEATURE_INFO = "FEATURE_INFO"; // NOI18N public static final String CREATE_SEARCH_POLYGON = "SEARCH_POLYGON"; // NOI18N public static final String MOVE_POLYGON = "MOVE_POLYGON"; // NOI18N public static final String REMOVE_POLYGON = "REMOVE_POLYGON"; // NOI18N public static final String NEW_POLYGON = "NEW_POLYGON"; // NOI18N public static final String SPLIT_POLYGON = "SPLIT_POLYGON"; // NOI18N public static final String JOIN_POLYGONS = "JOIN_POLYGONS"; // NOI18N public static final String RAISE_POLYGON = "RAISE_POLYGON"; // NOI18N public static final String ROTATE_POLYGON = "ROTATE_POLYGON"; // NOI18N public static final String ATTACH_POLYGON_TO_ALPHADATA = "ATTACH_POLYGON_TO_ALPHADATA"; // NOI18N public static final String MOVE_HANDLE = "MOVE_HANDLE"; // NOI18N public static final String REMOVE_HANDLE = "REMOVE_HANDLE"; // NOI18N public static final String ADD_HANDLE = "ADD_HANDLE"; // NOI18N public static final String MEASUREMENT = "MEASUREMENT"; // NOI18N public static final String LINEMEASUREMENT = "LINEMEASUREMENT"; // NOI18N public static final String PRINTING_AREA_SELECTION = "PRINTING_AREA_SELECTION"; // NOI18N public static final String CUSTOM_FEATUREACTION = "CUSTOM_FEATUREACTION"; // NOI18N public static final String CUSTOM_FEATUREINFO = "CUSTOM_FEATUREINFO"; // NOI18N public static final String OVERVIEW = "OVERVIEW"; // NOI18N private static MappingComponent THIS; /** Name of the internal Simple Layer Widget. */ public static final String LAYERWIDGET = "SimpleInternalLayerWidget"; // NOI18N /** Name of the internal Document Progress Widget. */ public static final String PROGRESSWIDGET = "DocumentProgressWidget"; // NOI18N /** Internat Widget at position north west. */ public static final int POSITION_NORTHWEST = 1; /** Internat Widget at position south west. */ public static final int POSITION_SOUTHWEST = 2; /** Internat Widget at position north east. */ public static final int POSITION_NORTHEAST = 4; /** Internat Widget at position south east. */ public static final int POSITION_SOUTHEAST = 8; /** Delay after a compoent resize event triggers a service reload request. */ private static final int RESIZE_DELAY = 500; /** If a document exceeds the criticalDocumentSize, the document progress widget is displayed. */ private static final long criticalDocumentSize = 10000000; // 10MB //~ Instance fields -------------------------------------------------------- // private // NewSimpleInternalLayerWidget // internalLayerWidget // = null;//new // NewSimpleInternalLayerWidget(this); // 10MB // private NewSimpleInternalLayerWidget internalLayerWidget = null;//new NewSimpleInternalLayerWidget(this); boolean featureServiceLayerVisible = true; final List<LayerControl> layerControls = new ArrayList<LayerControl>(); private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass()); private boolean gridEnabled = true; // private Feature[] currentlyShownFeatures = null; // private com.vividsolutions.jts.geom.Envelope currentFeatureEnvelope = null; private MappingModel mappingModel; private ConcurrentHashMap<Feature, PFeature> pFeatureHM = TypeSafeCollections.newConcurrentHashMap(); // private MultiMap pFeatureHMbyCoordinate = new MultiMap(); // Attribute die zum selektieren von PNodes gebraucht werden // private PFeature selectedFeature=null; // private Paint paint = null; private WorldToScreenTransform wtst = null; private double clip_offset_x; private double clip_offset_y; private double printingResolution = 0d; // double viewScale; // private PImage imageBackground = new XPImage(); // private SimpleWmsGetMapUrl wmsBackgroundUrl; private boolean backgroundEnabled = true; // private ConcurrentHashMap<String, PLayer> featureLayers = new ConcurrentHashMap<String, PLayer>(); private PLayer featureLayer = new PLayer(); private PLayer tmpFeatureLayer = new PLayer(); private PLayer mapServicelayer = new PLayer(); private PLayer featureServiceLayer = new PLayer(); private PLayer handleLayer = new PLayer(); private PLayer snapHandleLayer = new PLayer(); private PLayer rubberBandLayer = new PLayer(); private PLayer highlightingLayer = new PLayer(); private PLayer crosshairLayer = new PLayer(); private PLayer stickyLayer = new PLayer(); private PLayer printingFrameLayer = new PLayer(); private PLayer dragPerformanceImproverLayer = new PLayer(); private boolean readOnly = true; private boolean snappingEnabled = true; private boolean visualizeSnappingEnabled = true; private boolean visualizeSnappingRectEnabled = false; private int snappingRectSize = 20; private final Map<String, Cursor> cursors = TypeSafeCollections.newHashMap(); private final HashMap<String, PBasicInputEventHandler> inputEventListener = TypeSafeCollections.newHashMap(); // private Action backAction; // private Action forwardAction; // private Action homeAction; // private Action refreshAction; // private Action snappingAction; // private Action backgroundAction; private final Action zoomAction; // private Action panAction; // private Action selectAction; private int acceptableActions = DnDConstants.ACTION_COPY_OR_MOVE; // private DragSource dragSource; // private DragGestureListener dgListener; // private DragSourceListener dsListener; private FeatureCollection featureCollection; // private boolean internalLayerWidgetAvailable = false; private boolean infoNodesVisible = false; private boolean fixedMapExtent = false; private boolean fixedMapScale = false; private boolean inGlueIdenticalPointsMode = true; /** Holds value of property interactionMode. */ private String interactionMode; /** Holds value of property handleInteractionMode. */ private String handleInteractionMode; // "Phantom PCanvas" der nie selbst dargestellt wird // wird nur dazu benutzt das Graphics Objekt up to date // zu halten und dann als Hintergrund von z.B. einem // Panel zu fungieren // coooooooool, was ? ;-) private final PCanvas selectedObjectPresenter = new PCanvas(); private BoundingBox currentBoundingBox = null; // private HashMap rasterServiceImages = new HashMap(); private Rectangle2D newViewBounds; private int animationDuration = 500; private int taskCounter = 0; private CismapPreferences cismapPrefs; private DefaultHistoryModel historyModel = new DefaultHistoryModel(); // private Set<Feature> holdFeatures = new HashSet<Feature>(); // Scales private final List<Scale> scales = new ArrayList<Scale>(); // Printing private PrintingSettingsWidget printingSettingsDialog; private PrintingWidget printingDialog; // Scalebar private double screenResolution = 100.0; private volatile boolean locked = true; private final List<PNode> stickyPNodes = new ArrayList<PNode>(); // Undo- & Redo-Stacks private final MementoInterface memUndo = new Memento(); private final MementoInterface memRedo = new Memento(); private boolean featureDebugging = false; private BoundingBox fixedBoundingBox = null; // Object handleFeatureServiceBlocker = new Object(); private final List<MapListener> mapListeners = new ArrayList<MapListener>(); /** Contains the internal widgets. */ private final Map<String, JInternalFrame> internalWidgets = TypeSafeCollections.newHashMap(); /** Contains the positions of the internal widgets. */ private final Map<String, Integer> internalWidgetPositions = TypeSafeCollections.newHashMap(); /** The timer that delays the reload requests. */ private Timer delayedResizeEventTimer = null; private DocumentProgressListener documentProgressListener = null; private List<Crs> crsList = new ArrayList<Crs>(); private CrsTransformer transformer; private boolean resetCrs = false; private final Timer showHandleDelay; private final Map<MapService, Future<?>> serviceFuturesMap = TypeSafeCollections.newHashMap(); /** Utility field used by bound properties. */ private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); //~ Constructors ----------------------------------------------------------- /** * Creates a new instance of MappingComponent. */ public MappingComponent() { super(); locked = true; THIS = this; // wird in der Regel wieder ueberschrieben setSnappingRectSize(20); setSnappingEnabled(false); setVisualizeSnappingEnabled(false); setAnimationDuration(500); setInteractionMode(ZOOM); showHandleDelay = new Timer(500, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { showHandles(false); } }); showHandleDelay.setRepeats(false); featureDebugging = StaticDebuggingTools.checkHomeForFile("cismetTurnOnFeatureDebugging"); // NOI18N setFeatureCollection(new DefaultFeatureCollection()); addMapListener((DefaultFeatureCollection)getFeatureCollection()); final DropTarget dt = new DropTarget(this, acceptableActions, this); // setDefaultRenderQuality(PPaintContext.HIGH_QUALITY_RENDERING); // setAnimatingRenderQuality(PPaintContext.HIGH_QUALITY_RENDERING); setDefaultRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); setAnimatingRenderQuality(PPaintContext.LOW_QUALITY_RENDERING); removeInputEventListener(getPanEventHandler()); removeInputEventListener(getZoomEventHandler()); addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent evt) { if (MappingComponent.this.delayedResizeEventTimer == null) { delayedResizeEventTimer = new Timer(RESIZE_DELAY, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { delayedResizeEventTimer.stop(); delayedResizeEventTimer = null; // perform delayed resize: // rescape map + move widgets + reload services componentResizedDelayed(); } }); delayedResizeEventTimer.start(); } else { // perform intermediate resize: // rescape map + move widgets componentResizedIntermediate(); delayedResizeEventTimer.restart(); } } }); final PRoot root = getRoot(); final PCamera otherCamera = new PCamera(); otherCamera.addLayer(featureLayer); selectedObjectPresenter.setCamera(otherCamera); root.addChild(otherCamera); getLayer().addChild(mapServicelayer); getLayer().addChild(featureServiceLayer); getLayer().addChild(featureLayer); getLayer().addChild(tmpFeatureLayer); // getLayer().addChild(handleLayer); getLayer().addChild(rubberBandLayer); getLayer().addChild(highlightingLayer); getLayer().addChild(crosshairLayer); getLayer().addChild(dragPerformanceImproverLayer); getLayer().addChild(printingFrameLayer); getCamera().addLayer(mapServicelayer); // getCamera().addLayer(1, featureServiceLayer); getCamera().addLayer(featureLayer); getCamera().addLayer(tmpFeatureLayer); // getCamera().addLayer(5,snapHandleLayer); // getCamera().addLayer(5,handleLayer); getCamera().addLayer(rubberBandLayer); getCamera().addLayer(highlightingLayer); getCamera().addLayer(crosshairLayer); getCamera().addLayer(dragPerformanceImproverLayer); getCamera().addLayer(printingFrameLayer); getCamera().addChild(snapHandleLayer); getCamera().addChild(handleLayer); getCamera().addChild(stickyLayer); handleLayer.moveToFront(); otherCamera.setTransparency(0.05f); initInputListener(); initCursors(); addInputEventListener(getInputListener(MOTION)); addInputEventListener(getInputListener(CUSTOM_FEATUREACTION)); final KeyboardListener k = new KeyboardListener(this); addInputEventListener(k); getRoot().getDefaultInputManager().setKeyboardFocus(k); setInteractionMode(ZOOM); setHandleInteractionMode(MOVE_HANDLE); dragPerformanceImproverLayer.setVisible(false); historyModel.setMaximumPossibilities(30); zoomAction = new AbstractAction() { { putValue( Action.NAME, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.zoomAction.NAME")); // NOI18N putValue( Action.SMALL_ICON, new ImageIcon(getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/layers.png"))); // NOI18N putValue( Action.SHORT_DESCRIPTION, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.zoomAction.SHORT_DESCRIPTION")); // NOI18N putValue( Action.LONG_DESCRIPTION, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.zoomAction.LONG_DESCRIPTION")); // NOI18N putValue(Action.MNEMONIC_KEY, Integer.valueOf('Z')); // NOI18N putValue(Action.ACTION_COMMAND_KEY, "zoom.action"); // NOI18N } @Override public void actionPerformed(final ActionEvent event) { zoomAction.putValue( Action.SMALL_ICON, new ImageIcon(getClass().getResource("/de/cismet/cismap/commons/raster/wms/res/server.png"))); // NOI18N setInteractionMode(MappingComponent.ZOOM); } }; this.getCamera().addPropertyChangeListener(PCamera.PROPERTY_VIEW_TRANSFORM, new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { // if(DEBUG)log.debug("getCamera().getViewTransform():"+getCamera().getViewTransform()); // if(DEBUG)log.debug("getCamera().getViewTransform().getScaleY():"+getCamera().getViewTransform().getScaleY()); // double[] matrix=new double[9]; // getCamera().getViewTransform().getMatrix(matrix); // boolean nan=false; // for (double d:matrix) { // if (d==Double.NaN) { // nan=true; // break; // } // } // if (nan) { // log.warn("getCamera().getViewTransform() has at least one NaN"); // getCamera().getViewTransformReference().setToIdentity(); // // } // if (getCamera().getViewTransform().getScaleY()<=0) { // log.warn("getCamera().getViewTransform().getScaleY()<=0"); // } checkAndFixErroneousTransformation(); handleLayer.removeAllChildren(); showHandleDelay.restart(); rescaleStickyNodes(); // log.fatal(evt.getPropertyName()+" "+evt.getOldValue()+" "+evt.getNewValue()); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.SCALE, interactionMode)); } }); CismapBroker.getInstance().addCrsChangeListener(this); } //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @param mapListener DOCUMENT ME! */ public void addMapListener(final MapListener mapListener) { if (mapListener != null) { mapListeners.add(mapListener); } } /** * DOCUMENT ME! * * @param mapListener DOCUMENT ME! */ public void removeMapListener(final MapListener mapListener) { if (mapListener != null) { mapListeners.remove(mapListener); } } /** * DOCUMENT ME! */ public void dispose() { CismapBroker.getInstance().removeCrsChangeListener(this); getFeatureCollection().removeAllFeatures(); } /** * DOCUMENT ME! * * @return true, if debug-messages are logged. */ public boolean isFeatureDebugging() { return featureDebugging; } /** * Creates printingDialog and printingSettingsDialog. */ public void initPrintingDialogs() { printingSettingsDialog = new PrintingSettingsWidget(true, this); printingDialog = new PrintingWidget(true, this); } /** * Returns the momentary image of the PCamera of this MappingComponent. * * @return Image */ public Image getImage() { // this.getCamera().print(); return this.getCamera().toImage(this.getWidth(), this.getHeight(), Color.white); } /** * Creates an image with given width and height from all features in the given featurecollection. The image will be * used for printing. * * @param fc FeatureCollection * @param width desired width of the resulting image * @param height desired height of the resulting image * * @return Image of the featurecollection */ public Image getImageOfFeatures(final Collection<Feature> fc, final int width, final int height) { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getImageOffFeatures (" + width + "x" + height + ")"); // NOI18N } } final PrintingFrameListener pfl = ((PrintingFrameListener)getInputListener(PRINTING_AREA_SELECTION)); final PCanvas pc = new PCanvas(); // c.addLayer(featureLayer); pc.setSize(width, height); final List<PFeature> list = new ArrayList<PFeature>(); final Iterator it = fc.iterator(); while (it.hasNext()) { final Feature f = (Feature)it.next(); final PFeature p = new PFeature(f, wtst, clip_offset_x, clip_offset_y, MappingComponent.this); if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) { list.add(p); } } pc.getCamera().animateViewToCenterBounds(pfl.getPrintingRectangle().getBounds(), true, 0); final double scale = 1 / pc.getCamera().getViewScale(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("subPCscale:" + scale); // NOI18N } } // TODO Sorge dafür dass die PSwingKomponente richtig gedruckt wird und dass die Karte nicht mehr "zittert" int printingLineWidth = -1; for (final PNode p : list) { if (p instanceof PFeature) { final PFeature original = ((PFeature)p); original.setInfoNodeExpanded(false); if (printingLineWidth > 0) { ((StyledFeature)original.getFeature()).setLineWidth(printingLineWidth); } else if (StyledFeature.class.isAssignableFrom(original.getFeature().getClass())) { final int orginalLineWidth = ((StyledFeature)original.getFeature()).getLineWidth(); printingLineWidth = (int)Math.round(orginalLineWidth * (getPrintingResolution() * 2)); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getImageOfFeatures: changed printingLineWidth from " + orginalLineWidth + " to " + printingLineWidth + " (resolution=" + getPrintingResolution() + ")"); // NOI18N } } ((StyledFeature)original.getFeature()).setLineWidth(printingLineWidth); } final PFeature copy = new PFeature(original.getFeature(), getWtst(), 0, 0, MappingComponent.this, true); pc.getLayer().addChild(copy); copy.setTransparency(original.getTransparency()); copy.setStrokePaint(original.getStrokePaint()); final boolean expanded = original.isInfoNodeExpanded(); copy.addInfoNode(); copy.setInfoNodeExpanded(false); // original.setInfoNodeExpanded(true); copy.refreshInfoNode(); // Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new ImageSelection(original.toImage()), null); original.refreshInfoNode(); removeStickyNode(copy.getStickyChild()); // Wenn mal irgendwas wegen Querformat kommt : // pf.getStickyChild().setRotation(0.5); final PNode stickyChild = copy.getStickyChild(); if (stickyChild != null) { stickyChild.setScale(scale * getPrintingResolution()); if (copy.hasSecondStickyChild()) { copy.getSecondStickyChild().setScale(scale * getPrintingResolution()); } } } } final Image ret = pc.getCamera().toImage(width, height, new Color(255, 255, 255, 0)); if (DEBUG) { if (log.isDebugEnabled()) { log.debug(ret); } } return ret; } catch (Exception exception) { log.error("Error during the creation of an image from features", exception); // NOI18N return null; } } /** * Creates an image with given width and height from all features that intersects the printingframe. * * @param width desired width of the resulting image * @param height desired height of the resulting image * * @return Image of intersecting features */ public Image getFeatureImage(final int width, final int height) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getFeatureImage " + width + "x" + height); // NOI18N } } final PrintingFrameListener pfl = ((PrintingFrameListener)getInputListener(PRINTING_AREA_SELECTION)); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("printing rectangle bounds: " + pfl.getPrintingRectangle().getBounds()); // NOI18N } } final PCanvas pc = new PCanvas(); // c.addLayer(featureLayer); pc.setSize(width, height); final List<PNode> list = new ArrayList<PNode>(); final Iterator it = featureLayer.getChildrenIterator(); while (it.hasNext()) { final PNode p = (PNode)it.next(); if (p.getFullBounds().intersects(pfl.getPrintingRectangle().getBounds())) { list.add(p); } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("intersecting feature count: " + list.size()); // NOI18N } } pc.getCamera().animateViewToCenterBounds(pfl.getPrintingRectangle().getBounds(), true, 0); final double scale = 1 / pc.getCamera().getViewScale(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("subPCscale:" + scale); // NOI18N } } // TODO Sorge dafür dass die PSwingKomponente richtig gedruckt wird und dass die Karte nicht mehr "zittert" for (final PNode p : list) { if (p instanceof PFeature) { final PFeature original = ((PFeature)p); try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { try { original.setInfoNodeExpanded(false); final PFeature copy = new PFeature( original.getFeature(), getWtst(), 0, 0, MappingComponent.this, true); pc.getLayer().addChild(copy); copy.setTransparency(original.getTransparency()); copy.setStrokePaint(original.getStrokePaint()); copy.addInfoNode(); copy.setInfoNodeExpanded(false); // original.refreshInfoNode(); // Wenn mal irgendwas wegen Querformat kommt : // pf.getStickyChild().setRotation(0.5); if (copy.getStickyChild() != null) { copy.getStickyChild().setScale(scale * getPrintingResolution()); } } catch (Throwable t) { log.error("Fehler beim erstellen des Featureabbildes", t); // NOI18N } } }); } catch (Throwable t) { log.fatal("Fehler beim erstellen des Featureabbildes", t); // NOI18N return null; } // Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new ImageSelection(original.toImage()), // null); // if(DEBUG)log.debug("StcikyChild:"+pf.getStickyChild().); } } return pc.getCamera().toImage(width, height, new Color(255, 255, 255, 0)); } /** * Adds the given PCamera to the PRoot of this MappingComponent. * * @param cam PCamera-object */ public void addToPRoot(final PCamera cam) { getRoot().addChild(cam); } /** * Adds a PNode to the StickyNode-vector. * * @param pn PNode-object */ public void addStickyNode(final PNode pn) { // if(DEBUG)log.debug("addStickyNode:" + pn); stickyPNodes.add(pn); } /** * Removes a specific PNode from the StickyNode-vector. * * @param pn PNode that should be removed */ public void removeStickyNode(final PNode pn) { stickyPNodes.remove(pn); } /** * DOCUMENT ME! * * @return Vector<PNode> with all sticky PNodes */ public List<PNode> getStickyNodes() { return stickyPNodes; } /** * Calls private method rescaleStickyNodeWork(node) to rescale the sticky PNode. Forces the execution to the EDT. * * @param n PNode to rescale */ public void rescaleStickyNode(final PNode n) { if (!EventQueue.isDispatchThread()) { EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodeWork(n); } }); } else { rescaleStickyNodeWork(n); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ private double getPrintingResolution() { return this.printingResolution; } /** * DOCUMENT ME! * * @param printingResolution DOCUMENT ME! */ public void setPrintingResolution(final double printingResolution) { this.printingResolution = printingResolution; } /** * Sets the scale of the given PNode to the value of the camera scale. * * @param n PNode to rescale */ private void rescaleStickyNodeWork(final PNode n) { final double s = MappingComponent.this.getCamera().getViewScale(); n.setScale(1 / s); } /** * Rescales all nodes inside the StickyNode-vector. */ public void rescaleStickyNodes() { final List<PNode> stickyNodeCopy = new ArrayList<PNode>(getStickyNodes()); for (final PNode each : stickyNodeCopy) { if ((each instanceof PSticky) && each.getVisible()) { rescaleStickyNode(each); } else { if ((each instanceof PSticky) && (each.getParent() == null)) { removeStickyNode(each); } } } } /** * Returns the custom created Action zoomAction. * * @return Action-object */ public Action getZoomAction() { return zoomAction; } /** * Pans to the given bounds without creating a historyaction to undo the action. * * @param bounds new bounds of the camera */ public void gotoBoundsWithoutHistory(PBounds bounds) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("gotoBoundsWithoutHistory(PBounds: " + bounds, new CurrentStackTrace()); // NOI18N } } try { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("error during removeAllCHildren", e); // NOI18N } if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } if (bounds instanceof PBoundsWithCleverToString) { final PBoundsWithCleverToString boundWCTS = (PBoundsWithCleverToString)bounds; if (!boundWCTS.getCrsCode().equals(CismapBroker.getInstance().getSrs().getCode())) { try { final Rectangle2D pos = new Rectangle2D.Double(); XBoundingBox bbox = boundWCTS.getWorldCoordinates(); final CrsTransformer trans = new CrsTransformer(CismapBroker.getInstance().getSrs().getCode()); bbox = trans.transformBoundingBox(bbox); bounds = bbox.getPBounds(getWtst()); } catch (Exception e) { log.error("Cannot transform the bounding box from " + boundWCTS.getCrsCode() + " to " + CismapBroker.getInstance().getSrs().getCode()); } } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("before animateView"); // NOI18N } } getCamera().animateViewToCenterBounds(((PBounds)bounds), true, animationDuration); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("after animateView"); // NOI18N } } queryServicesWithoutHistory(); showHandles(true); } catch (NullPointerException npe) { log.warn("NPE in gotoBoundsWithoutHistory(" + bounds + ")", npe); // NOI18N } } /** * Checks out the y-camerascales for negative value and fixes it by negating both x- and y-scales. */ private void checkAndFixErroneousTransformation() { if (getCamera().getViewTransform().getScaleY() < 0) { final double y = getCamera().getViewTransform().getScaleY(); final double x = getCamera().getViewTransform().getScaleX(); log.warn("Erroneous ViewTransform: getViewTransform (scaleY=" + y + " scaleX=" + x + "). Try to fix it."); // NOI18N getCamera().getViewTransformReference() .setToScale(getCamera().getViewTransform().getScaleX() * (-1), y * (-1)); } } /** * Re-adds the default layers in a given order. */ private void adjustLayers() { // getCamera().removeAllChildren(); int counter = 0; getCamera().addLayer(counter++, mapServicelayer); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { getCamera().addLayer(counter++, (PLayer)featureServiceLayer.getChild(i)); } getCamera().addLayer(counter++, featureLayer); getCamera().addLayer(counter++, tmpFeatureLayer); // getCamera().addLayer(counter++,snapHandleLayer); // getCamera().addLayer(counter++,handleLayer); getCamera().addLayer(counter++, rubberBandLayer); getCamera().addLayer(counter++, dragPerformanceImproverLayer); getCamera().addLayer(counter++, printingFrameLayer); } /** * Assigns the listeners to the according interactionmodes. */ public void initInputListener() { inputEventListener.put(MOTION, new SimpleMoveListener(this)); inputEventListener.put(CUSTOM_FEATUREACTION, new CustomFeatureActionListener(this)); inputEventListener.put(ZOOM, new RubberBandZoomListener()); inputEventListener.put(PAN, new PanAndMousewheelZoomListener()); // inputEventListener.put(PAN, new BackgroundRefreshingPanEventListener()); inputEventListener.put(SELECT, new SelectionListener()); inputEventListener.put(FEATURE_INFO, new GetFeatureInfoClickDetectionListener()); inputEventListener.put(CREATE_SEARCH_POLYGON, new CreateSearchGeometryListener(this)); inputEventListener.put(MOVE_POLYGON, new FeatureMoveListener(this)); inputEventListener.put(NEW_POLYGON, new CreateNewGeometryListener(this)); inputEventListener.put(RAISE_POLYGON, new RaisePolygonListener(this)); inputEventListener.put(REMOVE_POLYGON, new DeleteFeatureListener()); inputEventListener.put(ATTACH_POLYGON_TO_ALPHADATA, new AttachFeatureListener()); inputEventListener.put(JOIN_POLYGONS, new JoinPolygonsListener()); inputEventListener.put(SPLIT_POLYGON, new SplitPolygonListener(this)); inputEventListener.put(LINEMEASUREMENT, new MeasurementMoveListener(this)); inputEventListener.put(MEASUREMENT, new MeasurementListener(this)); inputEventListener.put(PRINTING_AREA_SELECTION, new PrintingFrameListener(this)); inputEventListener.put(CUSTOM_FEATUREINFO, new CustomFeatureInfoListener()); inputEventListener.put(OVERVIEW, new OverviewModeListener()); } /** * Assigns a custom interactionmode with an own PBasicInputEventHandler. * * @param key interactionmode as String * @param listener new PBasicInputEventHandler */ public void addCustomInputListener(final String key, final PBasicInputEventHandler listener) { inputEventListener.put(key, listener); } /** * Assigns the cursors to the according interactionmodes. */ public void initCursors() { putCursor(SELECT, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(ZOOM, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(PAN, new Cursor(Cursor.HAND_CURSOR)); putCursor(FEATURE_INFO, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(CREATE_SEARCH_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(MOVE_POLYGON, new Cursor(Cursor.HAND_CURSOR)); putCursor(ROTATE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(NEW_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(RAISE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(REMOVE_POLYGON, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(ATTACH_POLYGON_TO_ALPHADATA, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(JOIN_POLYGONS, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(SPLIT_POLYGON, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(MEASUREMENT, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(LINEMEASUREMENT, new Cursor(Cursor.DEFAULT_CURSOR)); putCursor(MOVE_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(REMOVE_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR)); putCursor(ADD_HANDLE, new Cursor(Cursor.CROSSHAIR_CURSOR)); } /** * Shows the printingsetting-dialog that resets the interactionmode after printing. * * @param oldInteractionMode String-object */ public void showPrintingSettingsDialog(final String oldInteractionMode) { if (!(printingSettingsDialog.getParent() instanceof JFrame)) { printingSettingsDialog = printingSettingsDialog.cloneWithNewParent(true, this); } printingSettingsDialog.setInteractionModeAfterPrinting(oldInteractionMode); printingSettingsDialog.setLocationRelativeTo(this); printingSettingsDialog.setVisible(true); } /** * Shows the printing-dialog that resets the interactionmode after printing. * * @param oldInteractionMode String-object */ public void showPrintingDialog(final String oldInteractionMode) { setPointerAnnotationVisibility(false); if (!(printingDialog.getParent() instanceof JFrame)) { printingDialog = printingDialog.cloneWithNewParent(true, this); } try { printingDialog.setInteractionModeAfterPrinting(oldInteractionMode); printingDialog.startLoading(); printingDialog.setLocationRelativeTo(this); printingDialog.setVisible(true); } catch (Exception e) { log.error("Fehler beim Anzeigen des Printing Dialogs", e); // NOI18N } } /** * Getter for property interactionMode. * * @return Value of property interactionMode. */ public String getInteractionMode() { return this.interactionMode; } /** * Changes the interactionmode. * * @param interactionMode new interactionmode as String */ public void setInteractionMode(final String interactionMode) { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:" + this.interactionMode + "", new Exception()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } setPointerAnnotationVisibility(false); if (getPrintingFrameLayer().getChildrenCount() > 1) { getPrintingFrameLayer().removeAllChildren(); } if (this.interactionMode != null) { if (interactionMode.equals(FEATURE_INFO)) { ((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo() .setVisible(true); } else { ((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo() .setVisible(false); } if (isReadOnly()) { ((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class); } final PInputEventListener pivl = this.getInputListener(this.interactionMode); if (pivl != null) { removeInputEventListener(pivl); } else { log.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N } if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) { // if (selectedFeature!=null) { // selectPFeatureManually(null); // } featureCollection.unselectAll(); } if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEMEASUREMENT) || interactionMode.equals(SPLIT_POLYGON)) && (this.readOnly == false)) { // if (selectedFeature!=null) { // selectPFeatureManually(selectedFeature); // } featureSelectionChanged(null); } if (interactionMode.equals(JOIN_POLYGONS)) { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent( this, PROPERTY_MAP_INTERACTION_MODE, this.interactionMode, interactionMode); this.interactionMode = interactionMode; final PInputEventListener pivl = getInputListener(interactionMode); if (pivl != null) { addInputEventListener(pivl); propertyChangeSupport.firePropertyChange(interactionModeChangedEvent); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode)); } else { log.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N } } catch (Exception e) { log.error("Fehler beim Ändern des InteractionModes", e); // NOI18N } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Deprecated public void formComponentResized(final ComponentEvent evt) { this.componentResizedDelayed(); } /** * Resizes the map and does not reload all services. * * @see #componentResizedDelayed() */ public void componentResizedIntermediate() { if (!this.isLocked()) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N } } if (MappingComponent.this.currentBoundingBox == null) { log.error("currentBoundingBox is null"); // NOI18N currentBoundingBox = getCurrentBoundingBox(); } // rescale map if (historyModel.getCurrentElement() != null) { final PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } getCamera().animateViewToCenterBounds(bounds, true, animationDuration); } } } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } /** * Resizes the map and reloads all services. * * @see #componentResizedIntermediate() */ public void componentResizedDelayed() { if (!this.isLocked()) { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N } } if (MappingComponent.this.currentBoundingBox == null) { log.error("currentBoundingBox is null"); // NOI18N currentBoundingBox = getCurrentBoundingBox(); } gotoBoundsWithoutHistory((PBounds)historyModel.getCurrentElement()); // } // if (getCurrentElement()!=null) { // gotoBoundsWithoutHistory((PBounds)(getCurrentElement())); // } else { // if(DEBUG)log.debug("getCurrentElement()==null) "); // } // for (JComponent internalWiget : this.internalWidgets.values()) // { // if (internalWiget.isVisible()) // { // internalWiget.setVisible(false); // } // } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } // if (internalLayerWidget != null && internalLayerWidget.isVisible()) // { // internalLayerWidget.setVisible(false); // } } } } catch (Throwable t) { log.error("Fehler in formComponentResized()", t); // NOI18N } } } /** * syncSelectedObjectPresenter(int i). * * @param i DOCUMENT ME! */ public void syncSelectedObjectPresenter(final int i) { selectedObjectPresenter.setVisible(true); if (featureCollection.getSelectedFeatures().size() > 0) { if (featureCollection.getSelectedFeatures().size() == 1) { final PFeature selectedFeature = (PFeature)pFeatureHM.get( featureCollection.getSelectedFeatures().toArray()[0]); if (selectedFeature != null) { selectedObjectPresenter.getCamera() .animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2); } } else { // todo } } else { log.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N } } // public void selectPFeatureManually(PFeature feature) { // if (feature==null) { // handleLayer.removeAllChildren(); // if (selectedFeature!=null) { // selectedFeature.setSelected(false); // } // } else { // if (selectedFeature!=null) { // selectedFeature.setSelected(false); // } // feature.setSelected(true); // selectedFeature=feature; // // // //Fuer den selectedObjectPresenter (Eigener PCanvas) // syncSelectedObjectPresenter(1000); // // handleLayer.removeAllChildren(); // if ( this.isReadOnly()==false // &&( // getInteractionMode().equals(SELECT) // || // getInteractionMode().equals(PAN) // || // getInteractionMode().equals(ZOOM) // || // getInteractionMode().equals(SPLIT_POLYGON) // ) // ) { // selectedFeature.addHandles(handleLayer); // } else { // handleLayer.removeAllChildren(); // } // } // // } // public void selectionChanged(de.cismet.cismap.commons.MappingModelEvent mme) { // Feature f=mme.getFeature(); // if (f==null) { // selectPFeatureManually(null); // } else { // PFeature fp=((PFeature)pFeatureHM.get(f)); // if (fp!=null&&fp.getFeature()!=null&&fp.getFeature().getGeometry()!=null) { //// PNode p=fp.getChild(0); // selectPFeatureManually(fp); // } else { // selectPFeatureManually(null); // } // } // } /** * Returns the current featureCollection. * * @return DOCUMENT ME! */ public FeatureCollection getFeatureCollection() { return featureCollection; } /** * Replaces the old featureCollection with a new one. * * @param featureCollection the new featureCollection */ public void setFeatureCollection(final FeatureCollection featureCollection) { this.featureCollection = featureCollection; featureCollection.addFeatureCollectionListener(this); } /** * DOCUMENT ME! * * @param visibility DOCUMENT ME! */ public void setFeatureCollectionVisibility(final boolean visibility) { featureLayer.setVisible(visibility); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFeatureCollectionVisible() { return featureLayer.getVisible(); } /** * Adds a new mapservice at a specific place of the layercontrols. * * @param mapService the new mapservice * @param position the index where to position the mapservice */ public void addMapService(final MapService mapService, final int position) { try { PNode p = new PNode(); if (mapService instanceof RasterMapService) { log.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N if (mapService.getPNode() instanceof XPImage) { p = (XPImage)mapService.getPNode(); } else { p = new XPImage(); mapService.setPNode(p); } mapService.addRetrievalListener(new MappingComponentRasterServiceListener( position, p, (ServiceLayer)mapService)); } else { log.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName() + ")"); // NOI18N p = new PLayer(); mapService.setPNode(p); if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): isDocumentFeatureService, checking document size"); // NOI18N } } final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService; if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) { log.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '" + documentFeatureService.getName() + "' size of " + (documentFeatureService.getDocumentSize() / 1000000) + "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000) + "MB)"); // NOI18N if (this.documentProgressListener == null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): lazy instantiation of documentProgressListener"); // NOI18N } } this.documentProgressListener = new DocumentProgressListener(); } if (this.documentProgressListener.getRequestId() != -1) { log.error("FeatureMapService(" + mapService + "): The documentProgressListener is already in use by request '" + this.documentProgressListener.getRequestId() + ", document progress cannot be tracked"); // NOI18N } else { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N } } documentFeatureService.addRetrievalListener(this.documentProgressListener); } } } mapService.addRetrievalListener(new MappingComponentFeatureServiceListener( (ServiceLayer)mapService, (PLayer)mapService.getPNode())); } p.setTransparency(mapService.getTranslucency()); p.setVisible(mapService.isVisible()); mapServicelayer.addChild(p); // if (internalLayerWidgetAvailable) { //// LayerControl lc=internalLayerWidget.addRasterService(rs.size()-rsi,(ServiceLayer)o,cismapPrefs.getGlobalPrefs().getErrorAbolitionTime()); // LayerControl lc = internalLayerWidget.addRasterService(position, (ServiceLayer) mapService, 500); // mapService.addRetrievalListener(lc); // lc.setTransparentable(p); // layerControls.add(lc); // } } catch (Throwable t) { log.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + t.getMessage(), t); // NOI18N } } /** * DOCUMENT ME! * * @param mm DOCUMENT ME! */ public void preparationSetMappingModel(final MappingModel mm) { mappingModel = mm; } /** * Sets a new mappingmodel in this MappingComponent. * * @param mm the new mappingmodel */ public void setMappingModel(final MappingModel mm) { log.info("setMappingModel"); // NOI18N if (Thread.getDefaultUncaughtExceptionHandler() == null) { log.info("setDefaultUncaughtExceptionHandler"); // NOI18N Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { log.error("Error", e); } }); } mappingModel = mm; currentBoundingBox = mm.getInitialBoundingBox(); final Runnable r = new Runnable() { @Override public void run() { mappingModel.addMappingModelListener(MappingComponent.this); // currentBoundingBox=mm.getInitialBoundingBox(); final TreeMap rs = mappingModel.getRasterServices(); // reCalcWtstAndBoundingBox(); // Rückwärts wegen der Reihenfolge der Layer im Layer Widget final Iterator it = rs.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { addMapService(((MapService)o), rsi); } } // Es gibt nur noch MapServices // TreeMap fs = mappingModel.getFeatureServices(); // //Rueckwaerts wegen der Reihenfolge der Layer im Layer Widget // it = fs.keySet().iterator(); // while (it.hasNext()) { // Object key = it.next(); // int fsi = ((Integer) key).intValue(); // Object o = fs.get(key); // if (o instanceof MapService) { // if(DEBUG)log.debug("neuer Featureservice: " + o); // PLayer pn = new PLayer(); // //pn.setVisible(true); // //pn.setBounds(this.getRoot().getFullBounds()); // pn.setTransparency(((MapService) o).getTranslucency()); // //((FeatureService)o).setPNode(pn); // featureServiceLayer.addChild(pn); // pn.addClientProperty("serviceLayer", (ServiceLayer) o); // //getCamera().addLayer(pn); // ((MapService) o).addRetrievalListener(new MappingComponentFeatureServiceListener((ServiceLayer) o, pn)); // if(DEBUG)log.debug("add FeatureService"); // // //if (internalLayerWidgetAvailable) { // //LayerControl lc = internalLayerWidget.addFeatureService(fs.size() - fsi, (ServiceLayer) o, 3000); // //LayerControl lc=internalLayerWidget.addFeatureService(fs.size()-fsi,(ServiceLayer)o,cismapPrefs.getGlobalPrefs().getErrorAbolitionTime()); //// ((MapService) o).addRetrievalListener(lc); //// lc.setTransparentable(pn); //// layerControls.add(lc); // //} // } // } adjustLayers(); // TODO MappingModel im InternalLayerWidget setzen, da es bei // der Initialisierung des Widgets NULL ist // internalLayerWidget = new NewSimpleInternalLayerWidget(MappingComponent.this); // internalLayerWidget.setMappingModel(mappingModel); // gotoInitialBoundingBox(); final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Set Mapping Modell done"); // NOI18N } } } }; CismetThreadPool.execute(r); } /** * Returns the current mappingmodel. * * @return current mappingmodel */ public MappingModel getMappingModel() { return mappingModel; } /** * Animates a component to a given x/y-coordinate in a given time. * * @param c the component to animate * @param toX final x-position * @param toY final y-position * @param animationDuration duration of the animation * @param hideAfterAnimation should the component be hidden after animation? */ private void animateComponent(final JComponent c, final int toX, final int toY, final int animationDuration, final boolean hideAfterAnimation) { if (animationDuration > 0) { final int x = (int)c.getBounds().getX() - toX; final int y = (int)c.getBounds().getY() - toY; int sx; int sy; if (x > 0) { sx = -1; } else { sx = 1; } if (y > 0) { sy = -1; } else { sy = 1; } int big; if (Math.abs(x) > Math.abs(y)) { big = Math.abs(x); } else { big = Math.abs(y); } final int sleepy; if ((animationDuration / big) < 1) { sleepy = 1; } else { sleepy = (int)(animationDuration / big); } final int directionY = sy; final int directionX = sx; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY + ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX=" + toX + ", toY=" + toY); // NOI18N } } final Thread timer = new Thread() { @Override public void run() { while (!isInterrupted()) { try { sleep(sleepy); } catch (Exception iex) { } EventQueue.invokeLater(new Runnable() { @Override public void run() { int currentY = (int)c.getBounds().getY(); int currentX = (int)c.getBounds().getX(); if (currentY != toY) { currentY = currentY + directionY; } if (currentX != toX) { currentX = currentX + directionX; } c.setBounds(currentX, currentY, c.getWidth(), c.getHeight()); } }); if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) { if (hideAfterAnimation) { EventQueue.invokeLater(new Runnable() { @Override public void run() { c.setVisible(false); c.hide(); } }); } break; } } } }; timer.setPriority(Thread.NORM_PRIORITY); timer.start(); } else { c.setBounds(toX, toY, c.getWidth(), c.getHeight()); if (hideAfterAnimation) { c.setVisible(false); } } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @depreacted DOCUMENT ME! */ @Deprecated public NewSimpleInternalLayerWidget getInternalLayerWidget() { return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET); } /** * Adds a new internal widget to the map.<br/> * If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget * will be added. If a widget with a different name already exisit at the same {@code position} the new widget will * not be added and the operation returns {@code false}. * * @param name unique name of the widget * @param position position of the widget * @param widget the widget * * @return {@code true} if the widget could be added, {@code false} otherwise * * @see #POSITION_NORTHEAST * @see #POSITION_NORTHWEST * @see #POSITION_SOUTHEAST * @see #POSITION_SOUTHWEST */ public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) { if (log.isDebugEnabled()) { log.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N } if (this.internalWidgets.containsKey(name)) { log.warn("widget '" + name + "' already added, removing old widget"); // NOI18N this.remove(this.getInternalWidget(name)); } else if (this.internalWidgetPositions.containsValue(position)) { log.warn("widget position '" + position + "' already taken"); // NOI18N return false; } this.internalWidgets.put(name, widget); this.internalWidgetPositions.put(name, position); widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N this.add(widget); widget.pack(); return true; } /** * Removes an existing internal widget from the map. * * @param name name of the widget to be removed * * @return {@code true} id the widget was found and removed, {@code false} otherwise */ public boolean removeInternalWidget(final String name) { if (log.isDebugEnabled()) { log.debug("removing internal widget '" + name + "'"); // NOI18N } if (!this.internalWidgets.containsKey(name)) { log.warn("widget '" + name + "' not found"); // NOI18N return false; } this.remove(this.getInternalWidget(name)); this.internalWidgets.remove(name); this.internalWidgetPositions.remove(name); return true; } /** * Shows an InternalWidget by sliding it into the mappingcomponent. * * @param name name of the internl component to show * @param visible should the widget be visible after the animation? * @param animationDuration duration of the animation * * @return {@code true} if the operation was successful, {@code false} otherwise */ public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) { // log.info("showing internal widget '" + name + "': " + visible); final JInternalFrame internalWidget = this.getInternalWidget(name); if (internalWidget == null) { return false; } int positionX; int positionY; final int widgetPosition = this.getInternalWidgetPosition(name); switch (widgetPosition) { case POSITION_NORTHWEST: { positionX = 1; positionY = 1; break; } case POSITION_SOUTHWEST: { positionX = 1; positionY = getHeight() - internalWidget.getHeight() - 1; break; } case POSITION_NORTHEAST: { positionX = getWidth() - internalWidget.getWidth() - 1; positionY = 1; break; } case POSITION_SOUTHEAST: { positionX = getWidth() - internalWidget.getWidth() - 1; positionY = getHeight() - internalWidget.getHeight() - 1; break; } default: { log.warn("unkown widget position?!"); // NOI18N return false; } } if (visible) { int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } internalWidget.setBounds(positionX, toY, internalWidget.getWidth(), internalWidget.getHeight()); internalWidget.setVisible(true); internalWidget.show(); animateComponent(internalWidget, positionX, positionY, animationDuration, false); } else { internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight()); int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } animateComponent(internalWidget, positionX, toY, animationDuration, true); } return true; } /** * DOCUMENT ME! * * @param visible DOCUMENT ME! * @param animationDuration DOCUMENT ME! */ @Deprecated public void showInternalLayerWidget(final boolean visible, final int animationDuration) { this.showInternalWidget(LAYERWIDGET, visible, animationDuration); // //NORTH WEST // int positionX = 1; // int positionY = 1; // // //SOUTH WEST // positionX = 1; // positionY = getHeight() - getInternalLayerWidget().getHeight() - 1; // // //NORTH EAST // positionX = getWidth() - getInternalLayerWidget().getWidth() - 1; // positionY = 1; // // SOUTH EAST // int positionX = getWidth() - internalLayerWidget.getWidth() - 1; // int positionY = getHeight() - internalLayerWidget.getHeight() - 1; // // if (visible) // { // internalLayerWidget.setVisible(true); // internalLayerWidget.show(); // internalLayerWidget.setBounds(positionX, positionY + internalLayerWidget.getHeight() + 1, internalLayerWidget.getWidth(), internalLayerWidget.getHeight()); // animateComponent(internalLayerWidget, positionX, positionY, animationDuration, false); // // } else // { // internalLayerWidget.setBounds(positionX, positionY, internalLayerWidget.getWidth(), internalLayerWidget.getHeight()); // animateComponent(internalLayerWidget, positionX, positionY + internalLayerWidget.getHeight() + 1, animationDuration, true); // } } /** * Returns a boolean, if the InternalLayerWidget is visible. * * @return true, if visible, else false */ @Deprecated public boolean isInternalLayerWidgetVisible() { return this.getInternalLayerWidget().isVisible(); } /** * Returns a boolean, if the InternalWidget is visible. * * @param name name of the widget * * @return true, if visible, else false */ public boolean isInternalWidgetVisible(final String name) { final JInternalFrame widget = this.getInternalWidget(name); if (widget != null) { return widget.isVisible(); } return false; } /** * Moves the camera to the initial bounding box (e.g. if the home-button is pressed). */ public void gotoInitialBoundingBox() { final double x1; final double y1; final double x2; final double y2; final double w; final double h; x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1()); y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1()); x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2()); y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2()); final Rectangle2D home = new Rectangle2D.Double(); home.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(home, true, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { log.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } setNewViewBounds(home); queryServices(); } /** * Refreshs all registered services. */ public void queryServices() { if (newViewBounds != null) { addToHistory(new PBoundsWithCleverToString( new PBounds(newViewBounds), wtst, CismapBroker.getInstance().getSrs().getCode())); queryServicesWithoutHistory(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServices()"); // NOI18N } } rescaleStickyNodes(); } // showHandles(false); } /** * Forces all services to refresh themselves. */ public void refresh() { forceQueryServicesWithoutHistory(); } /** * Forces all services to refresh themselves. */ private void forceQueryServicesWithoutHistory() { queryServicesWithoutHistory(true); } /** * Refreshs all services, but not forced. */ private void queryServicesWithoutHistory() { queryServicesWithoutHistory(false); } /** * Waits until all animations are done, then iterates through all registered services and calls handleMapService() * for each. * * @param forced forces the refresh */ private void queryServicesWithoutHistory(final boolean forced) { if (!locked) { final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception doNothing) { } } CismapBroker.getInstance().fireMapBoundsChanged(); if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N } } handleMapService(rsi, (MapService)o, forced); } else { log.warn("service is not of type MapService:" + o); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof MapService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N } } handleMapService(fsi, (MapService)o, forced); } else { log.warn("service is not of type MapService:" + o); // NOI18N } } } } }; CismetThreadPool.execute(r); } } /** * queryServicesIndependentFromMap. * * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param rl DOCUMENT ME! */ public void queryServicesIndependentFromMap(final int width, final int height, final BoundingBox bb, final RetrievalListener rl) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N } } final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception doNothing) { } } if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer) && ((ServiceLayer)o).isEnabled() && (o instanceof RetrievalServiceLayer) && ((RetrievalServiceLayer)o).getPNode().getVisible()) { try { // AbstractRetrievalService r = ((AbstractRetrievalService) // o).cloneWithoutRetrievalListeners(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = wfsClone; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(rsi); handleMapService(rsi, (MapService)r, width, height, bb, true); } catch (Throwable t) { log.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N } } else { log.warn("ignoring service '" + o + "' for printing"); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof AbstractRetrievalService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = (AbstractRetrievalService)o; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(fsi); handleMapService(fsi, (MapService)r, 0, 0, bb, true); } } } } }; CismetThreadPool.execute(r); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param service rs * @param forced DOCUMENT ME! */ public void handleMapService(final int position, final MapService service, final boolean forced) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("in handleRasterService: " + service + "(" + Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N } } final PBounds bounds = getCamera().getViewBounds(); final BoundingBox bb = new BoundingBox(); final double x1 = getWtst().getWorldX(bounds.getMinX()); final double y1 = getWtst().getWorldY(bounds.getMaxY()); final double x2 = getWtst().getWorldX(bounds.getMaxX()); final double y2 = getWtst().getWorldY(bounds.getMinY()); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Bounds=" + bounds); // NOI18N } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N } } if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N bb.setX1(x1 - (x2 - x1)); bb.setY1(y1 - (y2 - y1)); bb.setX2(x2 + (x2 - x1)); bb.setY2(y2 + (y2 - y1)); } else { bb.setX1(x1); bb.setY1(y1); bb.setX2(x2); bb.setY2(y2); } handleMapService(position, service, getWidth(), getHeight(), bb, forced); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param rs DOCUMENT ME! * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param forced DOCUMENT ME! */ private void handleMapService(final int position, final MapService rs, final int width, final int height, final BoundingBox bb, final boolean forced) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("handleMapService: " + rs); // NOI18N } } if (((ServiceLayer)rs).isEnabled()) { synchronized (serviceFuturesMap) { final Future<?> sf = serviceFuturesMap.get(rs); if ((sf == null) || sf.isDone()) { rs.setSize(height, width); final Runnable serviceCall = new Runnable() { @Override public void run() { try { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception e) { } } rs.setBoundingBox(bb); if (rs instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection); } rs.retrieve(forced); } finally { serviceFuturesMap.remove(rs); } } }; synchronized (serviceFuturesMap) { serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall)); } } } } } // private void handleMapService(int position, final MapService rs, int width, int height, final BoundingBox bb, final boolean forced) { // if (DEBUG) { // log.debug("handleMapService: " + rs); // } // // if (((ServiceLayer) rs).isEnabled()) { // rs.setSize(height, width); // //if(DEBUG)log.debug("this.currentBoundingBox:"+this.currentBoundingBox); // //If the PCanvas is in animation state, there should be a pre information about the // //aimed new bounds // Runnable handle = new Runnable() { // // @Override // public void run() { // while (getAnimating()) { // try { // Thread.currentThread().sleep(50); // } catch (Exception e) { // } // } // rs.setBoundingBox(bb); // if (rs instanceof FeatureAwareRasterService) { // ((FeatureAwareRasterService) rs).setFeatureCollection(featureCollection); // } // rs.retrieve(forced); // } // }; // CismetThreadPool.execute(handle); // } // } //former synchronized method // private void handleFeatureService(int position, final FeatureService fs, boolean forced) { // synchronized (handleFeatureServiceBlocker) { // PBounds bounds = getCamera().getViewBounds(); // // BoundingBox bb = new BoundingBox(); // double x1 = getWtst().getSourceX(bounds.getMinX()); // double y1 = getWtst().getSourceY(bounds.getMaxY()); // double x2 = getWtst().getSourceX(bounds.getMaxX()); // double y2 = getWtst().getSourceY(bounds.getMinY()); // // if(DEBUG)log.debug("handleFeatureService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // // bb.setX1(x1); // bb.setY1(y1); // bb.setX2(x2); // bb.setY2(y2); // handleFeatureService(position, fs, bb, forced); // } // } ////former synchronized method // Object handleFeatureServiceBlocker2 = new Object(); // // private void handleFeatureService(int position, final FeatureService fs, final BoundingBox bb, final boolean forced) { // synchronized (handleFeatureServiceBlocker2) { // if(DEBUG)log.debug("handleFeatureService"); // if (fs instanceof ServiceLayer && ((ServiceLayer) fs).isEnabled()) { // Thread handle = new Thread() { // // @Override // public void run() { // while (getAnimating()) { // try { // sleep(50); // } catch (Exception e) { // log.error("Fehler im handle FeatureServicethread"); // } // } // fs.setBoundingBox(bb); // fs.retrieve(forced); // } // }; // handle.setPriority(Thread.NORM_PRIORITY); // handle.start(); // } // } // } /** * Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it. * * @return new WorldToScreenTransform or null */ public WorldToScreenTransform getWtst() { try { if (wtst == null) { final double y_real = mappingModel.getInitialBoundingBox().getY2() - mappingModel.getInitialBoundingBox().getY1(); final double x_real = mappingModel.getInitialBoundingBox().getX2() - mappingModel.getInitialBoundingBox().getX1(); double clip_height; double clip_width; double x_screen = getWidth(); double y_screen = getHeight(); if (x_screen == 0) { x_screen = 100; } if (y_screen == 0) { y_screen = 100; } if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert clip_height = x_screen * y_real / x_real; clip_width = x_screen; clip_offset_y = 0; // (y_screen-clip_height)/2; clip_offset_x = 0; } else { // Y ist Bestimmer clip_height = y_screen; clip_width = y_screen * x_real / y_real; clip_offset_y = 0; clip_offset_x = 0; // (x_screen-clip_width)/2; } // wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX2(),mappingModel.getInitialBoundingBox().getY2(),0,0,clip_width,clip_height); // wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX2(),mappingModel.getInitialBoundingBox().getY2(),0,0, // x_real,y_real); wtst= new WorldToScreenTransform(2566470,5673088,2566470+100,5673088+100,0,0,100,100); // wtst= new WorldToScreenTransform(-180,-90,180,90,0,0,180,90); wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX1()+100,mappingModel.getInitialBoundingBox().getY1()+100,0,0,100,100); // wtst= new WorldToScreenTransform(0,0, 1000, 1000, 0,0, 1000,1000); wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(), mappingModel.getInitialBoundingBox().getY2()); } return wtst; } catch (Throwable t) { log.error("Fehler in getWtst()", t); // NOI18N return null; } } /** * Resets the current WorldToScreenTransformation. */ public void resetWtst() { wtst = null; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_x() { return 0; // clip_offset_x; } /** * Assigns a new value to the x-clip-offset. * * @param clip_offset_x new clipoffset */ public void setClip_offset_x(final double clip_offset_x) { this.clip_offset_x = clip_offset_x; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_y() { return 0; // clip_offset_y; } /** * Assigns a new value to the y-clip-offset. * * @param clip_offset_y new clipoffset */ public void setClip_offset_y(final double clip_offset_y) { this.clip_offset_y = clip_offset_y; } /** * Returns the rubberband-PLayer. * * @return DOCUMENT ME! */ public PLayer getRubberBandLayer() { return rubberBandLayer; } /** * Assigns a given PLayer to the variable rubberBandLayer. * * @param rubberBandLayer a PLayer */ public void setRubberBandLayer(final PLayer rubberBandLayer) { this.rubberBandLayer = rubberBandLayer; } /** * Sets new viewbounds. * * @param r2d Rectangle2D */ public void setNewViewBounds(final Rectangle2D r2d) { newViewBounds = r2d; } /** * Will be called if the selection of features changes. It selects the PFeatures connected to the selected features * of the featurecollectionevent and moves them to the front. Also repaints handles at the end. * * @param fce featurecollectionevent with selected features */ @Override public void featureSelectionChanged(final FeatureCollectionEvent fce) { final Collection<PFeature> all = featureLayer.getChildrenReference(); for (final PFeature f : all) { f.setSelected(false); } Collection<Feature> c; if (fce != null) { c = fce.getFeatureCollection().getSelectedFeatures(); } else { c = featureCollection.getSelectedFeatures(); } ////handle featuregroup select-delegation//// final Set<Feature> selectionResult = TypeSafeCollections.newHashSet(); for (final Feature current : c) { if (current instanceof FeatureGroup) { selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current)); } else { selectionResult.add(current); } } ///////////////////////////////////////////// c = selectionResult; for (final Feature f : c) { if (f != null) { final PFeature feature = (PFeature)getPFeatureHM().get(f); if (feature != null) { feature.setSelected(true); feature.moveToFront(); // Fuer den selectedObjectPresenter (Eigener PCanvas) syncSelectedObjectPresenter(1000); } else { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } } showHandles(false); } /** * Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on * each feature of the given featurecollectionevent. Repaints handles at the end. * * @param fce featurecollectionevent with changed features */ @Override public void featuresChanged(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("featuresChanged"); // NOI18N } } final List<Feature> list = new ArrayList<Feature>(); list.addAll(fce.getEventFeatures()); for (final Feature elem : list) { reconsiderFeature(elem); } showHandles(false); } /** * Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls * following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode() * * @param fce featurecollectionevent with features to reconsile */ @Override public void featureReconsiderationRequested(final FeatureCollectionEvent fce) { for (final Feature f : fce.getEventFeatures()) { if (f != null) { final PFeature node = pFeatureHM.get(f); if (node != null) { node.syncGeometry(); node.visualize(); node.resetInfoNodePosition(); node.refreshInfoNode(); repaint(); // für Mehrfachzeichnung der Handles verantworlich ?? // showHandles(false); } } } } /** * Adds all features from the FeatureCollectionEvent to the mappingcomponent. Paints handles at the end. Former * synchronized method. * * @param fce FeatureCollectionEvent with features to add */ @Override public void featuresAdded(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("firefeaturesAdded (old disabled)"); // NOI18N } } // Attention: Bug-Gefahr !!! TODO // addFeaturesToMap(fce.getEventFeatures().toArray(new Feature[0])); // if(DEBUG)log.debug("featuresAdded()"); } /** * Method is deprecated and deactivated. Does nothing!! * * @deprecated DOCUMENT ME! */ @Override @Deprecated public void featureCollectionChanged() { // if (getFeatureCollection() instanceof DefaultFeatureCollection) { // DefaultFeatureCollection coll=((DefaultFeatureCollection)getFeatureCollection()); // Vector<String> layers=coll.getAllLayers(); // for (String layer :layers) { // if (!featureLayers.keySet().contains(layer)) { // PLayer pLayer=new PLayer(); // featureLayer.addChild(pLayer); // featureLayers.put(layer,pLayer); // } // } // } } /** * Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a * checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent. * * @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice */ @Override public void allFeaturesRemoved(final FeatureCollectionEvent fce) { for (final PFeature feature : pFeatureHM.values()) { feature.cleanup(); } stickyPNodes.clear(); pFeatureHM.clear(); featureLayer.removeAllChildren(); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); } /** * Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining * supporting rasterservices and paints handles at the end. * * @param fce FeatureCollectionEvent with features to remove */ @Override public void featuresRemoved(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("featuresRemoved"); // NOI18N } } removeFeatures(fce.getEventFeatures()); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); showHandles(false); } /** * Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and * which need a refresh. * * @param fce FeatureCollectionEvent with removed features */ private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) { final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>(); for (final Feature f : getFeatureCollection().getAllFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } rasterServices.add(rs); // DANGER } } for (final Feature f : fce.getEventFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } if (rasterServices.contains(rs)) { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r); } } } else { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r); } } } } } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) { getMappingModel().removeLayer(frs); } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) { handleMapService(0, frs, true); } } // public void showFeatureCollection(Feature[] features) { // com.vividsolutions.jts.geom.Envelope env=computeFeatureEnvelope(features); // showFeatureCollection(features,env); // } // public void showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { // selectedFeature=null; // handleLayer.removeAllChildren(); // //setRasterServiceLayerImagesVisibility(false); // Envelope eSquare=null; // HashSet<Feature> featureSet=new HashSet<Feature>(); // featureSet.addAll(holdFeatures); // featureSet.addAll(java.util.Arrays.asList(f)); // Feature[] features=featureSet.toArray(new Feature[0]); // // pFeatureHM.clear(); // addFeaturesToMap(features); // zoomToFullFeatureCollectionBounds(); // // } /** * Creates new PFeatures for all features in the given array and adds them to the PFeatureHashmap. Then adds the * PFeature to the featurelayer. * * <p>DANGER: there's a bug risk here because the method runs in an own thread! It is possible that a PFeature of a * feature is demanded but not yet added to the hashmap which causes in most cases a NullPointerException!</p> * * @param features array with features to add */ public void addFeaturesToMap(final Feature[] features) { // Runnable r = new Runnable() { // // @Override // public void run() { final double local_clip_offset_y = clip_offset_y; final double local_clip_offset_x = clip_offset_x; /// Hier muss der layer bestimmt werdenn for (int i = 0; i < features.length; ++i) { final PFeature p = new PFeature( features[i], getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); try { if (features[i] instanceof StyledFeature) { p.setTransparency(((StyledFeature)(features[i])).getTransparency()); } else { p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); } } catch (Exception e) { p.setTransparency(0.8f); log.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N } // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) // PFeature p=new PFeature(features[i],(WorldToScreenTransform)null,(double)0,(double)0); p.setViewer(this); // ((PPath)p).setStroke(new BasicStroke(0.5f)); if (features[i].getGeometry() != null) { pFeatureHM.put(p.getFeature(), p); // for (int j = 0; j < p.getCoordArr().length; ++j) { // pFeatureHMbyCoordinate.put(p.getCoordArr()[j], new PFeatureCoordinatePosition(p, j)); // } final int ii = i; EventQueue.invokeLater(new Runnable() { @Override public void run() { featureLayer.addChild(p); if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { // p.moveToBack(); p.moveToFront(); } } }); } } EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodes(); repaint(); fireFeaturesAddedToMap(Arrays.asList(features)); // SuchFeatures in den Vordergrund stellen for (final Feature feature : featureCollection.getAllFeatures()) { if (feature instanceof SearchFeature) { final PFeature pFeature = pFeatureHM.get(feature); pFeature.moveToFront(); } } } }); // } // }; // CismetThreadPool.execute(r); // check whether the feature has a rasterSupportLayer or not for (final Feature f : features) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (!getMappingModel().getRasterServices().containsValue(rs)) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureAwareRasterServiceAdded"); // NOI18N } } rs.setFeatureCollection(getFeatureCollection()); getMappingModel().addLayer(rs); } } } showHandles(false); } // public void addFeaturesToMap(final Feature[] features) { // Runnable r = new Runnable() { // // @Override // public void run() { // double local_clip_offset_y = clip_offset_y; // double local_clip_offset_x = clip_offset_x; // // /// Hier muss der layer bestimmt werdenn // for (int i = 0; i < features.length; ++i) { // final PFeature p = new PFeature(features[i], getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); // try { // if (features[i] instanceof StyledFeature) { // p.setTransparency(((StyledFeature) (features[i])).getTransparency()); // } else { // p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); // } // } catch (Exception e) { // p.setTransparency(0.8f); // log.info("Fehler beim Setzen der Transparenzeinstellungen", e); // } // // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) // // PFeature p=new PFeature(features[i],(WorldToScreenTransform)null,(double)0,(double)0); // // p.setViewer(this); // // ((PPath)p).setStroke(new BasicStroke(0.5f)); // if (features[i].getGeometry() != null) { // pFeatureHM.put(p.getFeature(), p); // for (int j = 0; j < p.getCoordArr().length; ++j) { // pFeatureHMbyCoordinate.put(p.getCoordArr()[j], new PFeatureCoordinatePosition(p, j)); // } // final int ii = i; // EventQueue.invokeLater(new Runnable() { // // @Override // public void run() { // featureLayer.addChild(p); // if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { // //p.moveToBack(); // p.moveToFront(); // } // } // }); // } // } // EventQueue.invokeLater(new Runnable() { // // @Override // public void run() { // rescaleStickyNodes(); // repaint(); // fireFeaturesAddedToMap(Arrays.asList(features)); // // // SuchFeatures in den Vordergrund stellen // for (Feature feature : featureCollection.getAllFeatures()) { // if (feature instanceof SearchFeature) { // PFeature pFeature = (PFeature)pFeatureHM.get(feature); // pFeature.moveToFront(); // } // } // } // }); // } // }; // CismetThreadPool.execute(r); // // //check whether the feature has a rasterSupportLayer or not // for (Feature f : features) { // if (f instanceof RasterLayerSupportedFeature && ((RasterLayerSupportedFeature) f).getSupportingRasterService() != null) { // FeatureAwareRasterService rs = ((RasterLayerSupportedFeature) f).getSupportingRasterService(); // if (!getMappingModel().getRasterServices().containsValue(rs)) { // if (DEBUG) { // log.debug("FeatureAwareRasterServiceAdded"); // } // rs.setFeatureCollection(getFeatureCollection()); // getMappingModel().addLayer(rs); // } // } // } // // showHandles(false); // } /** * DOCUMENT ME! * * @param cf DOCUMENT ME! */ private void fireFeaturesAddedToMap(final Collection<Feature> cf) { for (final MapListener curMapListener : mapListeners) { curMapListener.featuresAddedToMap(cf); } } /** * Returns a list of PFeatureCoordinatePositions which are located at the given coordinate. * * @param features c Coordinate * * @return list of PFeatureCoordinatePositions */ // public List<PFeatureCoordinatePosition> getPFeaturesByCoordinates(Coordinate c) { // List<PFeatureCoordinatePosition> l = (List<PFeatureCoordinatePosition>) pFeatureHMbyCoordinate.get(c); // return l; // } /** * Creates an envelope around all features from the given array. * * @param features features to create the envelope around * * @return Envelope com.vividsolutions.jts.geom.Envelope */ private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) { final PNode root = new PNode(); for (int i = 0; i < features.length; ++i) { final PNode p = PNodeFactory.createPFeature(features[i], this); if (p != null) { root.addChild(p); } } final PBounds ext = root.getFullBounds(); final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope( ext.x, ext.x + ext.width, ext.y, ext.y + ext.height); return env; } /** * Zooms in / out to match the bounds of the featurecollection. */ public void zoomToFullFeatureCollectionBounds() { zoomToFeatureCollection(); } /** * Adds a new cursor to the cursor-hashmap. * * @param mode interactionmode as string * @param cursor cursor-object */ public void putCursor(final String mode, final Cursor cursor) { cursors.put(mode, cursor); } /** * Returns the cursor assigned to the given mode. * * @param mode mode as String * * @return Cursor-object or null */ public Cursor getCursor(final String mode) { return cursors.get(mode); } /** * Adds a new PBasicInputEventHandler for a specific interactionmode. * * @param mode interactionmode as string * @param listener new PBasicInputEventHandler */ public void addInputListener(final String mode, final PBasicInputEventHandler listener) { inputEventListener.put(mode, listener); } /** * Returns the PBasicInputEventHandler assigned to the committed interactionmode. * * @param mode interactionmode as string * * @return PBasicInputEventHandler-object or null */ public PInputEventListener getInputListener(final String mode) { final Object o = inputEventListener.get(mode); if (o instanceof PInputEventListener) { return (PInputEventListener)o; } else { return null; } } /** * Returns whether the features are editable or not. * * @return DOCUMENT ME! */ public boolean isReadOnly() { return readOnly; } /** * Sets all Features ReadOnly use Feature.setEditable(boolean) instead. * * @param readOnly DOCUMENT ME! */ public void setReadOnly(final boolean readOnly) { for (final Object f : featureCollection.getAllFeatures()) { ((Feature)f).setEditable(!readOnly); } this.readOnly = readOnly; handleLayer.repaint(); // if (readOnly==false) { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } snapHandleLayer.removeAllChildren(); // } } /** * Returns the current HandleInteractionMode. * * @return DOCUMENT ME! */ public String getHandleInteractionMode() { return handleInteractionMode; } /** * Changes the HandleInteractionMode. Repaints handles. * * @param handleInteractionMode the new HandleInteractionMode */ public void setHandleInteractionMode(final String handleInteractionMode) { this.handleInteractionMode = handleInteractionMode; showHandles(false); } /** * Returns whether the background is enabled or not. * * @return DOCUMENT ME! */ public boolean isBackgroundEnabled() { return backgroundEnabled; } /** * TODO. * * @param backgroundEnabled DOCUMENT ME! */ public void setBackgroundEnabled(final boolean backgroundEnabled) { if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) { featureServiceLayerVisible = featureServiceLayer.getVisible(); } this.mapServicelayer.setVisible(backgroundEnabled); this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible); } if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) { this.queryServices(); } this.backgroundEnabled = backgroundEnabled; } /** * Returns the featurelayer. * * @return DOCUMENT ME! */ public PLayer getFeatureLayer() { return featureLayer; } /** * Adds a PFeature to the PFeatureHashmap. * * @param p PFeature to add */ public void refreshHM(final PFeature p) { pFeatureHM.put(p.getFeature(), p); } /** * Returns the selectedObjectPresenter (PCanvas). * * @return DOCUMENT ME! */ public PCanvas getSelectedObjectPresenter() { return selectedObjectPresenter; } /** * If f != null it calls the reconsiderFeature()-method of the featurecollection. * * @param f feature to reconcile */ public void reconsiderFeature(final Feature f) { if (f != null) { featureCollection.reconsiderFeature(f); } } /** * Removes all features of the collection from the hashmap. * * @param fc collection of features to remove */ public void removeFeatures(final Collection<Feature> fc) { featureLayer.setVisible(false); for (final Feature elem : fc) { removeFromHM(elem); } featureLayer.setVisible(true); } /** * Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key. * * @param f feature of the Pfeature that should be deleted */ public void removeFromHM(final Feature f) { final PFeature pf = pFeatureHM.get(f); if (pf != null) { pf.cleanup(); pFeatureHM.remove(f); stickyPNodes.remove(pf); try { log.info("Entferne Feature " + f); // NOI18N featureLayer.removeChild(pf); } catch (Exception ex) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N } } } } else { log.warn("Feature war nicht in pFeatureHM"); // NOI18N } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("pFeatureHM" + pFeatureHM); // NOI18N } } } /** * Zooms to the current selected node. * * @deprecated DOCUMENT ME! */ public void zoomToSelectedNode() { zoomToSelection(); } /** * Zooms to the current selected features. */ public void zoomToSelection() { final Collection<Feature> selection = featureCollection.getSelectedFeatures(); zoomToAFeatureCollection(selection, true, false); } /** * Zooms to a specific featurecollection. * * @param collection the featurecolltion * @param withHistory should the zoomaction be undoable * @param fixedScale fixedScale */ public void zoomToAFeatureCollection(final Collection<Feature> collection, final boolean withHistory, final boolean fixedScale) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("zoomToAFeatureCollection"); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } boolean first = true; Geometry g = null; for (final Feature f : collection) { if (first) { g = f.getGeometry().getEnvelope(); if (f instanceof Bufferable) { g = g.buffer(((Bufferable)f).getBuffer()); } first = false; } else { if (f.getGeometry() != null) { Geometry geometry = f.getGeometry().getEnvelope(); if (f instanceof Bufferable) { geometry = geometry.buffer(((Bufferable)f).getBuffer()); } g = g.getEnvelope().union(geometry); } } } if (g != null) { // dreisatz.de final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10; final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10; if ((getHeight() == 0) || (getWidth() == 0)) { log.fatal("DIVISION BY ZERO"); // NOI18N } double buff = 0; if (hBuff > vBuff) { buff = hBuff; } else { buff = vBuff; } g = g.buffer(buff); final BoundingBox bb = new BoundingBox(g); gotoBoundingBox(bb, withHistory, !fixedScale, animationDuration); } } /** * Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create * their handles and to add them to the handlelayer. * * @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles */ public void showHandles(final boolean waitTillAllAnimationsAreComplete) { // are there features selected? if (featureCollection.getSelectedFeatures().size() > 0) { // DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf final Runnable handle = new Runnable() { @Override public void run() { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); while (getAnimating() && waitTillAllAnimationsAreComplete) { try { Thread.currentThread().sleep(10); } catch (Exception e) { log.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (featureCollection.areFeaturesEditable() && (getInteractionMode().equals(SELECT) || getInteractionMode().equals(LINEMEASUREMENT) || getInteractionMode().equals(PAN) || getInteractionMode().equals(ZOOM) || getInteractionMode().equals(ALKIS_PRINT) || getInteractionMode().equals(SPLIT_POLYGON))) { // Handles für alle selektierten Features der Collection hinzufügen if (getHandleInteractionMode().equals(ROTATE_POLYGON)) { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature instanceof Feature) && ((Feature)selectedFeature).isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { ((PFeature)pFeatureHM.get(selectedFeature)).addRotationHandles( handleLayer); } }); } else { log.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } } } } else { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature != null) && selectedFeature.isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { try { ((PFeature)pFeatureHM.get(selectedFeature)).addHandles( handleLayer); } catch (Exception e) { log.error("Error bei addHandles: ", e); // NOI18N } } }); } else { log.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } // DANGER mit break werden nur die Handles EINES slektierten Features angezeigt // wird break auskommentiert werden jedoch zu viele Handles angezeigt break; } } } } } }; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("showHandles", new CurrentStackTrace()); // NOI18N } } CismetThreadPool.execute(handle); } else { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); } } /** * Will return a PureNewFeature if there is only one in the featurecollection else null. * * @return DOCUMENT ME! */ public PFeature getSolePureNewFeature() { int counter = 0; PFeature sole = null; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object o = it.next(); if (o instanceof PFeature) { if (((PFeature)o).getFeature() instanceof PureNewFeature) { ++counter; sole = ((PFeature)o); } } } if (counter == 1) { return sole; } else { return null; } } /** * Sets the visibility of the children of the rasterservicelayer. * * @param visible true sets visible */ private void setRasterServiceLayerImagesVisibility(final boolean visible) { final Iterator it = mapServicelayer.getChildrenIterator(); while (it.hasNext()) { final Object o = it.next(); if (o instanceof XPImage) { ((XPImage)o).setVisible(visible); } } } /** * Returns the temporary featurelayer. * * @return DOCUMENT ME! */ public PLayer getTmpFeatureLayer() { return tmpFeatureLayer; } /** * Assigns a new temporary featurelayer. * * @param tmpFeatureLayer PLayer */ public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) { this.tmpFeatureLayer = tmpFeatureLayer; } /** * Returns whether the grid is enabled or not. * * @return DOCUMENT ME! */ public boolean isGridEnabled() { return gridEnabled; } /** * Enables or disables the grid. * * @param gridEnabled true, to enable the grid */ public void setGridEnabled(final boolean gridEnabled) { this.gridEnabled = gridEnabled; } /** * Returns a String from two double-values. Serves the visualization. * * @param x X-coordinate * @param y Y-coordinate * * @return a Strin-object like "(X,Y)" */ public static String getCoordinateString(final double x, final double y) { final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N final DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); df.setDecimalFormatSymbols(dfs); return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHandleLayer() { return handleLayer; } /** * DOCUMENT ME! * * @param handleLayer DOCUMENT ME! */ public void setHandleLayer(final PLayer handleLayer) { this.handleLayer = handleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingEnabled() { return visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingEnabled DOCUMENT ME! */ public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) { this.visualizeSnappingEnabled = visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingRectEnabled() { return visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingRectEnabled DOCUMENT ME! */ public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) { this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getSnappingRectSize() { return snappingRectSize; } /** * DOCUMENT ME! * * @param snappingRectSize DOCUMENT ME! */ public void setSnappingRectSize(final int snappingRectSize) { this.snappingRectSize = snappingRectSize; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getSnapHandleLayer() { return snapHandleLayer; } /** * DOCUMENT ME! * * @param snapHandleLayer DOCUMENT ME! */ public void setSnapHandleLayer(final PLayer snapHandleLayer) { this.snapHandleLayer = snapHandleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isSnappingEnabled() { return snappingEnabled; } /** * DOCUMENT ME! * * @param snappingEnabled DOCUMENT ME! */ public void setSnappingEnabled(final boolean snappingEnabled) { this.snappingEnabled = snappingEnabled; setVisualizeSnappingEnabled(snappingEnabled); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getFeatureServiceLayer() { return featureServiceLayer; } /** * DOCUMENT ME! * * @param featureServiceLayer DOCUMENT ME! */ public void setFeatureServiceLayer(final PLayer featureServiceLayer) { this.featureServiceLayer = featureServiceLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getAnimationDuration() { return animationDuration; } /** * DOCUMENT ME! * * @param animationDuration DOCUMENT ME! */ public void setAnimationDuration(final int animationDuration) { this.animationDuration = animationDuration; } /** * DOCUMENT ME! * * @param prefs DOCUMENT ME! */ @Deprecated public void setPreferences(final CismapPreferences prefs) { log.warn("involing deprecated operation setPreferences()"); // NOI18N cismapPrefs = prefs; // DefaultMappingModel mm = new DefaultMappingModel(); final ActiveLayerModel mm = new ActiveLayerModel(); final LayersPreferences layersPrefs = prefs.getLayersPrefs(); final GlobalPreferences globalPrefs = prefs.getGlobalPrefs(); setSnappingRectSize(globalPrefs.getSnappingRectSize()); setSnappingEnabled(globalPrefs.isSnappingEnabled()); setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled()); setAnimationDuration(globalPrefs.getAnimationDuration()); setInteractionMode(globalPrefs.getStartMode()); // mm.setInitialBoundingBox(globalPrefs.getInitialBoundingBox()); mm.addHome(globalPrefs.getInitialBoundingBox()); final Crs crs = new Crs(); crs.setCode(globalPrefs.getInitialBoundingBox().getSrs()); crs.setName(globalPrefs.getInitialBoundingBox().getSrs()); crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs()); mm.setSrs(crs); final TreeMap raster = layersPrefs.getRasterServices(); if (raster != null) { final Iterator it = raster.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = raster.get(key); if (o instanceof MapService) { // mm.putMapService(((Integer) key).intValue(), (MapService) o); mm.addLayer((RetrievalServiceLayer)o); } } } final TreeMap features = layersPrefs.getFeatureServices(); if (features != null) { final Iterator it = features.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = features.get(key); if (o instanceof MapService) { // TODO // mm.putMapService(((Integer) key).intValue(), (MapService) o); mm.addLayer((RetrievalServiceLayer)o); } } } setMappingModel(mm); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public CismapPreferences getCismapPrefs() { return cismapPrefs; } /** * DOCUMENT ME! * * @param duration DOCUMENT ME! * @param animationDuration DOCUMENT ME! * @param what DOCUMENT ME! * @param number DOCUMENT ME! */ public void flash(final int duration, final int animationDuration, final int what, final int number) { } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getDragPerformanceImproverLayer() { return dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @param dragPerformanceImproverLayer DOCUMENT ME! */ public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) { this.dragPerformanceImproverLayer = dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public PLayer getRasterServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getMapServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @param rasterServiceLayer DOCUMENT ME! */ public void setRasterServiceLayer(final PLayer rasterServiceLayer) { this.mapServicelayer = rasterServiceLayer; } /** * DOCUMENT ME! * * @param f DOCUMENT ME! */ public void showGeometryInfoPanel(final Feature f) { } /** * Adds a PropertyChangeListener to the listener list. * * @param l The listener to add. */ @Override public void addPropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener from the listener list. * * @param l The listener to remove. */ @Override public void removePropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.removePropertyChangeListener(l); } /** * Setter for property taskCounter. former synchronized method */ public void fireActivityChanged() { propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N } /** * Returns true, if there's still one layercontrol running. Else false; former synchronized method * * @return DOCUMENT ME! */ public boolean isRunning() { for (final LayerControl lc : layerControls) { if (lc.isRunning()) { return true; } } return false; } /** * Sets the visibility of all infonodes. * * @param visible true, if infonodes should be visible */ public void setInfoNodesVisible(final boolean visible) { infoNodesVisible = visible; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object elem = it.next(); if (elem instanceof PFeature) { ((PFeature)elem).setInfoNodeVisible(visible); } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("setInfoNodesVisible()"); // NOI18N } } rescaleStickyNodes(); } /** * Adds an object to the historymodel. * * @param o Object to add */ @Override public void addToHistory(final Object o) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("addToHistory:" + o.toString()); // NOI18N } } historyModel.addToHistory(o); } /** * Removes a specific HistoryModelListener from the historymodel. * * @param hml HistoryModelListener */ @Override public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.removeHistoryModelListener(hml); } /** * Adds aHistoryModelListener to the historymodel. * * @param hml HistoryModelListener */ @Override public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.addHistoryModelListener(hml); } /** * Sets the maximum value of saved historyactions. * * @param max new integer value */ @Override public void setMaximumPossibilities(final int max) { historyModel.setMaximumPossibilities(max); } /** * Redos the last undone historyaction. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the forward-action */ @Override public Object forward(final boolean external) { final PBounds fwd = (PBounds)historyModel.forward(external); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("HistoryModel.forward():" + fwd); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(fwd); } return fwd; } /** * Undos the last action. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the back-action */ @Override public Object back(final boolean external) { final PBounds back = (PBounds)historyModel.back(external); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("HistoryModel.back():" + back); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(back); } return back; } /** * Returns true, if it's possible to redo an action. * * @return DOCUMENT ME! */ @Override public boolean isForwardPossible() { return historyModel.isForwardPossible(); } /** * Returns true, if it's possible to undo an action. * * @return DOCUMENT ME! */ @Override public boolean isBackPossible() { return historyModel.isBackPossible(); } /** * Returns a vector with all redo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getForwardPossibilities() { return historyModel.getForwardPossibilities(); } /** * Returns the current element of the historymodel. * * @return DOCUMENT ME! */ @Override public Object getCurrentElement() { return historyModel.getCurrentElement(); } /** * Returns a vector with all undo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getBackPossibilities() { return historyModel.getBackPossibilities(); } /** * Returns whether an internallayerwidget is available. * * @return DOCUMENT ME! */ @Deprecated public boolean isInternalLayerWidgetAvailable() { return this.getInternalWidget(LAYERWIDGET) != null; } /** * Sets the variable, if an internallayerwidget is available or not. * * @param internalLayerWidgetAvailable true, if available */ @Deprecated public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) { if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) { this.removeInternalWidget(LAYERWIDGET); } else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) { final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); } } @Override public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) { } /** * Removes the mapservice from the rasterservicelayer. * * @param rasterService the removing mapservice */ @Override public void mapServiceRemoved(final MapService rasterService) { try { mapServicelayer.removeChild(rasterService.getPNode()); System.gc(); } catch (Exception e) { log.warn("Fehler bei mapServiceRemoved", e); // NOI18N } } /** * Adds the commited mapservice on the last position to the rasterservicelayer. * * @param mapService the new mapservice */ @Override public void mapServiceAdded(final MapService mapService) { addMapService(mapService, mapServicelayer.getChildrenCount()); if (mapService instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection()); } if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) { handleMapService(0, mapService, false); } } /** * Returns the current OGC scale. * * @return DOCUMENT ME! */ public double getCurrentOGCScale() { // funktioniert nur bei metrischen SRS's final double h = getCamera().getViewBounds().getHeight() / getHeight(); final double w = getCamera().getViewBounds().getWidth() / getWidth(); // if(DEBUG)log.debug("H�he:"+getHeight()+" Breite:"+getWidth()); // if(DEBUG)log.debug("H�heReal:"+getCamera().getViewBounds().getHeight()+" BreiteReal:"+getCamera().getViewBounds().getWidth()); return Math.sqrt((h * h) + (w * w)); // Math.sqrt((getWidth()*getWidth())*2); } /** * Returns the current BoundingBox. * * @return DOCUMENT ME! */ public BoundingBox getCurrentBoundingBox() { if (fixedBoundingBox != null) { return fixedBoundingBox; } else { try { final PBounds bounds = getCamera().getViewBounds(); final double x1 = wtst.getWorldX(bounds.getX()); final double y1 = wtst.getWorldY(bounds.getY()); final double x2 = x1 + bounds.width; final double y2 = y1 - bounds.height; currentBoundingBox = new BoundingBox(x1, y1, x2, y2); // if(DEBUG)log.debug("getCurrentBoundingBox()" + currentBoundingBox + "(" + (y2 - y1) + "," + (x2 - // x1) + ")", new CurrentStackTrace()); return currentBoundingBox; } catch (Throwable t) { log.error("Fehler in getCurrentBoundingBox()", t); // NOI18N return null; } } } /** * Returns a BoundingBox with a fixed size. * * @return DOCUMENT ME! */ public BoundingBox getFixedBoundingBox() { return fixedBoundingBox; } /** * Assigns fixedBoundingBox a new value. * * @param fixedBoundingBox new boundingbox */ public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) { this.fixedBoundingBox = fixedBoundingBox; } /** * Paints the outline of the forwarded BoundingBox. * * @param bb BoundingBox */ public void outlineArea(final BoundingBox bb) { outlineArea(bb, null); } /** * Paints the outline of the forwarded PBounds. * * @param b PBounds */ public void outlineArea(final PBounds b) { outlineArea(b, null); } /** * Paints a filled rectangle of the area of the forwarded BoundingBox. * * @param bb BoundingBox * @param fillingPaint Color to fill the rectangle */ public void outlineArea(final BoundingBox bb, final Paint fillingPaint) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } outlineArea(pb, fillingPaint); } /** * Paints a filled rectangle of the area of the forwarded PBounds. * * @param b PBounds to paint * @param fillingColor Color to fill the rectangle */ public void outlineArea(final PBounds b, final Paint fillingColor) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { highlightingLayer.removeAllChildren(); } } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(fillingColor); rectangle.setStroke(new FixedWidthStroke()); rectangle.setStrokePaint(new Color(100, 100, 100, 255)); rectangle.setPathTo(b); highlightingLayer.addChild(rectangle); } } /** * Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally. * * @param bb BoundingBox to highlight */ public void highlightArea(final BoundingBox bb) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } highlightArea(pb); } /** * Highlights the delivered PBounds by painting over with a transparent white. * * @param b PBounds to hightlight */ private void highlightArea(final PBounds b) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { } highlightingLayer.animateToTransparency(0, animationDuration); highlightingLayer.removeAllChildren(); } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(new Color(255, 255, 255, 100)); rectangle.setStroke(null); // rectangle.setStroke(new BasicStroke((float)(1/ getCamera().getViewScale()))); // rectangle.setStrokePaint(new Color(255,255,255,20)); rectangle.setPathTo(this.getCamera().getViewBounds()); highlightingLayer.addChild(rectangle); rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration); } } /** * Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls * crossHairPoint(Point p) internally. * * @param c coordinate of the crosshair's venue */ public void crossHairPoint(final Coordinate c) { Point p = null; if (c != null) { p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y)); } crossHairPoint(p); } /** * Paints a crosshair at the delivered point. * * @param p point of the crosshair's venue */ public void crossHairPoint(final Point p) { if (p == null) { if (crosshairLayer.getChildrenCount() > 0) { crosshairLayer.removeAllChildren(); } } else { crosshairLayer.removeAllChildren(); crosshairLayer.setTransparency(1); final PPath lineX = new PPath(); final PPath lineY = new PPath(); lineX.setStroke(new FixedWidthStroke()); lineX.setStrokePaint(new Color(100, 100, 100, 255)); lineY.setStroke(new FixedWidthStroke()); lineY.setStrokePaint(new Color(100, 100, 100, 255)); // PBounds current=getCurrentBoundingBox().getPBounds(getWtst()); final PBounds current = getCamera().getViewBounds(); final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1); final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2); lineX.setPathTo(x); crosshairLayer.addChild(lineX); lineY.setPathTo(y); crosshairLayer.addChild(lineY); } } @Override public Element getConfiguration() { if (log.isDebugEnabled()) { log.debug("writing configuration <cismapMappingPreferences>"); // NOI18N } final Element ret = new Element("cismapMappingPreferences"); // NOI18N ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N ret.setAttribute( "creationMode", ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N // Position final Element currentPosition = new Element("Position"); // NOI18N // if (Double.isNaN(getCurrentBoundingBox().getX1())|| // Double.isNaN(getCurrentBoundingBox().getX2())|| // Double.isNaN(getCurrentBoundingBox().getY1())|| // Double.isNaN(getCurrentBoundingBox().getY2())) { // log.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // gotoInitialBoundingBox(); // } currentPosition.addContent(currentBoundingBox.getJDOMElement()); currentPosition.setAttribute("CRS", CismapBroker.getInstance().getSrs().getCode()); // currentPosition.addContent(getCurrentBoundingBox().getJDOMElement()); ret.addContent(currentPosition); // Crs final Element crsListElement = new Element("crsList"); for (final Crs tmp : crsList) { crsListElement.addContent(tmp.getJDOMElement()); } ret.addContent(crsListElement); if (printingSettingsDialog != null) { ret.addContent(printingSettingsDialog.getConfiguration()); } // save internal widgets status final Element widgets = new Element("InternalWidgets"); // NOI18N for (final String name : this.internalWidgets.keySet()) { final Element widget = new Element("Widget"); // NOI18N widget.setAttribute("name", name); // NOI18N widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N widgets.addContent(widget); } ret.addContent(widgets); return ret; } @Override public void masterConfigure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N // CRS List try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); crsList.add(s); if (s.isSelected() && s.isMetric()) { try { transformer = new CrsTransformer(s.getCode()); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (Exception skip) { log.error("Error while reading the crs list", skip); // NOI18N } if (transformer == null) { log.warn("No metric default crs found. Use EPSG:31466 to calculate geometry lengths and scales"); try { transformer = new CrsTransformer("EPSG:31466"); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); } } // HOME try { if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N } } while (it.hasNext()) { final Element elem = it.next(); final String srs = elem.getAttribute("srs").getValue(); // NOI18N boolean metric = false; try { metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { log.warn("Metric hat falschen Syntax", dce); // NOI18N } boolean defaultVal = false; try { defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { log.warn("default hat falschen Syntax", dce); // NOI18N } final XBoundingBox xbox = new XBoundingBox(elem, srs, metric); alm.addHome(xbox); if (defaultVal) { Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(srs)) { crsObject = tmp; break; } } if (crsObject == null) { log.error("CRS " + srs + " from the default home is not found in the crs list"); crsObject = new Crs(srs, srs, srs, true, false); crsList.add(crsObject); } alm.setSrs(crsObject); alm.setDefaultSrs(crsObject); CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } } } } catch (Throwable t) { log.error("Fehler beim MasterConfigure der MappingComponent", t); // NOI18N } try { final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N scales.clear(); for (final Object elem : scalesList) { if (elem instanceof Element) { final Scale s = new Scale((Element)elem); scales.add(s); } } } catch (Exception skip) { log.error("Fehler beim Lesen von Scale", skip); // NOI18N } // Und jetzt noch die PriningEinstellungen initPrintingDialogs(); printingSettingsDialog.masterConfigure(prefs); } /** * Configurates this MappingComponent. * * @param e JDOM-Element with configuration */ @Override public void configure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); if (!crsList.contains(s)) { crsList.add(s); } if (s.isSelected() && s.isMetric()) { try { transformer = new CrsTransformer(s.getCode()); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (Exception skip) { log.error("Error while reading the crs list", skip); // NOI18N } // InteractionMode try { final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N setInteractionMode(interactMode); if (interactMode.equals(MappingComponent.NEW_POLYGON)) { try { final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode); } catch (Throwable t) { log.warn("Fehler beim Setzen des CreationInteractionMode", t); // NOI18N } } } catch (Throwable t) { log.warn("Fehler beim Setzen des InteractionMode", t); // NOI18N } try { final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N setHandleInteractionMode(handleInterMode); } catch (Throwable t) { log.warn("Fehler beim Setzen des HandleInteractionMode", t); // NOI18N } try { final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N log.info("snapping=" + snapping); // NOI18N setSnappingEnabled(snapping); setVisualizeSnappingEnabled(snapping); setInGlueIdenticalPointsMode(snapping); } catch (Throwable t) { log.warn("Fehler beim setzen von snapping und Konsorten", t); // NOI18N } // aktuelle Position try { final Element pos = prefs.getChild("Position"); // NOI18N final BoundingBox b = new BoundingBox(pos); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Position:" + b); // NOI18N } } final PBounds pb = b.getPBounds(getWtst()); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("PositionPb:" + pb); // NOI18N } } if (Double.isNaN(b.getX1()) || Double.isNaN(b.getX2()) || Double.isNaN(b.getY1()) || Double.isNaN(b.getY2())) { log.fatal("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N // gotoInitialBoundingBox(); this.currentBoundingBox = getMappingModel().getInitialBoundingBox(); final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); addToHistory(new PBoundsWithCleverToString( new PBounds(currentBoundingBox.getPBounds(wtst)), wtst, crsCode)); } else { // set the current crs final Attribute crsAtt = pos.getAttribute("CRS"); if (crsAtt != null) { final String currentCrs = crsAtt.getValue(); Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(currentCrs)) { crsObject = tmp; break; } } if (crsObject == null) { log.error("CRS " + currentCrs + " from the position element is not found in the crs list"); } final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); if (alm instanceof ActiveLayerModel) { alm.setSrs(crsObject); } CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } this.currentBoundingBox = b; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("added to History" + b); // NOI18N } } final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); // addToHistory(new PBoundsWithCleverToString(new PBounds(currentBoundingBox.getPBounds(wtst)), wtst, crsCode )); // final BoundingBox bb=b; // EventQueue.invokeLater(new Runnable() { // public void run() { // gotoBoundingBoxWithHistory(bb); // } // }); } } catch (Throwable t) { log.error("Fehler beim lesen der aktuellen Position", t); // NOI18N // EventQueue.invokeLater(new Runnable() { // public void run() { // gotoBoundingBoxWithHistory(getMappingModel().getInitialBoundingBox()); this.currentBoundingBox = getMappingModel().getInitialBoundingBox(); // } // }); } if (printingSettingsDialog != null) { printingSettingsDialog.configure(prefs); } try { final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N if (widgets != null) { for (final Object widget : widgets.getChildren()) { final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N this.showInternalWidget(name, visible, 0); } } } catch (Throwable t) { log.warn("could not enable internal widgets: " + t, t); // NOI18N } } /** * Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent * will only pan to the featurecollection and not zoom. * * @param fixedScale true, if zoom is not allowed */ public void zoomToFeatureCollection(final boolean fixedScale) { zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale); } /** * Zooms to all features of the mappingcomponents featurecollection. */ public void zoomToFeatureCollection() { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("zoomToFeatureCollection"); // NOI18N } } zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration) { gotoBoundingBox(bb, history, scaleToFit, animationDuration, true); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation * @param queryServices true, if the services should be refreshed after animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration, final boolean queryServices) { if (bb != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } final double x1 = getWtst().getScreenX(bb.getX1()); final double y1 = getWtst().getScreenY(bb.getY1()); final double x2 = getWtst().getScreenX(bb.getX2()); final double y2 = getWtst().getScreenY(bb.getY2()); final double w; final double h; final Rectangle2D pos = new Rectangle2D.Double(); pos.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { log.fatal("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } showHandles(true); final Runnable handle = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(10); } catch (Exception e) { log.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (history) { if ((x1 == x2) || (y1 == y2) || !scaleToFit) { setNewViewBounds(getCamera().getViewBounds()); } else { setNewViewBounds(pos); } if (queryServices) { queryServices(); } } else { if (queryServices) { queryServicesWithoutHistory(); } } } }; CismetThreadPool.execute(handle); } else { log.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N } } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) { gotoBoundingBox(bb, false, true, animationDuration); } /** * Moves the view to the target Boundingbox and saves the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithHistory(final BoundingBox bb) { gotoBoundingBox(bb, true, true, animationDuration); } /** * Returns a BoundingBox of the current view in another scale. * * @param scaleDenominator specific target scale * * @return DOCUMENT ME! */ public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) { return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBox()); } /** * Returns the BoundingBox of the delivered BoundingBox in another scale. * * @param scaleDenominator specific target scale * @param bb source BoundingBox * * @return DOCUMENT ME! */ public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) { final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator; final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator; if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { // transform the given bounding box to a metric coordinate system bb = transformer.transformBoundingBox(bb, CismapBroker.getInstance().getSrs().getCode()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2); final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2); BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2), midY - (realWorldHeightInMeter / 2), midX + (realWorldWidthInMeter / 2), midY + (realWorldHeightInMeter / 2)); if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { // transform the scaled bounding box to the current coordinate system final CrsTransformer trans = new CrsTransformer(CismapBroker.getInstance().getSrs().getCode()); scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } return scaledBox; } /** * Calculate the current scaledenominator. * * @return DOCUMENT ME! */ public double getScaleDenominator() { BoundingBox boundingBox = getCurrentBoundingBox(); final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { boundingBox = transformer.transformBoundingBox( boundingBox, CismapBroker.getInstance().getSrs().getCode()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } final double realWorldWidthInMeter = boundingBox.getWidth(); final double realWorldHeightInMeter = boundingBox.getHeight(); return realWorldWidthInMeter / screenWidthInMeter; } // public static Image getFeatureImage(Feature f){ // MappingComponent mc=new MappingComponent(); // mc.setSize(100,100); // pc.setInfoNodesVisible(true); // pc.setSize(100,100); // PFeature pf=new PFeature(pnf,new WorldToScreenTransform(0,0),0,0,null); // pc.getLayer().addChild(pf); // pc.getCamera().animateViewToCenterBounds(pf.getBounds(),true,0); // i=new ImageIcon(pc.getCamera().toImage(100,100,getBackground())); // } /** * Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code> * DropTarget</code> registered with this listener. * * <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code> * DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data * object(s) to be transfered.</p> * * <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int * dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P> * * <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be * invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData() * method.</P> * * <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the * drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method.</P> * * <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code> * Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only * if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code> * true</code>. Otherwise, the behavior of the call is implementation-dependent.</P> * * @param dtde the <code>DropTargetDropEvent</code> */ @Override public void drop(final DropTargetDropEvent dtde) { if (isDropEnabled(dtde)) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDropOnMap(mde); } catch (NoninvertibleTransformException ex) { log.error(ex, ex); } } } /** * DOCUMENT ME! * * @param dtde DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean isDropEnabled(final DropTargetDropEvent dtde) { if (ALKIS_PRINT.equals(getInteractionMode())) { for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) { // necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) { return false; } } } return true; } /** * Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site * for the <code>DropTarget</code> registered with this listener. * * @param dte the <code>DropTargetEvent</code> */ @Override public void dragExit(final DropTargetEvent dte) { } /** * Called if the user has modified the current drop gesture. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dropActionChanged(final DropTargetDragEvent dtde) { } /** * Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p * site for the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragOver(final DropTargetDragEvent dtde) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); // TODO: this seems to be buggy! final Point p = dtde.getLocation(); // Point2D p2d; // double scale = 1 / getCamera().getViewScale(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDragOverMap(mde); } catch (NoninvertibleTransformException ex) { log.error(ex, ex); } // MapDnDEvent mde = new MapDnDEvent(); // mde.setDte(dtde); // Point p = dtde.getLocation(); // double scale = 1/getCamera().getViewScale(); // mde.setXPos(getWtst().getWorldX(p.getX() * scale)); // mde.setYPos(getWtst().getWorldY(p.getY() * scale)); // CismapBroker.getInstance().fireDragOverMap(mde); } /** * Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for * the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragEnter(final DropTargetDragEvent dtde) { } /** * Returns the PfeatureHashmap which assigns a Feature to a PFeature. * * @return DOCUMENT ME! */ public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() { return pFeatureHM; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapExtent() { return fixedMapExtent; } /** * DOCUMENT ME! * * @param fixedMapExtent DOCUMENT ME! */ public void setFixedMapExtent(final boolean fixedMapExtent) { this.fixedMapExtent = fixedMapExtent; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapScale() { return fixedMapScale; } /** * DOCUMENT ME! * * @param fixedMapScale DOCUMENT ME! */ public void setFixedMapScale(final boolean fixedMapScale) { this.fixedMapScale = fixedMapScale; } /** * DOCUMENT ME! * * @param one DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public void selectPFeatureManually(final PFeature one) { // throw new UnsupportedOperationException("Not yet implemented"); if (one != null) { featureCollection.select(one.getFeature()); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public PFeature getSelectedNode() { // gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist // deshalb gebe ich mal nur das erste zur�ck if (featureCollection.getSelectedFeatures().size() > 0) { final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0]; if (selF == null) { return null; } return pFeatureHM.get(selF); } else { return null; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInfoNodesVisible() { return infoNodesVisible; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getPrintingFrameLayer() { return printingFrameLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PrintingSettingsWidget getPrintingSettingsDialog() { return printingSettingsDialog; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInGlueIdenticalPointsMode() { return inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @param inGlueIdenticalPointsMode DOCUMENT ME! */ public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) { this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHighlightingLayer() { return highlightingLayer; } /** * DOCUMENT ME! * * @param anno DOCUMENT ME! */ public void setPointerAnnotation(final PNode anno) { ((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno); } /** * DOCUMENT ME! * * @param visib DOCUMENT ME! */ public void setPointerAnnotationVisibility(final boolean visib) { if (getInputListener(MOTION) != null) { ((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib); } } /** * Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't * equal MOTION. * * @return DOCUMENT ME! */ public boolean isPointerAnnotationVisible() { if (getInputListener(MOTION) != null) { return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible(); } else { return false; } } /** * Returns a vector with different scales. * * @return DOCUMENT ME! */ public List<Scale> getScales() { return scales; } /** * Returns a list with different crs. * * @return DOCUMENT ME! */ public List<Crs> getCrsList() { return crsList; } /** * DOCUMENT ME! * * @return a transformer with the default crs as destination crs. The default crs is the first crs in the * configuration file that has set the selected attribut on true). This crs must be metric. */ public CrsTransformer getMetricTransformer() { return transformer; } /** * Locks the MappingComponent. */ public void lock() { locked = true; } /** * Unlocks the MappingComponent. */ public void unlock() { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("unlock"); // NOI18N } } locked = false; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N } } gotoBoundingBoxWithHistory(currentBoundingBox); } /** * Returns whether the MappingComponent is locked or not. * * @return DOCUMENT ME! */ public boolean isLocked() { return locked; } /** * Returns the MementoInterface for redo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemRedo() { return memRedo; } /** * Returns the MementoInterface for undo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemUndo() { return memUndo; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public HashMap<String, PBasicInputEventHandler> getInputEventListener() { return inputEventListener; } /** * DOCUMENT ME! * * @param inputEventListener DOCUMENT ME! */ public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) { this.inputEventListener.clear(); this.inputEventListener.putAll(inputEventListener); } @Override - public void crsChanged(final CrsChangedEvent event) { + public synchronized void crsChanged(final CrsChangedEvent event) { if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) { if (locked) { return; } try { + // the wtst object should not be null, so teh getWtst method will be invoked + getWtst(); final BoundingBox bbox = getCurrentBoundingBox(); // getCurrentBoundingBox(); final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode()); final BoundingBox newBbox = crsTransformer.transformBoundingBox(bbox, event.getFormerCrs().getCode()); if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); } wtst = null; getWtst(); gotoBoundingBoxWithoutHistory(newBbox); // transform all features for (final Feature f : featureCollection.getAllFeatures()) { final Geometry geom = crsTransformer.transformGeometry(f.getGeometry(), event.getFormerCrs().getCode()); f.setGeometry(geom); final PFeature feature = pFeatureHM.get(f); feature.setFeature(f); Coordinate[] coordArray = feature.getCoordArr(); coordArray = crsTransformer.transformGeometry(coordArray, event.getFormerCrs().getCode()); feature.setCoordArr(coordArray); } final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures()); // list.add(f); removeFeatures(list); addFeaturesToMap(list.toArray(new Feature[list.size()])); } catch (Exception e) { JOptionPane.showMessageDialog( this, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"), JOptionPane.ERROR_MESSAGE); log.error("Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e); resetCrs = true; CismapBroker.getInstance().setSrs(event.getFormerCrs()); } } else { resetCrs = false; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public JInternalFrame getInternalWidget(final String name) { if (this.internalWidgets.containsKey(name)) { return this.internalWidgets.get(name); } else { log.warn("unknown internal widget '" + name + "'"); // NOI18N return null; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public int getInternalWidgetPosition(final String name) { if (this.internalWidgetPositions.containsKey(name)) { return this.internalWidgetPositions.get(name); } else { log.warn("unknown position for '" + name + "'"); // NOI18N return -1; } } //~ Inner Classes ---------------------------------------------------------- /** * /////////////////////////////////////////////// CLASS MappingComponentRasterServiceListener // * ///////////////////////////////////////////////. * * @version $Revision$, $Date$ */ private class MappingComponentRasterServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private Logger logger = Logger.getLogger(this.getClass()); private int position = -1; private XPImage pi = null; private ServiceLayer rasterService = null; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentRasterServiceListener object. * * @param position DOCUMENT ME! * @param pn DOCUMENT ME! * @param rasterService DOCUMENT ME! */ public MappingComponentRasterServiceListener(final int position, final PNode pn, final ServiceLayer rasterService) { this.position = position; if (pn instanceof XPImage) { this.pi = (XPImage)pn; } this.rasterService = rasterService; } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { fireActivityChanged(); if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } } @Override public void retrievalProgress(final RetrievalEvent e) { } @Override public void retrievalError(final RetrievalEvent e) { this.logger.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() + " Errors: " + e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N fireActivityChanged(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } } @Override public void retrievalComplete(final RetrievalEvent e) { final Point2D localOrigin = getCamera().getViewBounds().getOrigin(); final double localScale = getCamera().getViewScale(); final PBounds localBounds = getCamera().getViewBounds(); final Object o = e.getRetrievedObject(); // log.fatal(localBounds+ " "+localScale); if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } final Runnable paintImageOnMap = new Runnable() { @Override public void run() { fireActivityChanged(); if ((o instanceof Image) && (e.isHasErrors() == false)) { // TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden if (isBackgroundEnabled()) { // Image i=Static2DTools.toCompatibleImage((Image)o); final Image i = (Image)o; if (rasterService.getName().startsWith("prefetching")) { // NOI18N final double x = localOrigin.getX() - localBounds.getWidth(); final double y = localOrigin.getY() - localBounds.getHeight(); pi.setImage(i, 0); pi.setScale(3 / localScale); pi.setOffset(x, y); } else { pi.setImage(i, 1000); pi.setScale(1 / localScale); pi.setOffset(localOrigin); MappingComponent.this.repaint(); } } } } }; if (EventQueue.isDispatchThread()) { paintImageOnMap.run(); } else { EventQueue.invokeLater(paintImageOnMap); } } @Override public void retrievalAborted(final RetrievalEvent e) { this.logger.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getPosition() { return position; } /** * DOCUMENT ME! * * @param position DOCUMENT ME! */ public void setPosition(final int position) { this.position = position; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class DocumentProgressListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private Logger logger = Logger.getLogger(this.getClass()); private long requestId = -1; /** Displays the loading progress of Documents, e.g. SHP Files */ private final DocumentProgressWidget documentProgressWidget = new DocumentProgressWidget(); //~ Constructors ------------------------------------------------------- /** * Creates a new DocumentProgressListener object. */ public DocumentProgressListener() { documentProgressWidget.setVisible(false); if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) { MappingComponent.this.addInternalWidget( MappingComponent.PROGRESSWIDGET, MappingComponent.POSITION_SOUTHWEST, documentProgressWidget); } } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != -1) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = e.getRequestIdentifier(); this.documentProgressWidget.setServiceName(e.getRetrievalService().toString()); this.documentProgressWidget.setProgress(-1); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100); // MappingComponent.this.showInternalWidget(ZOOM, DEBUG, animationDuration); // MappingComponent.this.isInternalWidgetVisible(ZOOM); } @Override public void retrievalProgress(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: initialisation progress: " + e.getPercentageDone()); // NOI18N } } this.documentProgressWidget.setProgress(e.getPercentageDone()); } @Override public void retrievalComplete(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N } e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(100); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200); } @Override public void retrievalAborted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N } // e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } @Override public void retrievalError(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; e.getRetrievalService().removeRetrievalListener(this); this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public long getRequestId() { return this.requestId; } } /** * //////////////////////////////////////////////// CLASS MappingComponentFeatureServiceListener // * ////////////////////////////////////////////////. * * @version $Revision$, $Date$ */ private class MappingComponentFeatureServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- ServiceLayer featureService; PLayer parent; long requestIdentifier; Thread completionThread = null; private Logger logger = Logger.getLogger(this.getClass()); private Vector deletionCandidates = new Vector(); private Vector twins = new Vector(); //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentFeatureServiceListener. * * @param featureService the featureretrievalservice * @param parent the featurelayer (PNode) connected with the servicelayer */ public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) { this.featureService = featureService; this.parent = parent; } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { requestIdentifier = e.getRequestIdentifier(); } if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N } } fireActivityChanged(); } @Override public void retrievalProgress(final RetrievalEvent e) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: " + e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress() + ")"); // NOI18N } } fireActivityChanged(); // TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das // flüssiger ist } @Override public void retrievalError(final RetrievalEvent e) { this.logger.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N fireActivityChanged(); } @Override public void retrievalComplete(final RetrievalEvent e) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N } } if (e.isInitialisationEvent()) { this.logger.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: initialisation complete"); // NOI18N fireActivityChanged(); return; } if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N } ((RetrievalServiceLayer)featureService).setProgress(-1); fireActivityChanged(); return; } final Vector newFeatures = new Vector(); EventQueue.invokeLater(new Runnable() { @Override public void run() { ((RetrievalServiceLayer)featureService).setProgress(-1); parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible()); // parent.removeAllChildren(); } }); // clear all old data to delete twins deletionCandidates.removeAllElements(); twins.removeAllElements(); // if it's a refresh, add all old features which should be deleted in the // newly acquired featurecollection if (!e.isRefreshExisting()) { deletionCandidates.addAll(parent.getChildrenReference()); } if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N } } // only start parsing the features if there are no errors and a correct collection if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) { completionThread = new Thread() { @Override public void run() { // this is the collection with the retrieved features // Collection c = ((Collection) e.getRetrievedObject()); final List features = new ArrayList((Collection)e.getRetrievedObject()); final int size = features.size(); int counter = 0; final Iterator it = features.iterator(); if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N } } while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted() && it.hasNext()) { counter++; final Object o = it.next(); if (o instanceof Feature) { final PFeature p = new PFeature(((Feature)o), wtst, clip_offset_x, clip_offset_y, MappingComponent.this); PFeature twin = null; for (final Object tester : deletionCandidates) { // if tester and PFeature are FeatureWithId-objects if ((((PFeature)tester).getFeature() instanceof FeatureWithId) && (p.getFeature() instanceof FeatureWithId)) { final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId(); final int id2 = ((FeatureWithId)(p.getFeature())).getId(); if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id if (id1 == id2) { twin = ((PFeature)tester); break; } } else { // else test the geometry for equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } else { // no FeatureWithId, test geometries for // equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } // if a twin is found remove him from the deletion candidates // and add him to the twins if (twin != null) { deletionCandidates.remove(twin); twins.add(twin); } else { // else add the PFeature to the new features newFeatures.add(p); } // calculate the advance of the progressbar // fire event only wheen needed final int currentProgress = (int)((double)counter / (double)size * 100d); /*if(currentProgress % 10 == 0 && currentProgress > lastUpdateProgress) * { lastUpdateProgress = currentProgress; if(DEBUG)log.debug("fire progress changed * "+currentProgress); fireActivityChanged();}*/ if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) { ((RetrievalServiceLayer)featureService).setProgress(currentProgress); fireActivityChanged(); } } } if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) { // after all features are computed do stuff on the EDT EventQueue.invokeLater(new Runnable() { @Override public void run() { try { if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N } } // if it's a refresh, delete all previous features if (e.isRefreshExisting()) { parent.removeAllChildren(); } final Vector deleteFeatures = new Vector(); for (final Object o : newFeatures) { parent.addChild((PNode)o); } // for (Object o : twins) { // TODO only nesseccary if style has changed // ((PFeature) o).refreshDesign(); // if(DEBUG)log.debug("twin refresh"); // } // set the prograssbar to full if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: set progress to 100"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(100); fireActivityChanged(); // repaint the featurelayer parent.repaint(); // remove stickyNode from all deletionCandidates and add // each to the new deletefeature-collection for (final Object o : deletionCandidates) { if (o instanceof PFeature) { final PNode p = ((PFeature)o).getPrimaryAnnotationNode(); if (p != null) { removeStickyNode(p); } deleteFeatures.add(o); } } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount before:" + parent.getChildrenCount()); // NOI18N } } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: deleteFeatures=" + deleteFeatures.size()); // + " :" + // deleteFeatures);//NOI18N } } parent.removeChildren(deleteFeatures); if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount after:" + parent.getChildrenCount()); // NOI18N } } log.info( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + parent.getChildrenCount() + " features retrieved or updated"); // NOI18N rescaleStickyNodes(); } catch (Exception exception) { logger.warn( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Fehler beim Aufr\u00E4umen", exception); // NOI18N } } }); } else { if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } }; completionThread.setPriority(Thread.NORM_PRIORITY); if (requestIdentifier == e.getRequestIdentifier()) { completionThread.start(); } else { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } fireActivityChanged(); } @Override public void retrievalAborted(final RetrievalEvent e) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: aborted, TaskCounter:" + taskCounter); // NOI18N if (completionThread != null) { completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(-1); } else { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(0); } fireActivityChanged(); } } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ class ImageSelection implements Transferable { //~ Instance fields -------------------------------------------------------- private Image image; //~ Constructors ----------------------------------------------------------- /** * Creates a new ImageSelection object. * * @param image DOCUMENT ME! */ public ImageSelection(final Image image) { this.image = image; } //~ Methods ---------------------------------------------------------------- // Returns supported flavors @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { DataFlavor.imageFlavor }; } // Returns true if flavor is supported @Override public boolean isDataFlavorSupported(final DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } // Returns image @Override public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (!DataFlavor.imageFlavor.equals(flavor)) { throw new UnsupportedFlavorException(flavor); } return image; } }
false
true
public void setInteractionMode(final String interactionMode) { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:" + this.interactionMode + "", new Exception()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } setPointerAnnotationVisibility(false); if (getPrintingFrameLayer().getChildrenCount() > 1) { getPrintingFrameLayer().removeAllChildren(); } if (this.interactionMode != null) { if (interactionMode.equals(FEATURE_INFO)) { ((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo() .setVisible(true); } else { ((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo() .setVisible(false); } if (isReadOnly()) { ((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class); } final PInputEventListener pivl = this.getInputListener(this.interactionMode); if (pivl != null) { removeInputEventListener(pivl); } else { log.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N } if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) { // if (selectedFeature!=null) { // selectPFeatureManually(null); // } featureCollection.unselectAll(); } if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEMEASUREMENT) || interactionMode.equals(SPLIT_POLYGON)) && (this.readOnly == false)) { // if (selectedFeature!=null) { // selectPFeatureManually(selectedFeature); // } featureSelectionChanged(null); } if (interactionMode.equals(JOIN_POLYGONS)) { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent( this, PROPERTY_MAP_INTERACTION_MODE, this.interactionMode, interactionMode); this.interactionMode = interactionMode; final PInputEventListener pivl = getInputListener(interactionMode); if (pivl != null) { addInputEventListener(pivl); propertyChangeSupport.firePropertyChange(interactionModeChangedEvent); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode)); } else { log.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N } } catch (Exception e) { log.error("Fehler beim Ändern des InteractionModes", e); // NOI18N } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Deprecated public void formComponentResized(final ComponentEvent evt) { this.componentResizedDelayed(); } /** * Resizes the map and does not reload all services. * * @see #componentResizedDelayed() */ public void componentResizedIntermediate() { if (!this.isLocked()) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N } } if (MappingComponent.this.currentBoundingBox == null) { log.error("currentBoundingBox is null"); // NOI18N currentBoundingBox = getCurrentBoundingBox(); } // rescale map if (historyModel.getCurrentElement() != null) { final PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } getCamera().animateViewToCenterBounds(bounds, true, animationDuration); } } } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } /** * Resizes the map and reloads all services. * * @see #componentResizedIntermediate() */ public void componentResizedDelayed() { if (!this.isLocked()) { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N } } if (MappingComponent.this.currentBoundingBox == null) { log.error("currentBoundingBox is null"); // NOI18N currentBoundingBox = getCurrentBoundingBox(); } gotoBoundsWithoutHistory((PBounds)historyModel.getCurrentElement()); // } // if (getCurrentElement()!=null) { // gotoBoundsWithoutHistory((PBounds)(getCurrentElement())); // } else { // if(DEBUG)log.debug("getCurrentElement()==null) "); // } // for (JComponent internalWiget : this.internalWidgets.values()) // { // if (internalWiget.isVisible()) // { // internalWiget.setVisible(false); // } // } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } // if (internalLayerWidget != null && internalLayerWidget.isVisible()) // { // internalLayerWidget.setVisible(false); // } } } } catch (Throwable t) { log.error("Fehler in formComponentResized()", t); // NOI18N } } } /** * syncSelectedObjectPresenter(int i). * * @param i DOCUMENT ME! */ public void syncSelectedObjectPresenter(final int i) { selectedObjectPresenter.setVisible(true); if (featureCollection.getSelectedFeatures().size() > 0) { if (featureCollection.getSelectedFeatures().size() == 1) { final PFeature selectedFeature = (PFeature)pFeatureHM.get( featureCollection.getSelectedFeatures().toArray()[0]); if (selectedFeature != null) { selectedObjectPresenter.getCamera() .animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2); } } else { // todo } } else { log.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N } } // public void selectPFeatureManually(PFeature feature) { // if (feature==null) { // handleLayer.removeAllChildren(); // if (selectedFeature!=null) { // selectedFeature.setSelected(false); // } // } else { // if (selectedFeature!=null) { // selectedFeature.setSelected(false); // } // feature.setSelected(true); // selectedFeature=feature; // // // //Fuer den selectedObjectPresenter (Eigener PCanvas) // syncSelectedObjectPresenter(1000); // // handleLayer.removeAllChildren(); // if ( this.isReadOnly()==false // &&( // getInteractionMode().equals(SELECT) // || // getInteractionMode().equals(PAN) // || // getInteractionMode().equals(ZOOM) // || // getInteractionMode().equals(SPLIT_POLYGON) // ) // ) { // selectedFeature.addHandles(handleLayer); // } else { // handleLayer.removeAllChildren(); // } // } // // } // public void selectionChanged(de.cismet.cismap.commons.MappingModelEvent mme) { // Feature f=mme.getFeature(); // if (f==null) { // selectPFeatureManually(null); // } else { // PFeature fp=((PFeature)pFeatureHM.get(f)); // if (fp!=null&&fp.getFeature()!=null&&fp.getFeature().getGeometry()!=null) { //// PNode p=fp.getChild(0); // selectPFeatureManually(fp); // } else { // selectPFeatureManually(null); // } // } // } /** * Returns the current featureCollection. * * @return DOCUMENT ME! */ public FeatureCollection getFeatureCollection() { return featureCollection; } /** * Replaces the old featureCollection with a new one. * * @param featureCollection the new featureCollection */ public void setFeatureCollection(final FeatureCollection featureCollection) { this.featureCollection = featureCollection; featureCollection.addFeatureCollectionListener(this); } /** * DOCUMENT ME! * * @param visibility DOCUMENT ME! */ public void setFeatureCollectionVisibility(final boolean visibility) { featureLayer.setVisible(visibility); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFeatureCollectionVisible() { return featureLayer.getVisible(); } /** * Adds a new mapservice at a specific place of the layercontrols. * * @param mapService the new mapservice * @param position the index where to position the mapservice */ public void addMapService(final MapService mapService, final int position) { try { PNode p = new PNode(); if (mapService instanceof RasterMapService) { log.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N if (mapService.getPNode() instanceof XPImage) { p = (XPImage)mapService.getPNode(); } else { p = new XPImage(); mapService.setPNode(p); } mapService.addRetrievalListener(new MappingComponentRasterServiceListener( position, p, (ServiceLayer)mapService)); } else { log.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName() + ")"); // NOI18N p = new PLayer(); mapService.setPNode(p); if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): isDocumentFeatureService, checking document size"); // NOI18N } } final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService; if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) { log.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '" + documentFeatureService.getName() + "' size of " + (documentFeatureService.getDocumentSize() / 1000000) + "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000) + "MB)"); // NOI18N if (this.documentProgressListener == null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): lazy instantiation of documentProgressListener"); // NOI18N } } this.documentProgressListener = new DocumentProgressListener(); } if (this.documentProgressListener.getRequestId() != -1) { log.error("FeatureMapService(" + mapService + "): The documentProgressListener is already in use by request '" + this.documentProgressListener.getRequestId() + ", document progress cannot be tracked"); // NOI18N } else { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N } } documentFeatureService.addRetrievalListener(this.documentProgressListener); } } } mapService.addRetrievalListener(new MappingComponentFeatureServiceListener( (ServiceLayer)mapService, (PLayer)mapService.getPNode())); } p.setTransparency(mapService.getTranslucency()); p.setVisible(mapService.isVisible()); mapServicelayer.addChild(p); // if (internalLayerWidgetAvailable) { //// LayerControl lc=internalLayerWidget.addRasterService(rs.size()-rsi,(ServiceLayer)o,cismapPrefs.getGlobalPrefs().getErrorAbolitionTime()); // LayerControl lc = internalLayerWidget.addRasterService(position, (ServiceLayer) mapService, 500); // mapService.addRetrievalListener(lc); // lc.setTransparentable(p); // layerControls.add(lc); // } } catch (Throwable t) { log.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + t.getMessage(), t); // NOI18N } } /** * DOCUMENT ME! * * @param mm DOCUMENT ME! */ public void preparationSetMappingModel(final MappingModel mm) { mappingModel = mm; } /** * Sets a new mappingmodel in this MappingComponent. * * @param mm the new mappingmodel */ public void setMappingModel(final MappingModel mm) { log.info("setMappingModel"); // NOI18N if (Thread.getDefaultUncaughtExceptionHandler() == null) { log.info("setDefaultUncaughtExceptionHandler"); // NOI18N Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { log.error("Error", e); } }); } mappingModel = mm; currentBoundingBox = mm.getInitialBoundingBox(); final Runnable r = new Runnable() { @Override public void run() { mappingModel.addMappingModelListener(MappingComponent.this); // currentBoundingBox=mm.getInitialBoundingBox(); final TreeMap rs = mappingModel.getRasterServices(); // reCalcWtstAndBoundingBox(); // Rückwärts wegen der Reihenfolge der Layer im Layer Widget final Iterator it = rs.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { addMapService(((MapService)o), rsi); } } // Es gibt nur noch MapServices // TreeMap fs = mappingModel.getFeatureServices(); // //Rueckwaerts wegen der Reihenfolge der Layer im Layer Widget // it = fs.keySet().iterator(); // while (it.hasNext()) { // Object key = it.next(); // int fsi = ((Integer) key).intValue(); // Object o = fs.get(key); // if (o instanceof MapService) { // if(DEBUG)log.debug("neuer Featureservice: " + o); // PLayer pn = new PLayer(); // //pn.setVisible(true); // //pn.setBounds(this.getRoot().getFullBounds()); // pn.setTransparency(((MapService) o).getTranslucency()); // //((FeatureService)o).setPNode(pn); // featureServiceLayer.addChild(pn); // pn.addClientProperty("serviceLayer", (ServiceLayer) o); // //getCamera().addLayer(pn); // ((MapService) o).addRetrievalListener(new MappingComponentFeatureServiceListener((ServiceLayer) o, pn)); // if(DEBUG)log.debug("add FeatureService"); // // //if (internalLayerWidgetAvailable) { // //LayerControl lc = internalLayerWidget.addFeatureService(fs.size() - fsi, (ServiceLayer) o, 3000); // //LayerControl lc=internalLayerWidget.addFeatureService(fs.size()-fsi,(ServiceLayer)o,cismapPrefs.getGlobalPrefs().getErrorAbolitionTime()); //// ((MapService) o).addRetrievalListener(lc); //// lc.setTransparentable(pn); //// layerControls.add(lc); // //} // } // } adjustLayers(); // TODO MappingModel im InternalLayerWidget setzen, da es bei // der Initialisierung des Widgets NULL ist // internalLayerWidget = new NewSimpleInternalLayerWidget(MappingComponent.this); // internalLayerWidget.setMappingModel(mappingModel); // gotoInitialBoundingBox(); final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Set Mapping Modell done"); // NOI18N } } } }; CismetThreadPool.execute(r); } /** * Returns the current mappingmodel. * * @return current mappingmodel */ public MappingModel getMappingModel() { return mappingModel; } /** * Animates a component to a given x/y-coordinate in a given time. * * @param c the component to animate * @param toX final x-position * @param toY final y-position * @param animationDuration duration of the animation * @param hideAfterAnimation should the component be hidden after animation? */ private void animateComponent(final JComponent c, final int toX, final int toY, final int animationDuration, final boolean hideAfterAnimation) { if (animationDuration > 0) { final int x = (int)c.getBounds().getX() - toX; final int y = (int)c.getBounds().getY() - toY; int sx; int sy; if (x > 0) { sx = -1; } else { sx = 1; } if (y > 0) { sy = -1; } else { sy = 1; } int big; if (Math.abs(x) > Math.abs(y)) { big = Math.abs(x); } else { big = Math.abs(y); } final int sleepy; if ((animationDuration / big) < 1) { sleepy = 1; } else { sleepy = (int)(animationDuration / big); } final int directionY = sy; final int directionX = sx; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY + ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX=" + toX + ", toY=" + toY); // NOI18N } } final Thread timer = new Thread() { @Override public void run() { while (!isInterrupted()) { try { sleep(sleepy); } catch (Exception iex) { } EventQueue.invokeLater(new Runnable() { @Override public void run() { int currentY = (int)c.getBounds().getY(); int currentX = (int)c.getBounds().getX(); if (currentY != toY) { currentY = currentY + directionY; } if (currentX != toX) { currentX = currentX + directionX; } c.setBounds(currentX, currentY, c.getWidth(), c.getHeight()); } }); if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) { if (hideAfterAnimation) { EventQueue.invokeLater(new Runnable() { @Override public void run() { c.setVisible(false); c.hide(); } }); } break; } } } }; timer.setPriority(Thread.NORM_PRIORITY); timer.start(); } else { c.setBounds(toX, toY, c.getWidth(), c.getHeight()); if (hideAfterAnimation) { c.setVisible(false); } } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @depreacted DOCUMENT ME! */ @Deprecated public NewSimpleInternalLayerWidget getInternalLayerWidget() { return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET); } /** * Adds a new internal widget to the map.<br/> * If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget * will be added. If a widget with a different name already exisit at the same {@code position} the new widget will * not be added and the operation returns {@code false}. * * @param name unique name of the widget * @param position position of the widget * @param widget the widget * * @return {@code true} if the widget could be added, {@code false} otherwise * * @see #POSITION_NORTHEAST * @see #POSITION_NORTHWEST * @see #POSITION_SOUTHEAST * @see #POSITION_SOUTHWEST */ public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) { if (log.isDebugEnabled()) { log.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N } if (this.internalWidgets.containsKey(name)) { log.warn("widget '" + name + "' already added, removing old widget"); // NOI18N this.remove(this.getInternalWidget(name)); } else if (this.internalWidgetPositions.containsValue(position)) { log.warn("widget position '" + position + "' already taken"); // NOI18N return false; } this.internalWidgets.put(name, widget); this.internalWidgetPositions.put(name, position); widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N this.add(widget); widget.pack(); return true; } /** * Removes an existing internal widget from the map. * * @param name name of the widget to be removed * * @return {@code true} id the widget was found and removed, {@code false} otherwise */ public boolean removeInternalWidget(final String name) { if (log.isDebugEnabled()) { log.debug("removing internal widget '" + name + "'"); // NOI18N } if (!this.internalWidgets.containsKey(name)) { log.warn("widget '" + name + "' not found"); // NOI18N return false; } this.remove(this.getInternalWidget(name)); this.internalWidgets.remove(name); this.internalWidgetPositions.remove(name); return true; } /** * Shows an InternalWidget by sliding it into the mappingcomponent. * * @param name name of the internl component to show * @param visible should the widget be visible after the animation? * @param animationDuration duration of the animation * * @return {@code true} if the operation was successful, {@code false} otherwise */ public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) { // log.info("showing internal widget '" + name + "': " + visible); final JInternalFrame internalWidget = this.getInternalWidget(name); if (internalWidget == null) { return false; } int positionX; int positionY; final int widgetPosition = this.getInternalWidgetPosition(name); switch (widgetPosition) { case POSITION_NORTHWEST: { positionX = 1; positionY = 1; break; } case POSITION_SOUTHWEST: { positionX = 1; positionY = getHeight() - internalWidget.getHeight() - 1; break; } case POSITION_NORTHEAST: { positionX = getWidth() - internalWidget.getWidth() - 1; positionY = 1; break; } case POSITION_SOUTHEAST: { positionX = getWidth() - internalWidget.getWidth() - 1; positionY = getHeight() - internalWidget.getHeight() - 1; break; } default: { log.warn("unkown widget position?!"); // NOI18N return false; } } if (visible) { int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } internalWidget.setBounds(positionX, toY, internalWidget.getWidth(), internalWidget.getHeight()); internalWidget.setVisible(true); internalWidget.show(); animateComponent(internalWidget, positionX, positionY, animationDuration, false); } else { internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight()); int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } animateComponent(internalWidget, positionX, toY, animationDuration, true); } return true; } /** * DOCUMENT ME! * * @param visible DOCUMENT ME! * @param animationDuration DOCUMENT ME! */ @Deprecated public void showInternalLayerWidget(final boolean visible, final int animationDuration) { this.showInternalWidget(LAYERWIDGET, visible, animationDuration); // //NORTH WEST // int positionX = 1; // int positionY = 1; // // //SOUTH WEST // positionX = 1; // positionY = getHeight() - getInternalLayerWidget().getHeight() - 1; // // //NORTH EAST // positionX = getWidth() - getInternalLayerWidget().getWidth() - 1; // positionY = 1; // // SOUTH EAST // int positionX = getWidth() - internalLayerWidget.getWidth() - 1; // int positionY = getHeight() - internalLayerWidget.getHeight() - 1; // // if (visible) // { // internalLayerWidget.setVisible(true); // internalLayerWidget.show(); // internalLayerWidget.setBounds(positionX, positionY + internalLayerWidget.getHeight() + 1, internalLayerWidget.getWidth(), internalLayerWidget.getHeight()); // animateComponent(internalLayerWidget, positionX, positionY, animationDuration, false); // // } else // { // internalLayerWidget.setBounds(positionX, positionY, internalLayerWidget.getWidth(), internalLayerWidget.getHeight()); // animateComponent(internalLayerWidget, positionX, positionY + internalLayerWidget.getHeight() + 1, animationDuration, true); // } } /** * Returns a boolean, if the InternalLayerWidget is visible. * * @return true, if visible, else false */ @Deprecated public boolean isInternalLayerWidgetVisible() { return this.getInternalLayerWidget().isVisible(); } /** * Returns a boolean, if the InternalWidget is visible. * * @param name name of the widget * * @return true, if visible, else false */ public boolean isInternalWidgetVisible(final String name) { final JInternalFrame widget = this.getInternalWidget(name); if (widget != null) { return widget.isVisible(); } return false; } /** * Moves the camera to the initial bounding box (e.g. if the home-button is pressed). */ public void gotoInitialBoundingBox() { final double x1; final double y1; final double x2; final double y2; final double w; final double h; x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1()); y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1()); x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2()); y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2()); final Rectangle2D home = new Rectangle2D.Double(); home.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(home, true, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { log.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } setNewViewBounds(home); queryServices(); } /** * Refreshs all registered services. */ public void queryServices() { if (newViewBounds != null) { addToHistory(new PBoundsWithCleverToString( new PBounds(newViewBounds), wtst, CismapBroker.getInstance().getSrs().getCode())); queryServicesWithoutHistory(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServices()"); // NOI18N } } rescaleStickyNodes(); } // showHandles(false); } /** * Forces all services to refresh themselves. */ public void refresh() { forceQueryServicesWithoutHistory(); } /** * Forces all services to refresh themselves. */ private void forceQueryServicesWithoutHistory() { queryServicesWithoutHistory(true); } /** * Refreshs all services, but not forced. */ private void queryServicesWithoutHistory() { queryServicesWithoutHistory(false); } /** * Waits until all animations are done, then iterates through all registered services and calls handleMapService() * for each. * * @param forced forces the refresh */ private void queryServicesWithoutHistory(final boolean forced) { if (!locked) { final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception doNothing) { } } CismapBroker.getInstance().fireMapBoundsChanged(); if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N } } handleMapService(rsi, (MapService)o, forced); } else { log.warn("service is not of type MapService:" + o); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof MapService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N } } handleMapService(fsi, (MapService)o, forced); } else { log.warn("service is not of type MapService:" + o); // NOI18N } } } } }; CismetThreadPool.execute(r); } } /** * queryServicesIndependentFromMap. * * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param rl DOCUMENT ME! */ public void queryServicesIndependentFromMap(final int width, final int height, final BoundingBox bb, final RetrievalListener rl) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N } } final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception doNothing) { } } if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer) && ((ServiceLayer)o).isEnabled() && (o instanceof RetrievalServiceLayer) && ((RetrievalServiceLayer)o).getPNode().getVisible()) { try { // AbstractRetrievalService r = ((AbstractRetrievalService) // o).cloneWithoutRetrievalListeners(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = wfsClone; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(rsi); handleMapService(rsi, (MapService)r, width, height, bb, true); } catch (Throwable t) { log.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N } } else { log.warn("ignoring service '" + o + "' for printing"); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof AbstractRetrievalService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = (AbstractRetrievalService)o; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(fsi); handleMapService(fsi, (MapService)r, 0, 0, bb, true); } } } } }; CismetThreadPool.execute(r); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param service rs * @param forced DOCUMENT ME! */ public void handleMapService(final int position, final MapService service, final boolean forced) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("in handleRasterService: " + service + "(" + Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N } } final PBounds bounds = getCamera().getViewBounds(); final BoundingBox bb = new BoundingBox(); final double x1 = getWtst().getWorldX(bounds.getMinX()); final double y1 = getWtst().getWorldY(bounds.getMaxY()); final double x2 = getWtst().getWorldX(bounds.getMaxX()); final double y2 = getWtst().getWorldY(bounds.getMinY()); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Bounds=" + bounds); // NOI18N } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N } } if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N bb.setX1(x1 - (x2 - x1)); bb.setY1(y1 - (y2 - y1)); bb.setX2(x2 + (x2 - x1)); bb.setY2(y2 + (y2 - y1)); } else { bb.setX1(x1); bb.setY1(y1); bb.setX2(x2); bb.setY2(y2); } handleMapService(position, service, getWidth(), getHeight(), bb, forced); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param rs DOCUMENT ME! * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param forced DOCUMENT ME! */ private void handleMapService(final int position, final MapService rs, final int width, final int height, final BoundingBox bb, final boolean forced) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("handleMapService: " + rs); // NOI18N } } if (((ServiceLayer)rs).isEnabled()) { synchronized (serviceFuturesMap) { final Future<?> sf = serviceFuturesMap.get(rs); if ((sf == null) || sf.isDone()) { rs.setSize(height, width); final Runnable serviceCall = new Runnable() { @Override public void run() { try { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception e) { } } rs.setBoundingBox(bb); if (rs instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection); } rs.retrieve(forced); } finally { serviceFuturesMap.remove(rs); } } }; synchronized (serviceFuturesMap) { serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall)); } } } } } // private void handleMapService(int position, final MapService rs, int width, int height, final BoundingBox bb, final boolean forced) { // if (DEBUG) { // log.debug("handleMapService: " + rs); // } // // if (((ServiceLayer) rs).isEnabled()) { // rs.setSize(height, width); // //if(DEBUG)log.debug("this.currentBoundingBox:"+this.currentBoundingBox); // //If the PCanvas is in animation state, there should be a pre information about the // //aimed new bounds // Runnable handle = new Runnable() { // // @Override // public void run() { // while (getAnimating()) { // try { // Thread.currentThread().sleep(50); // } catch (Exception e) { // } // } // rs.setBoundingBox(bb); // if (rs instanceof FeatureAwareRasterService) { // ((FeatureAwareRasterService) rs).setFeatureCollection(featureCollection); // } // rs.retrieve(forced); // } // }; // CismetThreadPool.execute(handle); // } // } //former synchronized method // private void handleFeatureService(int position, final FeatureService fs, boolean forced) { // synchronized (handleFeatureServiceBlocker) { // PBounds bounds = getCamera().getViewBounds(); // // BoundingBox bb = new BoundingBox(); // double x1 = getWtst().getSourceX(bounds.getMinX()); // double y1 = getWtst().getSourceY(bounds.getMaxY()); // double x2 = getWtst().getSourceX(bounds.getMaxX()); // double y2 = getWtst().getSourceY(bounds.getMinY()); // // if(DEBUG)log.debug("handleFeatureService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // // bb.setX1(x1); // bb.setY1(y1); // bb.setX2(x2); // bb.setY2(y2); // handleFeatureService(position, fs, bb, forced); // } // } ////former synchronized method // Object handleFeatureServiceBlocker2 = new Object(); // // private void handleFeatureService(int position, final FeatureService fs, final BoundingBox bb, final boolean forced) { // synchronized (handleFeatureServiceBlocker2) { // if(DEBUG)log.debug("handleFeatureService"); // if (fs instanceof ServiceLayer && ((ServiceLayer) fs).isEnabled()) { // Thread handle = new Thread() { // // @Override // public void run() { // while (getAnimating()) { // try { // sleep(50); // } catch (Exception e) { // log.error("Fehler im handle FeatureServicethread"); // } // } // fs.setBoundingBox(bb); // fs.retrieve(forced); // } // }; // handle.setPriority(Thread.NORM_PRIORITY); // handle.start(); // } // } // } /** * Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it. * * @return new WorldToScreenTransform or null */ public WorldToScreenTransform getWtst() { try { if (wtst == null) { final double y_real = mappingModel.getInitialBoundingBox().getY2() - mappingModel.getInitialBoundingBox().getY1(); final double x_real = mappingModel.getInitialBoundingBox().getX2() - mappingModel.getInitialBoundingBox().getX1(); double clip_height; double clip_width; double x_screen = getWidth(); double y_screen = getHeight(); if (x_screen == 0) { x_screen = 100; } if (y_screen == 0) { y_screen = 100; } if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert clip_height = x_screen * y_real / x_real; clip_width = x_screen; clip_offset_y = 0; // (y_screen-clip_height)/2; clip_offset_x = 0; } else { // Y ist Bestimmer clip_height = y_screen; clip_width = y_screen * x_real / y_real; clip_offset_y = 0; clip_offset_x = 0; // (x_screen-clip_width)/2; } // wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX2(),mappingModel.getInitialBoundingBox().getY2(),0,0,clip_width,clip_height); // wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX2(),mappingModel.getInitialBoundingBox().getY2(),0,0, // x_real,y_real); wtst= new WorldToScreenTransform(2566470,5673088,2566470+100,5673088+100,0,0,100,100); // wtst= new WorldToScreenTransform(-180,-90,180,90,0,0,180,90); wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX1()+100,mappingModel.getInitialBoundingBox().getY1()+100,0,0,100,100); // wtst= new WorldToScreenTransform(0,0, 1000, 1000, 0,0, 1000,1000); wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(), mappingModel.getInitialBoundingBox().getY2()); } return wtst; } catch (Throwable t) { log.error("Fehler in getWtst()", t); // NOI18N return null; } } /** * Resets the current WorldToScreenTransformation. */ public void resetWtst() { wtst = null; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_x() { return 0; // clip_offset_x; } /** * Assigns a new value to the x-clip-offset. * * @param clip_offset_x new clipoffset */ public void setClip_offset_x(final double clip_offset_x) { this.clip_offset_x = clip_offset_x; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_y() { return 0; // clip_offset_y; } /** * Assigns a new value to the y-clip-offset. * * @param clip_offset_y new clipoffset */ public void setClip_offset_y(final double clip_offset_y) { this.clip_offset_y = clip_offset_y; } /** * Returns the rubberband-PLayer. * * @return DOCUMENT ME! */ public PLayer getRubberBandLayer() { return rubberBandLayer; } /** * Assigns a given PLayer to the variable rubberBandLayer. * * @param rubberBandLayer a PLayer */ public void setRubberBandLayer(final PLayer rubberBandLayer) { this.rubberBandLayer = rubberBandLayer; } /** * Sets new viewbounds. * * @param r2d Rectangle2D */ public void setNewViewBounds(final Rectangle2D r2d) { newViewBounds = r2d; } /** * Will be called if the selection of features changes. It selects the PFeatures connected to the selected features * of the featurecollectionevent and moves them to the front. Also repaints handles at the end. * * @param fce featurecollectionevent with selected features */ @Override public void featureSelectionChanged(final FeatureCollectionEvent fce) { final Collection<PFeature> all = featureLayer.getChildrenReference(); for (final PFeature f : all) { f.setSelected(false); } Collection<Feature> c; if (fce != null) { c = fce.getFeatureCollection().getSelectedFeatures(); } else { c = featureCollection.getSelectedFeatures(); } ////handle featuregroup select-delegation//// final Set<Feature> selectionResult = TypeSafeCollections.newHashSet(); for (final Feature current : c) { if (current instanceof FeatureGroup) { selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current)); } else { selectionResult.add(current); } } ///////////////////////////////////////////// c = selectionResult; for (final Feature f : c) { if (f != null) { final PFeature feature = (PFeature)getPFeatureHM().get(f); if (feature != null) { feature.setSelected(true); feature.moveToFront(); // Fuer den selectedObjectPresenter (Eigener PCanvas) syncSelectedObjectPresenter(1000); } else { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } } showHandles(false); } /** * Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on * each feature of the given featurecollectionevent. Repaints handles at the end. * * @param fce featurecollectionevent with changed features */ @Override public void featuresChanged(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("featuresChanged"); // NOI18N } } final List<Feature> list = new ArrayList<Feature>(); list.addAll(fce.getEventFeatures()); for (final Feature elem : list) { reconsiderFeature(elem); } showHandles(false); } /** * Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls * following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode() * * @param fce featurecollectionevent with features to reconsile */ @Override public void featureReconsiderationRequested(final FeatureCollectionEvent fce) { for (final Feature f : fce.getEventFeatures()) { if (f != null) { final PFeature node = pFeatureHM.get(f); if (node != null) { node.syncGeometry(); node.visualize(); node.resetInfoNodePosition(); node.refreshInfoNode(); repaint(); // für Mehrfachzeichnung der Handles verantworlich ?? // showHandles(false); } } } } /** * Adds all features from the FeatureCollectionEvent to the mappingcomponent. Paints handles at the end. Former * synchronized method. * * @param fce FeatureCollectionEvent with features to add */ @Override public void featuresAdded(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("firefeaturesAdded (old disabled)"); // NOI18N } } // Attention: Bug-Gefahr !!! TODO // addFeaturesToMap(fce.getEventFeatures().toArray(new Feature[0])); // if(DEBUG)log.debug("featuresAdded()"); } /** * Method is deprecated and deactivated. Does nothing!! * * @deprecated DOCUMENT ME! */ @Override @Deprecated public void featureCollectionChanged() { // if (getFeatureCollection() instanceof DefaultFeatureCollection) { // DefaultFeatureCollection coll=((DefaultFeatureCollection)getFeatureCollection()); // Vector<String> layers=coll.getAllLayers(); // for (String layer :layers) { // if (!featureLayers.keySet().contains(layer)) { // PLayer pLayer=new PLayer(); // featureLayer.addChild(pLayer); // featureLayers.put(layer,pLayer); // } // } // } } /** * Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a * checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent. * * @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice */ @Override public void allFeaturesRemoved(final FeatureCollectionEvent fce) { for (final PFeature feature : pFeatureHM.values()) { feature.cleanup(); } stickyPNodes.clear(); pFeatureHM.clear(); featureLayer.removeAllChildren(); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); } /** * Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining * supporting rasterservices and paints handles at the end. * * @param fce FeatureCollectionEvent with features to remove */ @Override public void featuresRemoved(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("featuresRemoved"); // NOI18N } } removeFeatures(fce.getEventFeatures()); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); showHandles(false); } /** * Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and * which need a refresh. * * @param fce FeatureCollectionEvent with removed features */ private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) { final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>(); for (final Feature f : getFeatureCollection().getAllFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } rasterServices.add(rs); // DANGER } } for (final Feature f : fce.getEventFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } if (rasterServices.contains(rs)) { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r); } } } else { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r); } } } } } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) { getMappingModel().removeLayer(frs); } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) { handleMapService(0, frs, true); } } // public void showFeatureCollection(Feature[] features) { // com.vividsolutions.jts.geom.Envelope env=computeFeatureEnvelope(features); // showFeatureCollection(features,env); // } // public void showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { // selectedFeature=null; // handleLayer.removeAllChildren(); // //setRasterServiceLayerImagesVisibility(false); // Envelope eSquare=null; // HashSet<Feature> featureSet=new HashSet<Feature>(); // featureSet.addAll(holdFeatures); // featureSet.addAll(java.util.Arrays.asList(f)); // Feature[] features=featureSet.toArray(new Feature[0]); // // pFeatureHM.clear(); // addFeaturesToMap(features); // zoomToFullFeatureCollectionBounds(); // // } /** * Creates new PFeatures for all features in the given array and adds them to the PFeatureHashmap. Then adds the * PFeature to the featurelayer. * * <p>DANGER: there's a bug risk here because the method runs in an own thread! It is possible that a PFeature of a * feature is demanded but not yet added to the hashmap which causes in most cases a NullPointerException!</p> * * @param features array with features to add */ public void addFeaturesToMap(final Feature[] features) { // Runnable r = new Runnable() { // // @Override // public void run() { final double local_clip_offset_y = clip_offset_y; final double local_clip_offset_x = clip_offset_x; /// Hier muss der layer bestimmt werdenn for (int i = 0; i < features.length; ++i) { final PFeature p = new PFeature( features[i], getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); try { if (features[i] instanceof StyledFeature) { p.setTransparency(((StyledFeature)(features[i])).getTransparency()); } else { p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); } } catch (Exception e) { p.setTransparency(0.8f); log.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N } // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) // PFeature p=new PFeature(features[i],(WorldToScreenTransform)null,(double)0,(double)0); p.setViewer(this); // ((PPath)p).setStroke(new BasicStroke(0.5f)); if (features[i].getGeometry() != null) { pFeatureHM.put(p.getFeature(), p); // for (int j = 0; j < p.getCoordArr().length; ++j) { // pFeatureHMbyCoordinate.put(p.getCoordArr()[j], new PFeatureCoordinatePosition(p, j)); // } final int ii = i; EventQueue.invokeLater(new Runnable() { @Override public void run() { featureLayer.addChild(p); if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { // p.moveToBack(); p.moveToFront(); } } }); } } EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodes(); repaint(); fireFeaturesAddedToMap(Arrays.asList(features)); // SuchFeatures in den Vordergrund stellen for (final Feature feature : featureCollection.getAllFeatures()) { if (feature instanceof SearchFeature) { final PFeature pFeature = pFeatureHM.get(feature); pFeature.moveToFront(); } } } }); // } // }; // CismetThreadPool.execute(r); // check whether the feature has a rasterSupportLayer or not for (final Feature f : features) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (!getMappingModel().getRasterServices().containsValue(rs)) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureAwareRasterServiceAdded"); // NOI18N } } rs.setFeatureCollection(getFeatureCollection()); getMappingModel().addLayer(rs); } } } showHandles(false); } // public void addFeaturesToMap(final Feature[] features) { // Runnable r = new Runnable() { // // @Override // public void run() { // double local_clip_offset_y = clip_offset_y; // double local_clip_offset_x = clip_offset_x; // // /// Hier muss der layer bestimmt werdenn // for (int i = 0; i < features.length; ++i) { // final PFeature p = new PFeature(features[i], getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); // try { // if (features[i] instanceof StyledFeature) { // p.setTransparency(((StyledFeature) (features[i])).getTransparency()); // } else { // p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); // } // } catch (Exception e) { // p.setTransparency(0.8f); // log.info("Fehler beim Setzen der Transparenzeinstellungen", e); // } // // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) // // PFeature p=new PFeature(features[i],(WorldToScreenTransform)null,(double)0,(double)0); // // p.setViewer(this); // // ((PPath)p).setStroke(new BasicStroke(0.5f)); // if (features[i].getGeometry() != null) { // pFeatureHM.put(p.getFeature(), p); // for (int j = 0; j < p.getCoordArr().length; ++j) { // pFeatureHMbyCoordinate.put(p.getCoordArr()[j], new PFeatureCoordinatePosition(p, j)); // } // final int ii = i; // EventQueue.invokeLater(new Runnable() { // // @Override // public void run() { // featureLayer.addChild(p); // if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { // //p.moveToBack(); // p.moveToFront(); // } // } // }); // } // } // EventQueue.invokeLater(new Runnable() { // // @Override // public void run() { // rescaleStickyNodes(); // repaint(); // fireFeaturesAddedToMap(Arrays.asList(features)); // // // SuchFeatures in den Vordergrund stellen // for (Feature feature : featureCollection.getAllFeatures()) { // if (feature instanceof SearchFeature) { // PFeature pFeature = (PFeature)pFeatureHM.get(feature); // pFeature.moveToFront(); // } // } // } // }); // } // }; // CismetThreadPool.execute(r); // // //check whether the feature has a rasterSupportLayer or not // for (Feature f : features) { // if (f instanceof RasterLayerSupportedFeature && ((RasterLayerSupportedFeature) f).getSupportingRasterService() != null) { // FeatureAwareRasterService rs = ((RasterLayerSupportedFeature) f).getSupportingRasterService(); // if (!getMappingModel().getRasterServices().containsValue(rs)) { // if (DEBUG) { // log.debug("FeatureAwareRasterServiceAdded"); // } // rs.setFeatureCollection(getFeatureCollection()); // getMappingModel().addLayer(rs); // } // } // } // // showHandles(false); // } /** * DOCUMENT ME! * * @param cf DOCUMENT ME! */ private void fireFeaturesAddedToMap(final Collection<Feature> cf) { for (final MapListener curMapListener : mapListeners) { curMapListener.featuresAddedToMap(cf); } } /** * Returns a list of PFeatureCoordinatePositions which are located at the given coordinate. * * @param features c Coordinate * * @return list of PFeatureCoordinatePositions */ // public List<PFeatureCoordinatePosition> getPFeaturesByCoordinates(Coordinate c) { // List<PFeatureCoordinatePosition> l = (List<PFeatureCoordinatePosition>) pFeatureHMbyCoordinate.get(c); // return l; // } /** * Creates an envelope around all features from the given array. * * @param features features to create the envelope around * * @return Envelope com.vividsolutions.jts.geom.Envelope */ private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) { final PNode root = new PNode(); for (int i = 0; i < features.length; ++i) { final PNode p = PNodeFactory.createPFeature(features[i], this); if (p != null) { root.addChild(p); } } final PBounds ext = root.getFullBounds(); final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope( ext.x, ext.x + ext.width, ext.y, ext.y + ext.height); return env; } /** * Zooms in / out to match the bounds of the featurecollection. */ public void zoomToFullFeatureCollectionBounds() { zoomToFeatureCollection(); } /** * Adds a new cursor to the cursor-hashmap. * * @param mode interactionmode as string * @param cursor cursor-object */ public void putCursor(final String mode, final Cursor cursor) { cursors.put(mode, cursor); } /** * Returns the cursor assigned to the given mode. * * @param mode mode as String * * @return Cursor-object or null */ public Cursor getCursor(final String mode) { return cursors.get(mode); } /** * Adds a new PBasicInputEventHandler for a specific interactionmode. * * @param mode interactionmode as string * @param listener new PBasicInputEventHandler */ public void addInputListener(final String mode, final PBasicInputEventHandler listener) { inputEventListener.put(mode, listener); } /** * Returns the PBasicInputEventHandler assigned to the committed interactionmode. * * @param mode interactionmode as string * * @return PBasicInputEventHandler-object or null */ public PInputEventListener getInputListener(final String mode) { final Object o = inputEventListener.get(mode); if (o instanceof PInputEventListener) { return (PInputEventListener)o; } else { return null; } } /** * Returns whether the features are editable or not. * * @return DOCUMENT ME! */ public boolean isReadOnly() { return readOnly; } /** * Sets all Features ReadOnly use Feature.setEditable(boolean) instead. * * @param readOnly DOCUMENT ME! */ public void setReadOnly(final boolean readOnly) { for (final Object f : featureCollection.getAllFeatures()) { ((Feature)f).setEditable(!readOnly); } this.readOnly = readOnly; handleLayer.repaint(); // if (readOnly==false) { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } snapHandleLayer.removeAllChildren(); // } } /** * Returns the current HandleInteractionMode. * * @return DOCUMENT ME! */ public String getHandleInteractionMode() { return handleInteractionMode; } /** * Changes the HandleInteractionMode. Repaints handles. * * @param handleInteractionMode the new HandleInteractionMode */ public void setHandleInteractionMode(final String handleInteractionMode) { this.handleInteractionMode = handleInteractionMode; showHandles(false); } /** * Returns whether the background is enabled or not. * * @return DOCUMENT ME! */ public boolean isBackgroundEnabled() { return backgroundEnabled; } /** * TODO. * * @param backgroundEnabled DOCUMENT ME! */ public void setBackgroundEnabled(final boolean backgroundEnabled) { if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) { featureServiceLayerVisible = featureServiceLayer.getVisible(); } this.mapServicelayer.setVisible(backgroundEnabled); this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible); } if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) { this.queryServices(); } this.backgroundEnabled = backgroundEnabled; } /** * Returns the featurelayer. * * @return DOCUMENT ME! */ public PLayer getFeatureLayer() { return featureLayer; } /** * Adds a PFeature to the PFeatureHashmap. * * @param p PFeature to add */ public void refreshHM(final PFeature p) { pFeatureHM.put(p.getFeature(), p); } /** * Returns the selectedObjectPresenter (PCanvas). * * @return DOCUMENT ME! */ public PCanvas getSelectedObjectPresenter() { return selectedObjectPresenter; } /** * If f != null it calls the reconsiderFeature()-method of the featurecollection. * * @param f feature to reconcile */ public void reconsiderFeature(final Feature f) { if (f != null) { featureCollection.reconsiderFeature(f); } } /** * Removes all features of the collection from the hashmap. * * @param fc collection of features to remove */ public void removeFeatures(final Collection<Feature> fc) { featureLayer.setVisible(false); for (final Feature elem : fc) { removeFromHM(elem); } featureLayer.setVisible(true); } /** * Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key. * * @param f feature of the Pfeature that should be deleted */ public void removeFromHM(final Feature f) { final PFeature pf = pFeatureHM.get(f); if (pf != null) { pf.cleanup(); pFeatureHM.remove(f); stickyPNodes.remove(pf); try { log.info("Entferne Feature " + f); // NOI18N featureLayer.removeChild(pf); } catch (Exception ex) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N } } } } else { log.warn("Feature war nicht in pFeatureHM"); // NOI18N } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("pFeatureHM" + pFeatureHM); // NOI18N } } } /** * Zooms to the current selected node. * * @deprecated DOCUMENT ME! */ public void zoomToSelectedNode() { zoomToSelection(); } /** * Zooms to the current selected features. */ public void zoomToSelection() { final Collection<Feature> selection = featureCollection.getSelectedFeatures(); zoomToAFeatureCollection(selection, true, false); } /** * Zooms to a specific featurecollection. * * @param collection the featurecolltion * @param withHistory should the zoomaction be undoable * @param fixedScale fixedScale */ public void zoomToAFeatureCollection(final Collection<Feature> collection, final boolean withHistory, final boolean fixedScale) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("zoomToAFeatureCollection"); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } boolean first = true; Geometry g = null; for (final Feature f : collection) { if (first) { g = f.getGeometry().getEnvelope(); if (f instanceof Bufferable) { g = g.buffer(((Bufferable)f).getBuffer()); } first = false; } else { if (f.getGeometry() != null) { Geometry geometry = f.getGeometry().getEnvelope(); if (f instanceof Bufferable) { geometry = geometry.buffer(((Bufferable)f).getBuffer()); } g = g.getEnvelope().union(geometry); } } } if (g != null) { // dreisatz.de final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10; final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10; if ((getHeight() == 0) || (getWidth() == 0)) { log.fatal("DIVISION BY ZERO"); // NOI18N } double buff = 0; if (hBuff > vBuff) { buff = hBuff; } else { buff = vBuff; } g = g.buffer(buff); final BoundingBox bb = new BoundingBox(g); gotoBoundingBox(bb, withHistory, !fixedScale, animationDuration); } } /** * Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create * their handles and to add them to the handlelayer. * * @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles */ public void showHandles(final boolean waitTillAllAnimationsAreComplete) { // are there features selected? if (featureCollection.getSelectedFeatures().size() > 0) { // DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf final Runnable handle = new Runnable() { @Override public void run() { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); while (getAnimating() && waitTillAllAnimationsAreComplete) { try { Thread.currentThread().sleep(10); } catch (Exception e) { log.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (featureCollection.areFeaturesEditable() && (getInteractionMode().equals(SELECT) || getInteractionMode().equals(LINEMEASUREMENT) || getInteractionMode().equals(PAN) || getInteractionMode().equals(ZOOM) || getInteractionMode().equals(ALKIS_PRINT) || getInteractionMode().equals(SPLIT_POLYGON))) { // Handles für alle selektierten Features der Collection hinzufügen if (getHandleInteractionMode().equals(ROTATE_POLYGON)) { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature instanceof Feature) && ((Feature)selectedFeature).isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { ((PFeature)pFeatureHM.get(selectedFeature)).addRotationHandles( handleLayer); } }); } else { log.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } } } } else { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature != null) && selectedFeature.isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { try { ((PFeature)pFeatureHM.get(selectedFeature)).addHandles( handleLayer); } catch (Exception e) { log.error("Error bei addHandles: ", e); // NOI18N } } }); } else { log.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } // DANGER mit break werden nur die Handles EINES slektierten Features angezeigt // wird break auskommentiert werden jedoch zu viele Handles angezeigt break; } } } } } }; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("showHandles", new CurrentStackTrace()); // NOI18N } } CismetThreadPool.execute(handle); } else { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); } } /** * Will return a PureNewFeature if there is only one in the featurecollection else null. * * @return DOCUMENT ME! */ public PFeature getSolePureNewFeature() { int counter = 0; PFeature sole = null; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object o = it.next(); if (o instanceof PFeature) { if (((PFeature)o).getFeature() instanceof PureNewFeature) { ++counter; sole = ((PFeature)o); } } } if (counter == 1) { return sole; } else { return null; } } /** * Sets the visibility of the children of the rasterservicelayer. * * @param visible true sets visible */ private void setRasterServiceLayerImagesVisibility(final boolean visible) { final Iterator it = mapServicelayer.getChildrenIterator(); while (it.hasNext()) { final Object o = it.next(); if (o instanceof XPImage) { ((XPImage)o).setVisible(visible); } } } /** * Returns the temporary featurelayer. * * @return DOCUMENT ME! */ public PLayer getTmpFeatureLayer() { return tmpFeatureLayer; } /** * Assigns a new temporary featurelayer. * * @param tmpFeatureLayer PLayer */ public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) { this.tmpFeatureLayer = tmpFeatureLayer; } /** * Returns whether the grid is enabled or not. * * @return DOCUMENT ME! */ public boolean isGridEnabled() { return gridEnabled; } /** * Enables or disables the grid. * * @param gridEnabled true, to enable the grid */ public void setGridEnabled(final boolean gridEnabled) { this.gridEnabled = gridEnabled; } /** * Returns a String from two double-values. Serves the visualization. * * @param x X-coordinate * @param y Y-coordinate * * @return a Strin-object like "(X,Y)" */ public static String getCoordinateString(final double x, final double y) { final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N final DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); df.setDecimalFormatSymbols(dfs); return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHandleLayer() { return handleLayer; } /** * DOCUMENT ME! * * @param handleLayer DOCUMENT ME! */ public void setHandleLayer(final PLayer handleLayer) { this.handleLayer = handleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingEnabled() { return visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingEnabled DOCUMENT ME! */ public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) { this.visualizeSnappingEnabled = visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingRectEnabled() { return visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingRectEnabled DOCUMENT ME! */ public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) { this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getSnappingRectSize() { return snappingRectSize; } /** * DOCUMENT ME! * * @param snappingRectSize DOCUMENT ME! */ public void setSnappingRectSize(final int snappingRectSize) { this.snappingRectSize = snappingRectSize; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getSnapHandleLayer() { return snapHandleLayer; } /** * DOCUMENT ME! * * @param snapHandleLayer DOCUMENT ME! */ public void setSnapHandleLayer(final PLayer snapHandleLayer) { this.snapHandleLayer = snapHandleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isSnappingEnabled() { return snappingEnabled; } /** * DOCUMENT ME! * * @param snappingEnabled DOCUMENT ME! */ public void setSnappingEnabled(final boolean snappingEnabled) { this.snappingEnabled = snappingEnabled; setVisualizeSnappingEnabled(snappingEnabled); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getFeatureServiceLayer() { return featureServiceLayer; } /** * DOCUMENT ME! * * @param featureServiceLayer DOCUMENT ME! */ public void setFeatureServiceLayer(final PLayer featureServiceLayer) { this.featureServiceLayer = featureServiceLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getAnimationDuration() { return animationDuration; } /** * DOCUMENT ME! * * @param animationDuration DOCUMENT ME! */ public void setAnimationDuration(final int animationDuration) { this.animationDuration = animationDuration; } /** * DOCUMENT ME! * * @param prefs DOCUMENT ME! */ @Deprecated public void setPreferences(final CismapPreferences prefs) { log.warn("involing deprecated operation setPreferences()"); // NOI18N cismapPrefs = prefs; // DefaultMappingModel mm = new DefaultMappingModel(); final ActiveLayerModel mm = new ActiveLayerModel(); final LayersPreferences layersPrefs = prefs.getLayersPrefs(); final GlobalPreferences globalPrefs = prefs.getGlobalPrefs(); setSnappingRectSize(globalPrefs.getSnappingRectSize()); setSnappingEnabled(globalPrefs.isSnappingEnabled()); setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled()); setAnimationDuration(globalPrefs.getAnimationDuration()); setInteractionMode(globalPrefs.getStartMode()); // mm.setInitialBoundingBox(globalPrefs.getInitialBoundingBox()); mm.addHome(globalPrefs.getInitialBoundingBox()); final Crs crs = new Crs(); crs.setCode(globalPrefs.getInitialBoundingBox().getSrs()); crs.setName(globalPrefs.getInitialBoundingBox().getSrs()); crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs()); mm.setSrs(crs); final TreeMap raster = layersPrefs.getRasterServices(); if (raster != null) { final Iterator it = raster.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = raster.get(key); if (o instanceof MapService) { // mm.putMapService(((Integer) key).intValue(), (MapService) o); mm.addLayer((RetrievalServiceLayer)o); } } } final TreeMap features = layersPrefs.getFeatureServices(); if (features != null) { final Iterator it = features.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = features.get(key); if (o instanceof MapService) { // TODO // mm.putMapService(((Integer) key).intValue(), (MapService) o); mm.addLayer((RetrievalServiceLayer)o); } } } setMappingModel(mm); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public CismapPreferences getCismapPrefs() { return cismapPrefs; } /** * DOCUMENT ME! * * @param duration DOCUMENT ME! * @param animationDuration DOCUMENT ME! * @param what DOCUMENT ME! * @param number DOCUMENT ME! */ public void flash(final int duration, final int animationDuration, final int what, final int number) { } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getDragPerformanceImproverLayer() { return dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @param dragPerformanceImproverLayer DOCUMENT ME! */ public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) { this.dragPerformanceImproverLayer = dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public PLayer getRasterServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getMapServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @param rasterServiceLayer DOCUMENT ME! */ public void setRasterServiceLayer(final PLayer rasterServiceLayer) { this.mapServicelayer = rasterServiceLayer; } /** * DOCUMENT ME! * * @param f DOCUMENT ME! */ public void showGeometryInfoPanel(final Feature f) { } /** * Adds a PropertyChangeListener to the listener list. * * @param l The listener to add. */ @Override public void addPropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener from the listener list. * * @param l The listener to remove. */ @Override public void removePropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.removePropertyChangeListener(l); } /** * Setter for property taskCounter. former synchronized method */ public void fireActivityChanged() { propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N } /** * Returns true, if there's still one layercontrol running. Else false; former synchronized method * * @return DOCUMENT ME! */ public boolean isRunning() { for (final LayerControl lc : layerControls) { if (lc.isRunning()) { return true; } } return false; } /** * Sets the visibility of all infonodes. * * @param visible true, if infonodes should be visible */ public void setInfoNodesVisible(final boolean visible) { infoNodesVisible = visible; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object elem = it.next(); if (elem instanceof PFeature) { ((PFeature)elem).setInfoNodeVisible(visible); } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("setInfoNodesVisible()"); // NOI18N } } rescaleStickyNodes(); } /** * Adds an object to the historymodel. * * @param o Object to add */ @Override public void addToHistory(final Object o) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("addToHistory:" + o.toString()); // NOI18N } } historyModel.addToHistory(o); } /** * Removes a specific HistoryModelListener from the historymodel. * * @param hml HistoryModelListener */ @Override public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.removeHistoryModelListener(hml); } /** * Adds aHistoryModelListener to the historymodel. * * @param hml HistoryModelListener */ @Override public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.addHistoryModelListener(hml); } /** * Sets the maximum value of saved historyactions. * * @param max new integer value */ @Override public void setMaximumPossibilities(final int max) { historyModel.setMaximumPossibilities(max); } /** * Redos the last undone historyaction. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the forward-action */ @Override public Object forward(final boolean external) { final PBounds fwd = (PBounds)historyModel.forward(external); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("HistoryModel.forward():" + fwd); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(fwd); } return fwd; } /** * Undos the last action. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the back-action */ @Override public Object back(final boolean external) { final PBounds back = (PBounds)historyModel.back(external); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("HistoryModel.back():" + back); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(back); } return back; } /** * Returns true, if it's possible to redo an action. * * @return DOCUMENT ME! */ @Override public boolean isForwardPossible() { return historyModel.isForwardPossible(); } /** * Returns true, if it's possible to undo an action. * * @return DOCUMENT ME! */ @Override public boolean isBackPossible() { return historyModel.isBackPossible(); } /** * Returns a vector with all redo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getForwardPossibilities() { return historyModel.getForwardPossibilities(); } /** * Returns the current element of the historymodel. * * @return DOCUMENT ME! */ @Override public Object getCurrentElement() { return historyModel.getCurrentElement(); } /** * Returns a vector with all undo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getBackPossibilities() { return historyModel.getBackPossibilities(); } /** * Returns whether an internallayerwidget is available. * * @return DOCUMENT ME! */ @Deprecated public boolean isInternalLayerWidgetAvailable() { return this.getInternalWidget(LAYERWIDGET) != null; } /** * Sets the variable, if an internallayerwidget is available or not. * * @param internalLayerWidgetAvailable true, if available */ @Deprecated public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) { if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) { this.removeInternalWidget(LAYERWIDGET); } else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) { final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); } } @Override public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) { } /** * Removes the mapservice from the rasterservicelayer. * * @param rasterService the removing mapservice */ @Override public void mapServiceRemoved(final MapService rasterService) { try { mapServicelayer.removeChild(rasterService.getPNode()); System.gc(); } catch (Exception e) { log.warn("Fehler bei mapServiceRemoved", e); // NOI18N } } /** * Adds the commited mapservice on the last position to the rasterservicelayer. * * @param mapService the new mapservice */ @Override public void mapServiceAdded(final MapService mapService) { addMapService(mapService, mapServicelayer.getChildrenCount()); if (mapService instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection()); } if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) { handleMapService(0, mapService, false); } } /** * Returns the current OGC scale. * * @return DOCUMENT ME! */ public double getCurrentOGCScale() { // funktioniert nur bei metrischen SRS's final double h = getCamera().getViewBounds().getHeight() / getHeight(); final double w = getCamera().getViewBounds().getWidth() / getWidth(); // if(DEBUG)log.debug("H�he:"+getHeight()+" Breite:"+getWidth()); // if(DEBUG)log.debug("H�heReal:"+getCamera().getViewBounds().getHeight()+" BreiteReal:"+getCamera().getViewBounds().getWidth()); return Math.sqrt((h * h) + (w * w)); // Math.sqrt((getWidth()*getWidth())*2); } /** * Returns the current BoundingBox. * * @return DOCUMENT ME! */ public BoundingBox getCurrentBoundingBox() { if (fixedBoundingBox != null) { return fixedBoundingBox; } else { try { final PBounds bounds = getCamera().getViewBounds(); final double x1 = wtst.getWorldX(bounds.getX()); final double y1 = wtst.getWorldY(bounds.getY()); final double x2 = x1 + bounds.width; final double y2 = y1 - bounds.height; currentBoundingBox = new BoundingBox(x1, y1, x2, y2); // if(DEBUG)log.debug("getCurrentBoundingBox()" + currentBoundingBox + "(" + (y2 - y1) + "," + (x2 - // x1) + ")", new CurrentStackTrace()); return currentBoundingBox; } catch (Throwable t) { log.error("Fehler in getCurrentBoundingBox()", t); // NOI18N return null; } } } /** * Returns a BoundingBox with a fixed size. * * @return DOCUMENT ME! */ public BoundingBox getFixedBoundingBox() { return fixedBoundingBox; } /** * Assigns fixedBoundingBox a new value. * * @param fixedBoundingBox new boundingbox */ public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) { this.fixedBoundingBox = fixedBoundingBox; } /** * Paints the outline of the forwarded BoundingBox. * * @param bb BoundingBox */ public void outlineArea(final BoundingBox bb) { outlineArea(bb, null); } /** * Paints the outline of the forwarded PBounds. * * @param b PBounds */ public void outlineArea(final PBounds b) { outlineArea(b, null); } /** * Paints a filled rectangle of the area of the forwarded BoundingBox. * * @param bb BoundingBox * @param fillingPaint Color to fill the rectangle */ public void outlineArea(final BoundingBox bb, final Paint fillingPaint) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } outlineArea(pb, fillingPaint); } /** * Paints a filled rectangle of the area of the forwarded PBounds. * * @param b PBounds to paint * @param fillingColor Color to fill the rectangle */ public void outlineArea(final PBounds b, final Paint fillingColor) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { highlightingLayer.removeAllChildren(); } } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(fillingColor); rectangle.setStroke(new FixedWidthStroke()); rectangle.setStrokePaint(new Color(100, 100, 100, 255)); rectangle.setPathTo(b); highlightingLayer.addChild(rectangle); } } /** * Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally. * * @param bb BoundingBox to highlight */ public void highlightArea(final BoundingBox bb) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } highlightArea(pb); } /** * Highlights the delivered PBounds by painting over with a transparent white. * * @param b PBounds to hightlight */ private void highlightArea(final PBounds b) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { } highlightingLayer.animateToTransparency(0, animationDuration); highlightingLayer.removeAllChildren(); } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(new Color(255, 255, 255, 100)); rectangle.setStroke(null); // rectangle.setStroke(new BasicStroke((float)(1/ getCamera().getViewScale()))); // rectangle.setStrokePaint(new Color(255,255,255,20)); rectangle.setPathTo(this.getCamera().getViewBounds()); highlightingLayer.addChild(rectangle); rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration); } } /** * Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls * crossHairPoint(Point p) internally. * * @param c coordinate of the crosshair's venue */ public void crossHairPoint(final Coordinate c) { Point p = null; if (c != null) { p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y)); } crossHairPoint(p); } /** * Paints a crosshair at the delivered point. * * @param p point of the crosshair's venue */ public void crossHairPoint(final Point p) { if (p == null) { if (crosshairLayer.getChildrenCount() > 0) { crosshairLayer.removeAllChildren(); } } else { crosshairLayer.removeAllChildren(); crosshairLayer.setTransparency(1); final PPath lineX = new PPath(); final PPath lineY = new PPath(); lineX.setStroke(new FixedWidthStroke()); lineX.setStrokePaint(new Color(100, 100, 100, 255)); lineY.setStroke(new FixedWidthStroke()); lineY.setStrokePaint(new Color(100, 100, 100, 255)); // PBounds current=getCurrentBoundingBox().getPBounds(getWtst()); final PBounds current = getCamera().getViewBounds(); final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1); final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2); lineX.setPathTo(x); crosshairLayer.addChild(lineX); lineY.setPathTo(y); crosshairLayer.addChild(lineY); } } @Override public Element getConfiguration() { if (log.isDebugEnabled()) { log.debug("writing configuration <cismapMappingPreferences>"); // NOI18N } final Element ret = new Element("cismapMappingPreferences"); // NOI18N ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N ret.setAttribute( "creationMode", ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N // Position final Element currentPosition = new Element("Position"); // NOI18N // if (Double.isNaN(getCurrentBoundingBox().getX1())|| // Double.isNaN(getCurrentBoundingBox().getX2())|| // Double.isNaN(getCurrentBoundingBox().getY1())|| // Double.isNaN(getCurrentBoundingBox().getY2())) { // log.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // gotoInitialBoundingBox(); // } currentPosition.addContent(currentBoundingBox.getJDOMElement()); currentPosition.setAttribute("CRS", CismapBroker.getInstance().getSrs().getCode()); // currentPosition.addContent(getCurrentBoundingBox().getJDOMElement()); ret.addContent(currentPosition); // Crs final Element crsListElement = new Element("crsList"); for (final Crs tmp : crsList) { crsListElement.addContent(tmp.getJDOMElement()); } ret.addContent(crsListElement); if (printingSettingsDialog != null) { ret.addContent(printingSettingsDialog.getConfiguration()); } // save internal widgets status final Element widgets = new Element("InternalWidgets"); // NOI18N for (final String name : this.internalWidgets.keySet()) { final Element widget = new Element("Widget"); // NOI18N widget.setAttribute("name", name); // NOI18N widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N widgets.addContent(widget); } ret.addContent(widgets); return ret; } @Override public void masterConfigure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N // CRS List try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); crsList.add(s); if (s.isSelected() && s.isMetric()) { try { transformer = new CrsTransformer(s.getCode()); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (Exception skip) { log.error("Error while reading the crs list", skip); // NOI18N } if (transformer == null) { log.warn("No metric default crs found. Use EPSG:31466 to calculate geometry lengths and scales"); try { transformer = new CrsTransformer("EPSG:31466"); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); } } // HOME try { if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N } } while (it.hasNext()) { final Element elem = it.next(); final String srs = elem.getAttribute("srs").getValue(); // NOI18N boolean metric = false; try { metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { log.warn("Metric hat falschen Syntax", dce); // NOI18N } boolean defaultVal = false; try { defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { log.warn("default hat falschen Syntax", dce); // NOI18N } final XBoundingBox xbox = new XBoundingBox(elem, srs, metric); alm.addHome(xbox); if (defaultVal) { Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(srs)) { crsObject = tmp; break; } } if (crsObject == null) { log.error("CRS " + srs + " from the default home is not found in the crs list"); crsObject = new Crs(srs, srs, srs, true, false); crsList.add(crsObject); } alm.setSrs(crsObject); alm.setDefaultSrs(crsObject); CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } } } } catch (Throwable t) { log.error("Fehler beim MasterConfigure der MappingComponent", t); // NOI18N } try { final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N scales.clear(); for (final Object elem : scalesList) { if (elem instanceof Element) { final Scale s = new Scale((Element)elem); scales.add(s); } } } catch (Exception skip) { log.error("Fehler beim Lesen von Scale", skip); // NOI18N } // Und jetzt noch die PriningEinstellungen initPrintingDialogs(); printingSettingsDialog.masterConfigure(prefs); } /** * Configurates this MappingComponent. * * @param e JDOM-Element with configuration */ @Override public void configure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); if (!crsList.contains(s)) { crsList.add(s); } if (s.isSelected() && s.isMetric()) { try { transformer = new CrsTransformer(s.getCode()); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (Exception skip) { log.error("Error while reading the crs list", skip); // NOI18N } // InteractionMode try { final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N setInteractionMode(interactMode); if (interactMode.equals(MappingComponent.NEW_POLYGON)) { try { final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode); } catch (Throwable t) { log.warn("Fehler beim Setzen des CreationInteractionMode", t); // NOI18N } } } catch (Throwable t) { log.warn("Fehler beim Setzen des InteractionMode", t); // NOI18N } try { final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N setHandleInteractionMode(handleInterMode); } catch (Throwable t) { log.warn("Fehler beim Setzen des HandleInteractionMode", t); // NOI18N } try { final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N log.info("snapping=" + snapping); // NOI18N setSnappingEnabled(snapping); setVisualizeSnappingEnabled(snapping); setInGlueIdenticalPointsMode(snapping); } catch (Throwable t) { log.warn("Fehler beim setzen von snapping und Konsorten", t); // NOI18N } // aktuelle Position try { final Element pos = prefs.getChild("Position"); // NOI18N final BoundingBox b = new BoundingBox(pos); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Position:" + b); // NOI18N } } final PBounds pb = b.getPBounds(getWtst()); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("PositionPb:" + pb); // NOI18N } } if (Double.isNaN(b.getX1()) || Double.isNaN(b.getX2()) || Double.isNaN(b.getY1()) || Double.isNaN(b.getY2())) { log.fatal("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N // gotoInitialBoundingBox(); this.currentBoundingBox = getMappingModel().getInitialBoundingBox(); final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); addToHistory(new PBoundsWithCleverToString( new PBounds(currentBoundingBox.getPBounds(wtst)), wtst, crsCode)); } else { // set the current crs final Attribute crsAtt = pos.getAttribute("CRS"); if (crsAtt != null) { final String currentCrs = crsAtt.getValue(); Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(currentCrs)) { crsObject = tmp; break; } } if (crsObject == null) { log.error("CRS " + currentCrs + " from the position element is not found in the crs list"); } final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); if (alm instanceof ActiveLayerModel) { alm.setSrs(crsObject); } CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } this.currentBoundingBox = b; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("added to History" + b); // NOI18N } } final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); // addToHistory(new PBoundsWithCleverToString(new PBounds(currentBoundingBox.getPBounds(wtst)), wtst, crsCode )); // final BoundingBox bb=b; // EventQueue.invokeLater(new Runnable() { // public void run() { // gotoBoundingBoxWithHistory(bb); // } // }); } } catch (Throwable t) { log.error("Fehler beim lesen der aktuellen Position", t); // NOI18N // EventQueue.invokeLater(new Runnable() { // public void run() { // gotoBoundingBoxWithHistory(getMappingModel().getInitialBoundingBox()); this.currentBoundingBox = getMappingModel().getInitialBoundingBox(); // } // }); } if (printingSettingsDialog != null) { printingSettingsDialog.configure(prefs); } try { final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N if (widgets != null) { for (final Object widget : widgets.getChildren()) { final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N this.showInternalWidget(name, visible, 0); } } } catch (Throwable t) { log.warn("could not enable internal widgets: " + t, t); // NOI18N } } /** * Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent * will only pan to the featurecollection and not zoom. * * @param fixedScale true, if zoom is not allowed */ public void zoomToFeatureCollection(final boolean fixedScale) { zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale); } /** * Zooms to all features of the mappingcomponents featurecollection. */ public void zoomToFeatureCollection() { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("zoomToFeatureCollection"); // NOI18N } } zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration) { gotoBoundingBox(bb, history, scaleToFit, animationDuration, true); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation * @param queryServices true, if the services should be refreshed after animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration, final boolean queryServices) { if (bb != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } final double x1 = getWtst().getScreenX(bb.getX1()); final double y1 = getWtst().getScreenY(bb.getY1()); final double x2 = getWtst().getScreenX(bb.getX2()); final double y2 = getWtst().getScreenY(bb.getY2()); final double w; final double h; final Rectangle2D pos = new Rectangle2D.Double(); pos.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { log.fatal("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } showHandles(true); final Runnable handle = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(10); } catch (Exception e) { log.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (history) { if ((x1 == x2) || (y1 == y2) || !scaleToFit) { setNewViewBounds(getCamera().getViewBounds()); } else { setNewViewBounds(pos); } if (queryServices) { queryServices(); } } else { if (queryServices) { queryServicesWithoutHistory(); } } } }; CismetThreadPool.execute(handle); } else { log.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N } } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) { gotoBoundingBox(bb, false, true, animationDuration); } /** * Moves the view to the target Boundingbox and saves the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithHistory(final BoundingBox bb) { gotoBoundingBox(bb, true, true, animationDuration); } /** * Returns a BoundingBox of the current view in another scale. * * @param scaleDenominator specific target scale * * @return DOCUMENT ME! */ public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) { return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBox()); } /** * Returns the BoundingBox of the delivered BoundingBox in another scale. * * @param scaleDenominator specific target scale * @param bb source BoundingBox * * @return DOCUMENT ME! */ public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) { final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator; final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator; if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { // transform the given bounding box to a metric coordinate system bb = transformer.transformBoundingBox(bb, CismapBroker.getInstance().getSrs().getCode()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2); final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2); BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2), midY - (realWorldHeightInMeter / 2), midX + (realWorldWidthInMeter / 2), midY + (realWorldHeightInMeter / 2)); if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { // transform the scaled bounding box to the current coordinate system final CrsTransformer trans = new CrsTransformer(CismapBroker.getInstance().getSrs().getCode()); scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } return scaledBox; } /** * Calculate the current scaledenominator. * * @return DOCUMENT ME! */ public double getScaleDenominator() { BoundingBox boundingBox = getCurrentBoundingBox(); final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { boundingBox = transformer.transformBoundingBox( boundingBox, CismapBroker.getInstance().getSrs().getCode()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } final double realWorldWidthInMeter = boundingBox.getWidth(); final double realWorldHeightInMeter = boundingBox.getHeight(); return realWorldWidthInMeter / screenWidthInMeter; } // public static Image getFeatureImage(Feature f){ // MappingComponent mc=new MappingComponent(); // mc.setSize(100,100); // pc.setInfoNodesVisible(true); // pc.setSize(100,100); // PFeature pf=new PFeature(pnf,new WorldToScreenTransform(0,0),0,0,null); // pc.getLayer().addChild(pf); // pc.getCamera().animateViewToCenterBounds(pf.getBounds(),true,0); // i=new ImageIcon(pc.getCamera().toImage(100,100,getBackground())); // } /** * Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code> * DropTarget</code> registered with this listener. * * <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code> * DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data * object(s) to be transfered.</p> * * <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int * dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P> * * <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be * invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData() * method.</P> * * <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the * drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method.</P> * * <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code> * Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only * if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code> * true</code>. Otherwise, the behavior of the call is implementation-dependent.</P> * * @param dtde the <code>DropTargetDropEvent</code> */ @Override public void drop(final DropTargetDropEvent dtde) { if (isDropEnabled(dtde)) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDropOnMap(mde); } catch (NoninvertibleTransformException ex) { log.error(ex, ex); } } } /** * DOCUMENT ME! * * @param dtde DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean isDropEnabled(final DropTargetDropEvent dtde) { if (ALKIS_PRINT.equals(getInteractionMode())) { for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) { // necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) { return false; } } } return true; } /** * Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site * for the <code>DropTarget</code> registered with this listener. * * @param dte the <code>DropTargetEvent</code> */ @Override public void dragExit(final DropTargetEvent dte) { } /** * Called if the user has modified the current drop gesture. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dropActionChanged(final DropTargetDragEvent dtde) { } /** * Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p * site for the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragOver(final DropTargetDragEvent dtde) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); // TODO: this seems to be buggy! final Point p = dtde.getLocation(); // Point2D p2d; // double scale = 1 / getCamera().getViewScale(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDragOverMap(mde); } catch (NoninvertibleTransformException ex) { log.error(ex, ex); } // MapDnDEvent mde = new MapDnDEvent(); // mde.setDte(dtde); // Point p = dtde.getLocation(); // double scale = 1/getCamera().getViewScale(); // mde.setXPos(getWtst().getWorldX(p.getX() * scale)); // mde.setYPos(getWtst().getWorldY(p.getY() * scale)); // CismapBroker.getInstance().fireDragOverMap(mde); } /** * Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for * the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragEnter(final DropTargetDragEvent dtde) { } /** * Returns the PfeatureHashmap which assigns a Feature to a PFeature. * * @return DOCUMENT ME! */ public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() { return pFeatureHM; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapExtent() { return fixedMapExtent; } /** * DOCUMENT ME! * * @param fixedMapExtent DOCUMENT ME! */ public void setFixedMapExtent(final boolean fixedMapExtent) { this.fixedMapExtent = fixedMapExtent; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapScale() { return fixedMapScale; } /** * DOCUMENT ME! * * @param fixedMapScale DOCUMENT ME! */ public void setFixedMapScale(final boolean fixedMapScale) { this.fixedMapScale = fixedMapScale; } /** * DOCUMENT ME! * * @param one DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public void selectPFeatureManually(final PFeature one) { // throw new UnsupportedOperationException("Not yet implemented"); if (one != null) { featureCollection.select(one.getFeature()); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public PFeature getSelectedNode() { // gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist // deshalb gebe ich mal nur das erste zur�ck if (featureCollection.getSelectedFeatures().size() > 0) { final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0]; if (selF == null) { return null; } return pFeatureHM.get(selF); } else { return null; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInfoNodesVisible() { return infoNodesVisible; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getPrintingFrameLayer() { return printingFrameLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PrintingSettingsWidget getPrintingSettingsDialog() { return printingSettingsDialog; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInGlueIdenticalPointsMode() { return inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @param inGlueIdenticalPointsMode DOCUMENT ME! */ public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) { this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHighlightingLayer() { return highlightingLayer; } /** * DOCUMENT ME! * * @param anno DOCUMENT ME! */ public void setPointerAnnotation(final PNode anno) { ((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno); } /** * DOCUMENT ME! * * @param visib DOCUMENT ME! */ public void setPointerAnnotationVisibility(final boolean visib) { if (getInputListener(MOTION) != null) { ((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib); } } /** * Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't * equal MOTION. * * @return DOCUMENT ME! */ public boolean isPointerAnnotationVisible() { if (getInputListener(MOTION) != null) { return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible(); } else { return false; } } /** * Returns a vector with different scales. * * @return DOCUMENT ME! */ public List<Scale> getScales() { return scales; } /** * Returns a list with different crs. * * @return DOCUMENT ME! */ public List<Crs> getCrsList() { return crsList; } /** * DOCUMENT ME! * * @return a transformer with the default crs as destination crs. The default crs is the first crs in the * configuration file that has set the selected attribut on true). This crs must be metric. */ public CrsTransformer getMetricTransformer() { return transformer; } /** * Locks the MappingComponent. */ public void lock() { locked = true; } /** * Unlocks the MappingComponent. */ public void unlock() { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("unlock"); // NOI18N } } locked = false; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N } } gotoBoundingBoxWithHistory(currentBoundingBox); } /** * Returns whether the MappingComponent is locked or not. * * @return DOCUMENT ME! */ public boolean isLocked() { return locked; } /** * Returns the MementoInterface for redo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemRedo() { return memRedo; } /** * Returns the MementoInterface for undo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemUndo() { return memUndo; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public HashMap<String, PBasicInputEventHandler> getInputEventListener() { return inputEventListener; } /** * DOCUMENT ME! * * @param inputEventListener DOCUMENT ME! */ public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) { this.inputEventListener.clear(); this.inputEventListener.putAll(inputEventListener); } @Override public void crsChanged(final CrsChangedEvent event) { if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) { if (locked) { return; } try { final BoundingBox bbox = getCurrentBoundingBox(); // getCurrentBoundingBox(); final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode()); final BoundingBox newBbox = crsTransformer.transformBoundingBox(bbox, event.getFormerCrs().getCode()); if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); } wtst = null; getWtst(); gotoBoundingBoxWithoutHistory(newBbox); // transform all features for (final Feature f : featureCollection.getAllFeatures()) { final Geometry geom = crsTransformer.transformGeometry(f.getGeometry(), event.getFormerCrs().getCode()); f.setGeometry(geom); final PFeature feature = pFeatureHM.get(f); feature.setFeature(f); Coordinate[] coordArray = feature.getCoordArr(); coordArray = crsTransformer.transformGeometry(coordArray, event.getFormerCrs().getCode()); feature.setCoordArr(coordArray); } final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures()); // list.add(f); removeFeatures(list); addFeaturesToMap(list.toArray(new Feature[list.size()])); } catch (Exception e) { JOptionPane.showMessageDialog( this, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"), JOptionPane.ERROR_MESSAGE); log.error("Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e); resetCrs = true; CismapBroker.getInstance().setSrs(event.getFormerCrs()); } } else { resetCrs = false; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public JInternalFrame getInternalWidget(final String name) { if (this.internalWidgets.containsKey(name)) { return this.internalWidgets.get(name); } else { log.warn("unknown internal widget '" + name + "'"); // NOI18N return null; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public int getInternalWidgetPosition(final String name) { if (this.internalWidgetPositions.containsKey(name)) { return this.internalWidgetPositions.get(name); } else { log.warn("unknown position for '" + name + "'"); // NOI18N return -1; } } //~ Inner Classes ---------------------------------------------------------- /** * /////////////////////////////////////////////// CLASS MappingComponentRasterServiceListener // * ///////////////////////////////////////////////. * * @version $Revision$, $Date$ */ private class MappingComponentRasterServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private Logger logger = Logger.getLogger(this.getClass()); private int position = -1; private XPImage pi = null; private ServiceLayer rasterService = null; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentRasterServiceListener object. * * @param position DOCUMENT ME! * @param pn DOCUMENT ME! * @param rasterService DOCUMENT ME! */ public MappingComponentRasterServiceListener(final int position, final PNode pn, final ServiceLayer rasterService) { this.position = position; if (pn instanceof XPImage) { this.pi = (XPImage)pn; } this.rasterService = rasterService; } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { fireActivityChanged(); if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } } @Override public void retrievalProgress(final RetrievalEvent e) { } @Override public void retrievalError(final RetrievalEvent e) { this.logger.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() + " Errors: " + e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N fireActivityChanged(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } } @Override public void retrievalComplete(final RetrievalEvent e) { final Point2D localOrigin = getCamera().getViewBounds().getOrigin(); final double localScale = getCamera().getViewScale(); final PBounds localBounds = getCamera().getViewBounds(); final Object o = e.getRetrievedObject(); // log.fatal(localBounds+ " "+localScale); if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } final Runnable paintImageOnMap = new Runnable() { @Override public void run() { fireActivityChanged(); if ((o instanceof Image) && (e.isHasErrors() == false)) { // TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden if (isBackgroundEnabled()) { // Image i=Static2DTools.toCompatibleImage((Image)o); final Image i = (Image)o; if (rasterService.getName().startsWith("prefetching")) { // NOI18N final double x = localOrigin.getX() - localBounds.getWidth(); final double y = localOrigin.getY() - localBounds.getHeight(); pi.setImage(i, 0); pi.setScale(3 / localScale); pi.setOffset(x, y); } else { pi.setImage(i, 1000); pi.setScale(1 / localScale); pi.setOffset(localOrigin); MappingComponent.this.repaint(); } } } } }; if (EventQueue.isDispatchThread()) { paintImageOnMap.run(); } else { EventQueue.invokeLater(paintImageOnMap); } } @Override public void retrievalAborted(final RetrievalEvent e) { this.logger.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getPosition() { return position; } /** * DOCUMENT ME! * * @param position DOCUMENT ME! */ public void setPosition(final int position) { this.position = position; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class DocumentProgressListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private Logger logger = Logger.getLogger(this.getClass()); private long requestId = -1; /** Displays the loading progress of Documents, e.g. SHP Files */ private final DocumentProgressWidget documentProgressWidget = new DocumentProgressWidget(); //~ Constructors ------------------------------------------------------- /** * Creates a new DocumentProgressListener object. */ public DocumentProgressListener() { documentProgressWidget.setVisible(false); if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) { MappingComponent.this.addInternalWidget( MappingComponent.PROGRESSWIDGET, MappingComponent.POSITION_SOUTHWEST, documentProgressWidget); } } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != -1) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = e.getRequestIdentifier(); this.documentProgressWidget.setServiceName(e.getRetrievalService().toString()); this.documentProgressWidget.setProgress(-1); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100); // MappingComponent.this.showInternalWidget(ZOOM, DEBUG, animationDuration); // MappingComponent.this.isInternalWidgetVisible(ZOOM); } @Override public void retrievalProgress(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: initialisation progress: " + e.getPercentageDone()); // NOI18N } } this.documentProgressWidget.setProgress(e.getPercentageDone()); } @Override public void retrievalComplete(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N } e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(100); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200); } @Override public void retrievalAborted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N } // e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } @Override public void retrievalError(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; e.getRetrievalService().removeRetrievalListener(this); this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public long getRequestId() { return this.requestId; } } /** * //////////////////////////////////////////////// CLASS MappingComponentFeatureServiceListener // * ////////////////////////////////////////////////. * * @version $Revision$, $Date$ */ private class MappingComponentFeatureServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- ServiceLayer featureService; PLayer parent; long requestIdentifier; Thread completionThread = null; private Logger logger = Logger.getLogger(this.getClass()); private Vector deletionCandidates = new Vector(); private Vector twins = new Vector(); //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentFeatureServiceListener. * * @param featureService the featureretrievalservice * @param parent the featurelayer (PNode) connected with the servicelayer */ public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) { this.featureService = featureService; this.parent = parent; } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { requestIdentifier = e.getRequestIdentifier(); } if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N } } fireActivityChanged(); } @Override public void retrievalProgress(final RetrievalEvent e) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: " + e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress() + ")"); // NOI18N } } fireActivityChanged(); // TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das // flüssiger ist } @Override public void retrievalError(final RetrievalEvent e) { this.logger.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N fireActivityChanged(); } @Override public void retrievalComplete(final RetrievalEvent e) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N } } if (e.isInitialisationEvent()) { this.logger.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: initialisation complete"); // NOI18N fireActivityChanged(); return; } if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N } ((RetrievalServiceLayer)featureService).setProgress(-1); fireActivityChanged(); return; } final Vector newFeatures = new Vector(); EventQueue.invokeLater(new Runnable() { @Override public void run() { ((RetrievalServiceLayer)featureService).setProgress(-1); parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible()); // parent.removeAllChildren(); } }); // clear all old data to delete twins deletionCandidates.removeAllElements(); twins.removeAllElements(); // if it's a refresh, add all old features which should be deleted in the // newly acquired featurecollection if (!e.isRefreshExisting()) { deletionCandidates.addAll(parent.getChildrenReference()); } if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N } } // only start parsing the features if there are no errors and a correct collection if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) { completionThread = new Thread() { @Override public void run() { // this is the collection with the retrieved features // Collection c = ((Collection) e.getRetrievedObject()); final List features = new ArrayList((Collection)e.getRetrievedObject()); final int size = features.size(); int counter = 0; final Iterator it = features.iterator(); if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N } } while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted() && it.hasNext()) { counter++; final Object o = it.next(); if (o instanceof Feature) { final PFeature p = new PFeature(((Feature)o), wtst, clip_offset_x, clip_offset_y, MappingComponent.this); PFeature twin = null; for (final Object tester : deletionCandidates) { // if tester and PFeature are FeatureWithId-objects if ((((PFeature)tester).getFeature() instanceof FeatureWithId) && (p.getFeature() instanceof FeatureWithId)) { final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId(); final int id2 = ((FeatureWithId)(p.getFeature())).getId(); if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id if (id1 == id2) { twin = ((PFeature)tester); break; } } else { // else test the geometry for equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } else { // no FeatureWithId, test geometries for // equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } // if a twin is found remove him from the deletion candidates // and add him to the twins if (twin != null) { deletionCandidates.remove(twin); twins.add(twin); } else { // else add the PFeature to the new features newFeatures.add(p); } // calculate the advance of the progressbar // fire event only wheen needed final int currentProgress = (int)((double)counter / (double)size * 100d); /*if(currentProgress % 10 == 0 && currentProgress > lastUpdateProgress) * { lastUpdateProgress = currentProgress; if(DEBUG)log.debug("fire progress changed * "+currentProgress); fireActivityChanged();}*/ if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) { ((RetrievalServiceLayer)featureService).setProgress(currentProgress); fireActivityChanged(); } } } if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) { // after all features are computed do stuff on the EDT EventQueue.invokeLater(new Runnable() { @Override public void run() { try { if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N } } // if it's a refresh, delete all previous features if (e.isRefreshExisting()) { parent.removeAllChildren(); } final Vector deleteFeatures = new Vector(); for (final Object o : newFeatures) { parent.addChild((PNode)o); } // for (Object o : twins) { // TODO only nesseccary if style has changed // ((PFeature) o).refreshDesign(); // if(DEBUG)log.debug("twin refresh"); // } // set the prograssbar to full if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: set progress to 100"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(100); fireActivityChanged(); // repaint the featurelayer parent.repaint(); // remove stickyNode from all deletionCandidates and add // each to the new deletefeature-collection for (final Object o : deletionCandidates) { if (o instanceof PFeature) { final PNode p = ((PFeature)o).getPrimaryAnnotationNode(); if (p != null) { removeStickyNode(p); } deleteFeatures.add(o); } } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount before:" + parent.getChildrenCount()); // NOI18N } } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: deleteFeatures=" + deleteFeatures.size()); // + " :" + // deleteFeatures);//NOI18N } } parent.removeChildren(deleteFeatures); if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount after:" + parent.getChildrenCount()); // NOI18N } } log.info( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + parent.getChildrenCount() + " features retrieved or updated"); // NOI18N rescaleStickyNodes(); } catch (Exception exception) { logger.warn( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Fehler beim Aufr\u00E4umen", exception); // NOI18N } } }); } else { if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } }; completionThread.setPriority(Thread.NORM_PRIORITY); if (requestIdentifier == e.getRequestIdentifier()) { completionThread.start(); } else { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } fireActivityChanged(); } @Override public void retrievalAborted(final RetrievalEvent e) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: aborted, TaskCounter:" + taskCounter); // NOI18N if (completionThread != null) { completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(-1); } else { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(0); } fireActivityChanged(); } } }
public void setInteractionMode(final String interactionMode) { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("setInteractionMode(" + interactionMode + ")\nAlter InteractionMode:" + this.interactionMode + "", new Exception()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } setPointerAnnotationVisibility(false); if (getPrintingFrameLayer().getChildrenCount() > 1) { getPrintingFrameLayer().removeAllChildren(); } if (this.interactionMode != null) { if (interactionMode.equals(FEATURE_INFO)) { ((GetFeatureInfoClickDetectionListener)this.getInputListener(interactionMode)).getPInfo() .setVisible(true); } else { ((GetFeatureInfoClickDetectionListener)this.getInputListener(FEATURE_INFO)).getPInfo() .setVisible(false); } if (isReadOnly()) { ((DefaultFeatureCollection)(getFeatureCollection())).removeFeaturesByInstance(PureNewFeature.class); } final PInputEventListener pivl = this.getInputListener(this.interactionMode); if (pivl != null) { removeInputEventListener(pivl); } else { log.warn("this.getInputListener(this.interactionMode)==null"); // NOI18N } if (interactionMode.equals(NEW_POLYGON) || interactionMode.equals(CREATE_SEARCH_POLYGON)) { // ||interactionMode==SELECT) { // if (selectedFeature!=null) { // selectPFeatureManually(null); // } featureCollection.unselectAll(); } if ((interactionMode.equals(SELECT) || interactionMode.equals(LINEMEASUREMENT) || interactionMode.equals(SPLIT_POLYGON)) && (this.readOnly == false)) { // if (selectedFeature!=null) { // selectPFeatureManually(selectedFeature); // } featureSelectionChanged(null); } if (interactionMode.equals(JOIN_POLYGONS)) { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } final PropertyChangeEvent interactionModeChangedEvent = new PropertyChangeEvent( this, PROPERTY_MAP_INTERACTION_MODE, this.interactionMode, interactionMode); this.interactionMode = interactionMode; final PInputEventListener pivl = getInputListener(interactionMode); if (pivl != null) { addInputEventListener(pivl); propertyChangeSupport.firePropertyChange(interactionModeChangedEvent); CismapBroker.getInstance() .fireStatusValueChanged(new StatusEvent(StatusEvent.MAPPING_MODE, interactionMode)); } else { log.warn("this.getInputListener(this.interactionMode)==null bei interactionMode=" + interactionMode); // NOI18N } } catch (Exception e) { log.error("Fehler beim Ändern des InteractionModes", e); // NOI18N } } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ @Deprecated public void formComponentResized(final ComponentEvent evt) { this.componentResizedDelayed(); } /** * Resizes the map and does not reload all services. * * @see #componentResizedDelayed() */ public void componentResizedIntermediate() { if (!this.isLocked()) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("componentResizedIntermediate " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N } } if (MappingComponent.this.currentBoundingBox == null) { log.error("currentBoundingBox is null"); // NOI18N currentBoundingBox = getCurrentBoundingBox(); } // rescale map if (historyModel.getCurrentElement() != null) { final PBounds bounds = (PBounds)historyModel.getCurrentElement(); if (bounds.getWidth() < 0) { bounds.setSize(bounds.getWidth() * (-1), bounds.getHeight()); } if (bounds.getHeight() < 0) { bounds.setSize(bounds.getWidth(), bounds.getHeight() * (-1)); } getCamera().animateViewToCenterBounds(bounds, true, animationDuration); } } } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } } } /** * Resizes the map and reloads all services. * * @see #componentResizedIntermediate() */ public void componentResizedDelayed() { if (!this.isLocked()) { try { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("componentResizedDelayed " + MappingComponent.this.getSize()); // NOI18N } } if ((MappingComponent.this.getSize().height >= 0) && (MappingComponent.this.getSize().width >= 0)) { if (mappingModel != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("BB:" + MappingComponent.this.currentBoundingBox); // NOI18N } } if (MappingComponent.this.currentBoundingBox == null) { log.error("currentBoundingBox is null"); // NOI18N currentBoundingBox = getCurrentBoundingBox(); } gotoBoundsWithoutHistory((PBounds)historyModel.getCurrentElement()); // } // if (getCurrentElement()!=null) { // gotoBoundsWithoutHistory((PBounds)(getCurrentElement())); // } else { // if(DEBUG)log.debug("getCurrentElement()==null) "); // } // for (JComponent internalWiget : this.internalWidgets.values()) // { // if (internalWiget.isVisible()) // { // internalWiget.setVisible(false); // } // } // move internal widgets for (final String internalWidget : this.internalWidgets.keySet()) { if (this.getInternalWidget(internalWidget).isVisible()) { showInternalWidget(internalWidget, true, 0); } } // if (internalLayerWidget != null && internalLayerWidget.isVisible()) // { // internalLayerWidget.setVisible(false); // } } } } catch (Throwable t) { log.error("Fehler in formComponentResized()", t); // NOI18N } } } /** * syncSelectedObjectPresenter(int i). * * @param i DOCUMENT ME! */ public void syncSelectedObjectPresenter(final int i) { selectedObjectPresenter.setVisible(true); if (featureCollection.getSelectedFeatures().size() > 0) { if (featureCollection.getSelectedFeatures().size() == 1) { final PFeature selectedFeature = (PFeature)pFeatureHM.get( featureCollection.getSelectedFeatures().toArray()[0]); if (selectedFeature != null) { selectedObjectPresenter.getCamera() .animateViewToCenterBounds(selectedFeature.getBounds(), true, getAnimationDuration() * 2); } } else { // todo } } else { log.warn("in syncSelectedObjectPresenter(" + i + "): selectedFeature==null"); // NOI18N } } // public void selectPFeatureManually(PFeature feature) { // if (feature==null) { // handleLayer.removeAllChildren(); // if (selectedFeature!=null) { // selectedFeature.setSelected(false); // } // } else { // if (selectedFeature!=null) { // selectedFeature.setSelected(false); // } // feature.setSelected(true); // selectedFeature=feature; // // // //Fuer den selectedObjectPresenter (Eigener PCanvas) // syncSelectedObjectPresenter(1000); // // handleLayer.removeAllChildren(); // if ( this.isReadOnly()==false // &&( // getInteractionMode().equals(SELECT) // || // getInteractionMode().equals(PAN) // || // getInteractionMode().equals(ZOOM) // || // getInteractionMode().equals(SPLIT_POLYGON) // ) // ) { // selectedFeature.addHandles(handleLayer); // } else { // handleLayer.removeAllChildren(); // } // } // // } // public void selectionChanged(de.cismet.cismap.commons.MappingModelEvent mme) { // Feature f=mme.getFeature(); // if (f==null) { // selectPFeatureManually(null); // } else { // PFeature fp=((PFeature)pFeatureHM.get(f)); // if (fp!=null&&fp.getFeature()!=null&&fp.getFeature().getGeometry()!=null) { //// PNode p=fp.getChild(0); // selectPFeatureManually(fp); // } else { // selectPFeatureManually(null); // } // } // } /** * Returns the current featureCollection. * * @return DOCUMENT ME! */ public FeatureCollection getFeatureCollection() { return featureCollection; } /** * Replaces the old featureCollection with a new one. * * @param featureCollection the new featureCollection */ public void setFeatureCollection(final FeatureCollection featureCollection) { this.featureCollection = featureCollection; featureCollection.addFeatureCollectionListener(this); } /** * DOCUMENT ME! * * @param visibility DOCUMENT ME! */ public void setFeatureCollectionVisibility(final boolean visibility) { featureLayer.setVisible(visibility); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFeatureCollectionVisible() { return featureLayer.getVisible(); } /** * Adds a new mapservice at a specific place of the layercontrols. * * @param mapService the new mapservice * @param position the index where to position the mapservice */ public void addMapService(final MapService mapService, final int position) { try { PNode p = new PNode(); if (mapService instanceof RasterMapService) { log.info("adding RasterMapService '" + mapService + "' " + mapService.getClass().getSimpleName() + ")"); // NOI18N if (mapService.getPNode() instanceof XPImage) { p = (XPImage)mapService.getPNode(); } else { p = new XPImage(); mapService.setPNode(p); } mapService.addRetrievalListener(new MappingComponentRasterServiceListener( position, p, (ServiceLayer)mapService)); } else { log.info("adding FeatureMapService '" + mapService + "' (" + mapService.getClass().getSimpleName() + ")"); // NOI18N p = new PLayer(); mapService.setPNode(p); if (DocumentFeatureService.class.isAssignableFrom(mapService.getClass())) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): isDocumentFeatureService, checking document size"); // NOI18N } } final DocumentFeatureService documentFeatureService = (DocumentFeatureService)mapService; if (documentFeatureService.getDocumentSize() > this.criticalDocumentSize) { log.warn("FeatureMapService(" + mapService + "): DocumentFeatureService '" + documentFeatureService.getName() + "' size of " + (documentFeatureService.getDocumentSize() / 1000000) + "MB exceeds critical document size (" + (this.criticalDocumentSize / 1000000) + "MB)"); // NOI18N if (this.documentProgressListener == null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): lazy instantiation of documentProgressListener"); // NOI18N } } this.documentProgressListener = new DocumentProgressListener(); } if (this.documentProgressListener.getRequestId() != -1) { log.error("FeatureMapService(" + mapService + "): The documentProgressListener is already in use by request '" + this.documentProgressListener.getRequestId() + ", document progress cannot be tracked"); // NOI18N } else { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureMapService(" + mapService + "): adding documentProgressListener"); // NOI18N } } documentFeatureService.addRetrievalListener(this.documentProgressListener); } } } mapService.addRetrievalListener(new MappingComponentFeatureServiceListener( (ServiceLayer)mapService, (PLayer)mapService.getPNode())); } p.setTransparency(mapService.getTranslucency()); p.setVisible(mapService.isVisible()); mapServicelayer.addChild(p); // if (internalLayerWidgetAvailable) { //// LayerControl lc=internalLayerWidget.addRasterService(rs.size()-rsi,(ServiceLayer)o,cismapPrefs.getGlobalPrefs().getErrorAbolitionTime()); // LayerControl lc = internalLayerWidget.addRasterService(position, (ServiceLayer) mapService, 500); // mapService.addRetrievalListener(lc); // lc.setTransparentable(p); // layerControls.add(lc); // } } catch (Throwable t) { log.error("addMapService(" + mapService + "): Fehler beim hinzufuegen eines Layers: " + t.getMessage(), t); // NOI18N } } /** * DOCUMENT ME! * * @param mm DOCUMENT ME! */ public void preparationSetMappingModel(final MappingModel mm) { mappingModel = mm; } /** * Sets a new mappingmodel in this MappingComponent. * * @param mm the new mappingmodel */ public void setMappingModel(final MappingModel mm) { log.info("setMappingModel"); // NOI18N if (Thread.getDefaultUncaughtExceptionHandler() == null) { log.info("setDefaultUncaughtExceptionHandler"); // NOI18N Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { log.error("Error", e); } }); } mappingModel = mm; currentBoundingBox = mm.getInitialBoundingBox(); final Runnable r = new Runnable() { @Override public void run() { mappingModel.addMappingModelListener(MappingComponent.this); // currentBoundingBox=mm.getInitialBoundingBox(); final TreeMap rs = mappingModel.getRasterServices(); // reCalcWtstAndBoundingBox(); // Rückwärts wegen der Reihenfolge der Layer im Layer Widget final Iterator it = rs.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { addMapService(((MapService)o), rsi); } } // Es gibt nur noch MapServices // TreeMap fs = mappingModel.getFeatureServices(); // //Rueckwaerts wegen der Reihenfolge der Layer im Layer Widget // it = fs.keySet().iterator(); // while (it.hasNext()) { // Object key = it.next(); // int fsi = ((Integer) key).intValue(); // Object o = fs.get(key); // if (o instanceof MapService) { // if(DEBUG)log.debug("neuer Featureservice: " + o); // PLayer pn = new PLayer(); // //pn.setVisible(true); // //pn.setBounds(this.getRoot().getFullBounds()); // pn.setTransparency(((MapService) o).getTranslucency()); // //((FeatureService)o).setPNode(pn); // featureServiceLayer.addChild(pn); // pn.addClientProperty("serviceLayer", (ServiceLayer) o); // //getCamera().addLayer(pn); // ((MapService) o).addRetrievalListener(new MappingComponentFeatureServiceListener((ServiceLayer) o, pn)); // if(DEBUG)log.debug("add FeatureService"); // // //if (internalLayerWidgetAvailable) { // //LayerControl lc = internalLayerWidget.addFeatureService(fs.size() - fsi, (ServiceLayer) o, 3000); // //LayerControl lc=internalLayerWidget.addFeatureService(fs.size()-fsi,(ServiceLayer)o,cismapPrefs.getGlobalPrefs().getErrorAbolitionTime()); //// ((MapService) o).addRetrievalListener(lc); //// lc.setTransparentable(pn); //// layerControls.add(lc); // //} // } // } adjustLayers(); // TODO MappingModel im InternalLayerWidget setzen, da es bei // der Initialisierung des Widgets NULL ist // internalLayerWidget = new NewSimpleInternalLayerWidget(MappingComponent.this); // internalLayerWidget.setMappingModel(mappingModel); // gotoInitialBoundingBox(); final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Set Mapping Modell done"); // NOI18N } } } }; CismetThreadPool.execute(r); } /** * Returns the current mappingmodel. * * @return current mappingmodel */ public MappingModel getMappingModel() { return mappingModel; } /** * Animates a component to a given x/y-coordinate in a given time. * * @param c the component to animate * @param toX final x-position * @param toY final y-position * @param animationDuration duration of the animation * @param hideAfterAnimation should the component be hidden after animation? */ private void animateComponent(final JComponent c, final int toX, final int toY, final int animationDuration, final boolean hideAfterAnimation) { if (animationDuration > 0) { final int x = (int)c.getBounds().getX() - toX; final int y = (int)c.getBounds().getY() - toY; int sx; int sy; if (x > 0) { sx = -1; } else { sx = 1; } if (y > 0) { sy = -1; } else { sy = 1; } int big; if (Math.abs(x) > Math.abs(y)) { big = Math.abs(x); } else { big = Math.abs(y); } final int sleepy; if ((animationDuration / big) < 1) { sleepy = 1; } else { sleepy = (int)(animationDuration / big); } final int directionY = sy; final int directionX = sx; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("animateComponent: directionX=" + directionX + ", directionY=" + directionY + ", currentX=" + c.getBounds().getX() + ", currentY=" + c.getBounds().getY() + ", toX=" + toX + ", toY=" + toY); // NOI18N } } final Thread timer = new Thread() { @Override public void run() { while (!isInterrupted()) { try { sleep(sleepy); } catch (Exception iex) { } EventQueue.invokeLater(new Runnable() { @Override public void run() { int currentY = (int)c.getBounds().getY(); int currentX = (int)c.getBounds().getX(); if (currentY != toY) { currentY = currentY + directionY; } if (currentX != toX) { currentX = currentX + directionX; } c.setBounds(currentX, currentY, c.getWidth(), c.getHeight()); } }); if ((c.getBounds().getY() == toY) && (c.getBounds().getX() == toX)) { if (hideAfterAnimation) { EventQueue.invokeLater(new Runnable() { @Override public void run() { c.setVisible(false); c.hide(); } }); } break; } } } }; timer.setPriority(Thread.NORM_PRIORITY); timer.start(); } else { c.setBounds(toX, toY, c.getWidth(), c.getHeight()); if (hideAfterAnimation) { c.setVisible(false); } } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @depreacted DOCUMENT ME! */ @Deprecated public NewSimpleInternalLayerWidget getInternalLayerWidget() { return (NewSimpleInternalLayerWidget)this.getInternalWidget(LAYERWIDGET); } /** * Adds a new internal widget to the map.<br/> * If a {@code widget} with the same {@code name} already exisits, the old widget will be removed and the new widget * will be added. If a widget with a different name already exisit at the same {@code position} the new widget will * not be added and the operation returns {@code false}. * * @param name unique name of the widget * @param position position of the widget * @param widget the widget * * @return {@code true} if the widget could be added, {@code false} otherwise * * @see #POSITION_NORTHEAST * @see #POSITION_NORTHWEST * @see #POSITION_SOUTHEAST * @see #POSITION_SOUTHWEST */ public boolean addInternalWidget(final String name, final int position, final JInternalFrame widget) { if (log.isDebugEnabled()) { log.debug("adding internal widget '" + name + "' to position '" + position + "'"); // NOI18N } if (this.internalWidgets.containsKey(name)) { log.warn("widget '" + name + "' already added, removing old widget"); // NOI18N this.remove(this.getInternalWidget(name)); } else if (this.internalWidgetPositions.containsValue(position)) { log.warn("widget position '" + position + "' already taken"); // NOI18N return false; } this.internalWidgets.put(name, widget); this.internalWidgetPositions.put(name, position); widget.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); // NOI18N this.add(widget); widget.pack(); return true; } /** * Removes an existing internal widget from the map. * * @param name name of the widget to be removed * * @return {@code true} id the widget was found and removed, {@code false} otherwise */ public boolean removeInternalWidget(final String name) { if (log.isDebugEnabled()) { log.debug("removing internal widget '" + name + "'"); // NOI18N } if (!this.internalWidgets.containsKey(name)) { log.warn("widget '" + name + "' not found"); // NOI18N return false; } this.remove(this.getInternalWidget(name)); this.internalWidgets.remove(name); this.internalWidgetPositions.remove(name); return true; } /** * Shows an InternalWidget by sliding it into the mappingcomponent. * * @param name name of the internl component to show * @param visible should the widget be visible after the animation? * @param animationDuration duration of the animation * * @return {@code true} if the operation was successful, {@code false} otherwise */ public boolean showInternalWidget(final String name, final boolean visible, final int animationDuration) { // log.info("showing internal widget '" + name + "': " + visible); final JInternalFrame internalWidget = this.getInternalWidget(name); if (internalWidget == null) { return false; } int positionX; int positionY; final int widgetPosition = this.getInternalWidgetPosition(name); switch (widgetPosition) { case POSITION_NORTHWEST: { positionX = 1; positionY = 1; break; } case POSITION_SOUTHWEST: { positionX = 1; positionY = getHeight() - internalWidget.getHeight() - 1; break; } case POSITION_NORTHEAST: { positionX = getWidth() - internalWidget.getWidth() - 1; positionY = 1; break; } case POSITION_SOUTHEAST: { positionX = getWidth() - internalWidget.getWidth() - 1; positionY = getHeight() - internalWidget.getHeight() - 1; break; } default: { log.warn("unkown widget position?!"); // NOI18N return false; } } if (visible) { int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } internalWidget.setBounds(positionX, toY, internalWidget.getWidth(), internalWidget.getHeight()); internalWidget.setVisible(true); internalWidget.show(); animateComponent(internalWidget, positionX, positionY, animationDuration, false); } else { internalWidget.setBounds(positionX, positionY, internalWidget.getWidth(), internalWidget.getHeight()); int toY = positionY + internalWidget.getHeight() + 1; if ((widgetPosition == POSITION_NORTHWEST) || (widgetPosition == POSITION_NORTHEAST)) { toY = positionY - internalWidget.getHeight() - 1; } animateComponent(internalWidget, positionX, toY, animationDuration, true); } return true; } /** * DOCUMENT ME! * * @param visible DOCUMENT ME! * @param animationDuration DOCUMENT ME! */ @Deprecated public void showInternalLayerWidget(final boolean visible, final int animationDuration) { this.showInternalWidget(LAYERWIDGET, visible, animationDuration); // //NORTH WEST // int positionX = 1; // int positionY = 1; // // //SOUTH WEST // positionX = 1; // positionY = getHeight() - getInternalLayerWidget().getHeight() - 1; // // //NORTH EAST // positionX = getWidth() - getInternalLayerWidget().getWidth() - 1; // positionY = 1; // // SOUTH EAST // int positionX = getWidth() - internalLayerWidget.getWidth() - 1; // int positionY = getHeight() - internalLayerWidget.getHeight() - 1; // // if (visible) // { // internalLayerWidget.setVisible(true); // internalLayerWidget.show(); // internalLayerWidget.setBounds(positionX, positionY + internalLayerWidget.getHeight() + 1, internalLayerWidget.getWidth(), internalLayerWidget.getHeight()); // animateComponent(internalLayerWidget, positionX, positionY, animationDuration, false); // // } else // { // internalLayerWidget.setBounds(positionX, positionY, internalLayerWidget.getWidth(), internalLayerWidget.getHeight()); // animateComponent(internalLayerWidget, positionX, positionY + internalLayerWidget.getHeight() + 1, animationDuration, true); // } } /** * Returns a boolean, if the InternalLayerWidget is visible. * * @return true, if visible, else false */ @Deprecated public boolean isInternalLayerWidgetVisible() { return this.getInternalLayerWidget().isVisible(); } /** * Returns a boolean, if the InternalWidget is visible. * * @param name name of the widget * * @return true, if visible, else false */ public boolean isInternalWidgetVisible(final String name) { final JInternalFrame widget = this.getInternalWidget(name); if (widget != null) { return widget.isVisible(); } return false; } /** * Moves the camera to the initial bounding box (e.g. if the home-button is pressed). */ public void gotoInitialBoundingBox() { final double x1; final double y1; final double x2; final double y2; final double w; final double h; x1 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX1()); y1 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY1()); x2 = getWtst().getScreenX(mappingModel.getInitialBoundingBox().getX2()); y2 = getWtst().getScreenY(mappingModel.getInitialBoundingBox().getY2()); final Rectangle2D home = new Rectangle2D.Double(); home.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(home, true, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { log.fatal("gotoInitialBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } setNewViewBounds(home); queryServices(); } /** * Refreshs all registered services. */ public void queryServices() { if (newViewBounds != null) { addToHistory(new PBoundsWithCleverToString( new PBounds(newViewBounds), wtst, CismapBroker.getInstance().getSrs().getCode())); queryServicesWithoutHistory(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServices()"); // NOI18N } } rescaleStickyNodes(); } // showHandles(false); } /** * Forces all services to refresh themselves. */ public void refresh() { forceQueryServicesWithoutHistory(); } /** * Forces all services to refresh themselves. */ private void forceQueryServicesWithoutHistory() { queryServicesWithoutHistory(true); } /** * Refreshs all services, but not forced. */ private void queryServicesWithoutHistory() { queryServicesWithoutHistory(false); } /** * Waits until all animations are done, then iterates through all registered services and calls handleMapService() * for each. * * @param forced forces the refresh */ private void queryServicesWithoutHistory(final boolean forced) { if (!locked) { final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception doNothing) { } } CismapBroker.getInstance().fireMapBoundsChanged(); if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if (o instanceof MapService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesWithoutHistory (RasterServices): " + o); // NOI18N } } handleMapService(rsi, (MapService)o, forced); } else { log.warn("service is not of type MapService:" + o); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof MapService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesWithoutHistory (FeatureServices): " + o); // NOI18N } } handleMapService(fsi, (MapService)o, forced); } else { log.warn("service is not of type MapService:" + o); // NOI18N } } } } }; CismetThreadPool.execute(r); } } /** * queryServicesIndependentFromMap. * * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param rl DOCUMENT ME! */ public void queryServicesIndependentFromMap(final int width, final int height, final BoundingBox bb, final RetrievalListener rl) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap (" + width + "x" + height + ")"); // NOI18N } } final Runnable r = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception doNothing) { } } if (MappingComponent.this.isBackgroundEnabled()) { final TreeMap rs = mappingModel.getRasterServices(); final TreeMap fs = mappingModel.getFeatureServices(); for (final Iterator it = rs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int rsi = ((Integer)key).intValue(); final Object o = rs.get(key); if ((o instanceof AbstractRetrievalService) && (o instanceof ServiceLayer) && ((ServiceLayer)o).isEnabled() && (o instanceof RetrievalServiceLayer) && ((RetrievalServiceLayer)o).getPNode().getVisible()) { try { // AbstractRetrievalService r = ((AbstractRetrievalService) // o).cloneWithoutRetrievalListeners(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = wfsClone; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(rsi); handleMapService(rsi, (MapService)r, width, height, bb, true); } catch (Throwable t) { log.error("could not clone service '" + o + "' for printing: " + t.getMessage(), t); // NOI18N } } else { log.warn("ignoring service '" + o + "' for printing"); // NOI18N } } for (final Iterator it = fs.keySet().iterator(); it.hasNext();) { final Object key = it.next(); final int fsi = ((Integer)key).intValue(); final Object o = fs.get(key); if (o instanceof AbstractRetrievalService) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("queryServicesIndependentFromMap: cloning '" + o.getClass().getSimpleName() + "': '" + o + "'"); // NOI18N } } AbstractRetrievalService r; if (o instanceof WebFeatureService) { final WebFeatureService wfsClone = (WebFeatureService)((WebFeatureService)o) .clone(); wfsClone.removeAllListeners(); r = (AbstractRetrievalService)o; } else { r = ((AbstractRetrievalService)o).cloneWithoutRetrievalListeners(); } r.addRetrievalListener(rl); ((ServiceLayer)r).setLayerPosition(fsi); handleMapService(fsi, (MapService)r, 0, 0, bb, true); } } } } }; CismetThreadPool.execute(r); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param service rs * @param forced DOCUMENT ME! */ public void handleMapService(final int position, final MapService service, final boolean forced) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("in handleRasterService: " + service + "(" + Integer.toHexString(System.identityHashCode(service)) + ")(" + service.hashCode() + ")"); // NOI18N } } final PBounds bounds = getCamera().getViewBounds(); final BoundingBox bb = new BoundingBox(); final double x1 = getWtst().getWorldX(bounds.getMinX()); final double y1 = getWtst().getWorldY(bounds.getMaxY()); final double x2 = getWtst().getWorldX(bounds.getMaxX()); final double y2 = getWtst().getWorldY(bounds.getMinY()); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Bounds=" + bounds); // NOI18N } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("handleRasterService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // NOI18N } } if (((ServiceLayer)service).getName().startsWith("prefetching")) { // NOI18N bb.setX1(x1 - (x2 - x1)); bb.setY1(y1 - (y2 - y1)); bb.setX2(x2 + (x2 - x1)); bb.setY2(y2 + (y2 - y1)); } else { bb.setX1(x1); bb.setY1(y1); bb.setX2(x2); bb.setY2(y2); } handleMapService(position, service, getWidth(), getHeight(), bb, forced); } /** * former synchronized method. * * @param position DOCUMENT ME! * @param rs DOCUMENT ME! * @param width DOCUMENT ME! * @param height DOCUMENT ME! * @param bb DOCUMENT ME! * @param forced DOCUMENT ME! */ private void handleMapService(final int position, final MapService rs, final int width, final int height, final BoundingBox bb, final boolean forced) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("handleMapService: " + rs); // NOI18N } } if (((ServiceLayer)rs).isEnabled()) { synchronized (serviceFuturesMap) { final Future<?> sf = serviceFuturesMap.get(rs); if ((sf == null) || sf.isDone()) { rs.setSize(height, width); final Runnable serviceCall = new Runnable() { @Override public void run() { try { while (getAnimating()) { try { Thread.currentThread().sleep(50); } catch (Exception e) { } } rs.setBoundingBox(bb); if (rs instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)rs).setFeatureCollection(featureCollection); } rs.retrieve(forced); } finally { serviceFuturesMap.remove(rs); } } }; synchronized (serviceFuturesMap) { serviceFuturesMap.put(rs, CismetThreadPool.submit(serviceCall)); } } } } } // private void handleMapService(int position, final MapService rs, int width, int height, final BoundingBox bb, final boolean forced) { // if (DEBUG) { // log.debug("handleMapService: " + rs); // } // // if (((ServiceLayer) rs).isEnabled()) { // rs.setSize(height, width); // //if(DEBUG)log.debug("this.currentBoundingBox:"+this.currentBoundingBox); // //If the PCanvas is in animation state, there should be a pre information about the // //aimed new bounds // Runnable handle = new Runnable() { // // @Override // public void run() { // while (getAnimating()) { // try { // Thread.currentThread().sleep(50); // } catch (Exception e) { // } // } // rs.setBoundingBox(bb); // if (rs instanceof FeatureAwareRasterService) { // ((FeatureAwareRasterService) rs).setFeatureCollection(featureCollection); // } // rs.retrieve(forced); // } // }; // CismetThreadPool.execute(handle); // } // } //former synchronized method // private void handleFeatureService(int position, final FeatureService fs, boolean forced) { // synchronized (handleFeatureServiceBlocker) { // PBounds bounds = getCamera().getViewBounds(); // // BoundingBox bb = new BoundingBox(); // double x1 = getWtst().getSourceX(bounds.getMinX()); // double y1 = getWtst().getSourceY(bounds.getMaxY()); // double x2 = getWtst().getSourceX(bounds.getMaxX()); // double y2 = getWtst().getSourceY(bounds.getMinY()); // // if(DEBUG)log.debug("handleFeatureService BoundingBox(" + x1 + " " + y1 + "," + x2 + " " + y2 + ")"); // // bb.setX1(x1); // bb.setY1(y1); // bb.setX2(x2); // bb.setY2(y2); // handleFeatureService(position, fs, bb, forced); // } // } ////former synchronized method // Object handleFeatureServiceBlocker2 = new Object(); // // private void handleFeatureService(int position, final FeatureService fs, final BoundingBox bb, final boolean forced) { // synchronized (handleFeatureServiceBlocker2) { // if(DEBUG)log.debug("handleFeatureService"); // if (fs instanceof ServiceLayer && ((ServiceLayer) fs).isEnabled()) { // Thread handle = new Thread() { // // @Override // public void run() { // while (getAnimating()) { // try { // sleep(50); // } catch (Exception e) { // log.error("Fehler im handle FeatureServicethread"); // } // } // fs.setBoundingBox(bb); // fs.retrieve(forced); // } // }; // handle.setPriority(Thread.NORM_PRIORITY); // handle.start(); // } // } // } /** * Creates a new WorldToScreenTransform for the current screensize (boundingbox) and returns it. * * @return new WorldToScreenTransform or null */ public WorldToScreenTransform getWtst() { try { if (wtst == null) { final double y_real = mappingModel.getInitialBoundingBox().getY2() - mappingModel.getInitialBoundingBox().getY1(); final double x_real = mappingModel.getInitialBoundingBox().getX2() - mappingModel.getInitialBoundingBox().getX1(); double clip_height; double clip_width; double x_screen = getWidth(); double y_screen = getHeight(); if (x_screen == 0) { x_screen = 100; } if (y_screen == 0) { y_screen = 100; } if ((x_real / x_screen) >= (y_real / y_screen)) { // X ist Bestimmer d.h. x wird nicht verändert clip_height = x_screen * y_real / x_real; clip_width = x_screen; clip_offset_y = 0; // (y_screen-clip_height)/2; clip_offset_x = 0; } else { // Y ist Bestimmer clip_height = y_screen; clip_width = y_screen * x_real / y_real; clip_offset_y = 0; clip_offset_x = 0; // (x_screen-clip_width)/2; } // wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX2(),mappingModel.getInitialBoundingBox().getY2(),0,0,clip_width,clip_height); // wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX2(),mappingModel.getInitialBoundingBox().getY2(),0,0, // x_real,y_real); wtst= new WorldToScreenTransform(2566470,5673088,2566470+100,5673088+100,0,0,100,100); // wtst= new WorldToScreenTransform(-180,-90,180,90,0,0,180,90); wtst= new // WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(),mappingModel.getInitialBoundingBox().getY1(),mappingModel.getInitialBoundingBox().getX1()+100,mappingModel.getInitialBoundingBox().getY1()+100,0,0,100,100); // wtst= new WorldToScreenTransform(0,0, 1000, 1000, 0,0, 1000,1000); wtst = new WorldToScreenTransform(mappingModel.getInitialBoundingBox().getX1(), mappingModel.getInitialBoundingBox().getY2()); } return wtst; } catch (Throwable t) { log.error("Fehler in getWtst()", t); // NOI18N return null; } } /** * Resets the current WorldToScreenTransformation. */ public void resetWtst() { wtst = null; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_x() { return 0; // clip_offset_x; } /** * Assigns a new value to the x-clip-offset. * * @param clip_offset_x new clipoffset */ public void setClip_offset_x(final double clip_offset_x) { this.clip_offset_x = clip_offset_x; } /** * Returns 0. * * @return DOCUMENT ME! */ public double getClip_offset_y() { return 0; // clip_offset_y; } /** * Assigns a new value to the y-clip-offset. * * @param clip_offset_y new clipoffset */ public void setClip_offset_y(final double clip_offset_y) { this.clip_offset_y = clip_offset_y; } /** * Returns the rubberband-PLayer. * * @return DOCUMENT ME! */ public PLayer getRubberBandLayer() { return rubberBandLayer; } /** * Assigns a given PLayer to the variable rubberBandLayer. * * @param rubberBandLayer a PLayer */ public void setRubberBandLayer(final PLayer rubberBandLayer) { this.rubberBandLayer = rubberBandLayer; } /** * Sets new viewbounds. * * @param r2d Rectangle2D */ public void setNewViewBounds(final Rectangle2D r2d) { newViewBounds = r2d; } /** * Will be called if the selection of features changes. It selects the PFeatures connected to the selected features * of the featurecollectionevent and moves them to the front. Also repaints handles at the end. * * @param fce featurecollectionevent with selected features */ @Override public void featureSelectionChanged(final FeatureCollectionEvent fce) { final Collection<PFeature> all = featureLayer.getChildrenReference(); for (final PFeature f : all) { f.setSelected(false); } Collection<Feature> c; if (fce != null) { c = fce.getFeatureCollection().getSelectedFeatures(); } else { c = featureCollection.getSelectedFeatures(); } ////handle featuregroup select-delegation//// final Set<Feature> selectionResult = TypeSafeCollections.newHashSet(); for (final Feature current : c) { if (current instanceof FeatureGroup) { selectionResult.addAll(FeatureGroups.expandToLeafs((FeatureGroup)current)); } else { selectionResult.add(current); } } ///////////////////////////////////////////// c = selectionResult; for (final Feature f : c) { if (f != null) { final PFeature feature = (PFeature)getPFeatureHM().get(f); if (feature != null) { feature.setSelected(true); feature.moveToFront(); // Fuer den selectedObjectPresenter (Eigener PCanvas) syncSelectedObjectPresenter(1000); } else { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } } } showHandles(false); } /** * Will be called if one or more features are changed somehow (handles moved/rotated). Calls reconsiderFeature() on * each feature of the given featurecollectionevent. Repaints handles at the end. * * @param fce featurecollectionevent with changed features */ @Override public void featuresChanged(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("featuresChanged"); // NOI18N } } final List<Feature> list = new ArrayList<Feature>(); list.addAll(fce.getEventFeatures()); for (final Feature elem : list) { reconsiderFeature(elem); } showHandles(false); } /** * Does a complete reconciliation of the PFeature assigned to a feature from the FeatureCollectionEvent. Calls * following PFeature-methods: syncGeometry(), visualize(), resetInfoNodePosition() and refreshInfoNode() * * @param fce featurecollectionevent with features to reconsile */ @Override public void featureReconsiderationRequested(final FeatureCollectionEvent fce) { for (final Feature f : fce.getEventFeatures()) { if (f != null) { final PFeature node = pFeatureHM.get(f); if (node != null) { node.syncGeometry(); node.visualize(); node.resetInfoNodePosition(); node.refreshInfoNode(); repaint(); // für Mehrfachzeichnung der Handles verantworlich ?? // showHandles(false); } } } } /** * Adds all features from the FeatureCollectionEvent to the mappingcomponent. Paints handles at the end. Former * synchronized method. * * @param fce FeatureCollectionEvent with features to add */ @Override public void featuresAdded(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("firefeaturesAdded (old disabled)"); // NOI18N } } // Attention: Bug-Gefahr !!! TODO // addFeaturesToMap(fce.getEventFeatures().toArray(new Feature[0])); // if(DEBUG)log.debug("featuresAdded()"); } /** * Method is deprecated and deactivated. Does nothing!! * * @deprecated DOCUMENT ME! */ @Override @Deprecated public void featureCollectionChanged() { // if (getFeatureCollection() instanceof DefaultFeatureCollection) { // DefaultFeatureCollection coll=((DefaultFeatureCollection)getFeatureCollection()); // Vector<String> layers=coll.getAllLayers(); // for (String layer :layers) { // if (!featureLayers.keySet().contains(layer)) { // PLayer pLayer=new PLayer(); // featureLayer.addChild(pLayer); // featureLayers.put(layer,pLayer); // } // } // } } /** * Clears the PFeatureHashmap and removes all PFeatures from the featurelayer. Does a * checkFeatureSupportingRasterServiceAfterFeatureRemoval() on all features from the given FeatureCollectionEvent. * * @param fce FeatureCollectionEvent with features to check for a remaining supporting rasterservice */ @Override public void allFeaturesRemoved(final FeatureCollectionEvent fce) { for (final PFeature feature : pFeatureHM.values()) { feature.cleanup(); } stickyPNodes.clear(); pFeatureHM.clear(); featureLayer.removeAllChildren(); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); } /** * Removes all features of the given FeatureCollectionEvent from the mappingcomponent. Checks for remaining * supporting rasterservices and paints handles at the end. * * @param fce FeatureCollectionEvent with features to remove */ @Override public void featuresRemoved(final FeatureCollectionEvent fce) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("featuresRemoved"); // NOI18N } } removeFeatures(fce.getEventFeatures()); checkFeatureSupportingRasterServiceAfterFeatureRemoval(fce); showHandles(false); } /** * Checks after removing one or more features from the mappingcomponent which rasterservices became unnecessary and * which need a refresh. * * @param fce FeatureCollectionEvent with removed features */ private void checkFeatureSupportingRasterServiceAfterFeatureRemoval(final FeatureCollectionEvent fce) { final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRemoved = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServicesWhichShouldBeRefreshed = new HashSet<FeatureAwareRasterService>(); final HashSet<FeatureAwareRasterService> rasterServices = new HashSet<FeatureAwareRasterService>(); for (final Feature f : getFeatureCollection().getAllFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getAllFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } rasterServices.add(rs); // DANGER } } for (final Feature f : fce.getEventFeatures()) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("getEventFeatures() Feature:SupportingRasterService:" + f + ":" + rs); // NOI18N } } if (rasterServices.contains(rs)) { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRefreshed.add((FeatureAwareRasterService)r); } } } else { for (final Object o : getMappingModel().getRasterServices().values()) { final MapService r = (MapService)o; if (r.equals(rs)) { rasterServicesWhichShouldBeRemoved.add((FeatureAwareRasterService)r); } } } } } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRemoved) { getMappingModel().removeLayer(frs); } for (final FeatureAwareRasterService frs : rasterServicesWhichShouldBeRefreshed) { handleMapService(0, frs, true); } } // public void showFeatureCollection(Feature[] features) { // com.vividsolutions.jts.geom.Envelope env=computeFeatureEnvelope(features); // showFeatureCollection(features,env); // } // public void showFeatureCollection(Feature[] f,com.vividsolutions.jts.geom.Envelope featureEnvelope) { // selectedFeature=null; // handleLayer.removeAllChildren(); // //setRasterServiceLayerImagesVisibility(false); // Envelope eSquare=null; // HashSet<Feature> featureSet=new HashSet<Feature>(); // featureSet.addAll(holdFeatures); // featureSet.addAll(java.util.Arrays.asList(f)); // Feature[] features=featureSet.toArray(new Feature[0]); // // pFeatureHM.clear(); // addFeaturesToMap(features); // zoomToFullFeatureCollectionBounds(); // // } /** * Creates new PFeatures for all features in the given array and adds them to the PFeatureHashmap. Then adds the * PFeature to the featurelayer. * * <p>DANGER: there's a bug risk here because the method runs in an own thread! It is possible that a PFeature of a * feature is demanded but not yet added to the hashmap which causes in most cases a NullPointerException!</p> * * @param features array with features to add */ public void addFeaturesToMap(final Feature[] features) { // Runnable r = new Runnable() { // // @Override // public void run() { final double local_clip_offset_y = clip_offset_y; final double local_clip_offset_x = clip_offset_x; /// Hier muss der layer bestimmt werdenn for (int i = 0; i < features.length; ++i) { final PFeature p = new PFeature( features[i], getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); try { if (features[i] instanceof StyledFeature) { p.setTransparency(((StyledFeature)(features[i])).getTransparency()); } else { p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); } } catch (Exception e) { p.setTransparency(0.8f); log.info("Fehler beim Setzen der Transparenzeinstellungen", e); // NOI18N } // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) // PFeature p=new PFeature(features[i],(WorldToScreenTransform)null,(double)0,(double)0); p.setViewer(this); // ((PPath)p).setStroke(new BasicStroke(0.5f)); if (features[i].getGeometry() != null) { pFeatureHM.put(p.getFeature(), p); // for (int j = 0; j < p.getCoordArr().length; ++j) { // pFeatureHMbyCoordinate.put(p.getCoordArr()[j], new PFeatureCoordinatePosition(p, j)); // } final int ii = i; EventQueue.invokeLater(new Runnable() { @Override public void run() { featureLayer.addChild(p); if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { // p.moveToBack(); p.moveToFront(); } } }); } } EventQueue.invokeLater(new Runnable() { @Override public void run() { rescaleStickyNodes(); repaint(); fireFeaturesAddedToMap(Arrays.asList(features)); // SuchFeatures in den Vordergrund stellen for (final Feature feature : featureCollection.getAllFeatures()) { if (feature instanceof SearchFeature) { final PFeature pFeature = pFeatureHM.get(feature); pFeature.moveToFront(); } } } }); // } // }; // CismetThreadPool.execute(r); // check whether the feature has a rasterSupportLayer or not for (final Feature f : features) { if ((f instanceof RasterLayerSupportedFeature) && (((RasterLayerSupportedFeature)f).getSupportingRasterService() != null)) { final FeatureAwareRasterService rs = ((RasterLayerSupportedFeature)f).getSupportingRasterService(); if (!getMappingModel().getRasterServices().containsValue(rs)) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("FeatureAwareRasterServiceAdded"); // NOI18N } } rs.setFeatureCollection(getFeatureCollection()); getMappingModel().addLayer(rs); } } } showHandles(false); } // public void addFeaturesToMap(final Feature[] features) { // Runnable r = new Runnable() { // // @Override // public void run() { // double local_clip_offset_y = clip_offset_y; // double local_clip_offset_x = clip_offset_x; // // /// Hier muss der layer bestimmt werdenn // for (int i = 0; i < features.length; ++i) { // final PFeature p = new PFeature(features[i], getWtst(), local_clip_offset_x, local_clip_offset_y, MappingComponent.this); // try { // if (features[i] instanceof StyledFeature) { // p.setTransparency(((StyledFeature) (features[i])).getTransparency()); // } else { // p.setTransparency(cismapPrefs.getLayersPrefs().getAppFeatureLayerTranslucency()); // } // } catch (Exception e) { // p.setTransparency(0.8f); // log.info("Fehler beim Setzen der Transparenzeinstellungen", e); // } // // So kann man es Piccolo überlassen (müsste nur noch ein transformation machen, die die y achse spiegelt) // // PFeature p=new PFeature(features[i],(WorldToScreenTransform)null,(double)0,(double)0); // // p.setViewer(this); // // ((PPath)p).setStroke(new BasicStroke(0.5f)); // if (features[i].getGeometry() != null) { // pFeatureHM.put(p.getFeature(), p); // for (int j = 0; j < p.getCoordArr().length; ++j) { // pFeatureHMbyCoordinate.put(p.getCoordArr()[j], new PFeatureCoordinatePosition(p, j)); // } // final int ii = i; // EventQueue.invokeLater(new Runnable() { // // @Override // public void run() { // featureLayer.addChild(p); // if (!(features[ii].getGeometry() instanceof com.vividsolutions.jts.geom.Point)) { // //p.moveToBack(); // p.moveToFront(); // } // } // }); // } // } // EventQueue.invokeLater(new Runnable() { // // @Override // public void run() { // rescaleStickyNodes(); // repaint(); // fireFeaturesAddedToMap(Arrays.asList(features)); // // // SuchFeatures in den Vordergrund stellen // for (Feature feature : featureCollection.getAllFeatures()) { // if (feature instanceof SearchFeature) { // PFeature pFeature = (PFeature)pFeatureHM.get(feature); // pFeature.moveToFront(); // } // } // } // }); // } // }; // CismetThreadPool.execute(r); // // //check whether the feature has a rasterSupportLayer or not // for (Feature f : features) { // if (f instanceof RasterLayerSupportedFeature && ((RasterLayerSupportedFeature) f).getSupportingRasterService() != null) { // FeatureAwareRasterService rs = ((RasterLayerSupportedFeature) f).getSupportingRasterService(); // if (!getMappingModel().getRasterServices().containsValue(rs)) { // if (DEBUG) { // log.debug("FeatureAwareRasterServiceAdded"); // } // rs.setFeatureCollection(getFeatureCollection()); // getMappingModel().addLayer(rs); // } // } // } // // showHandles(false); // } /** * DOCUMENT ME! * * @param cf DOCUMENT ME! */ private void fireFeaturesAddedToMap(final Collection<Feature> cf) { for (final MapListener curMapListener : mapListeners) { curMapListener.featuresAddedToMap(cf); } } /** * Returns a list of PFeatureCoordinatePositions which are located at the given coordinate. * * @param features c Coordinate * * @return list of PFeatureCoordinatePositions */ // public List<PFeatureCoordinatePosition> getPFeaturesByCoordinates(Coordinate c) { // List<PFeatureCoordinatePosition> l = (List<PFeatureCoordinatePosition>) pFeatureHMbyCoordinate.get(c); // return l; // } /** * Creates an envelope around all features from the given array. * * @param features features to create the envelope around * * @return Envelope com.vividsolutions.jts.geom.Envelope */ private com.vividsolutions.jts.geom.Envelope computeFeatureEnvelope(final Feature[] features) { final PNode root = new PNode(); for (int i = 0; i < features.length; ++i) { final PNode p = PNodeFactory.createPFeature(features[i], this); if (p != null) { root.addChild(p); } } final PBounds ext = root.getFullBounds(); final com.vividsolutions.jts.geom.Envelope env = new com.vividsolutions.jts.geom.Envelope( ext.x, ext.x + ext.width, ext.y, ext.y + ext.height); return env; } /** * Zooms in / out to match the bounds of the featurecollection. */ public void zoomToFullFeatureCollectionBounds() { zoomToFeatureCollection(); } /** * Adds a new cursor to the cursor-hashmap. * * @param mode interactionmode as string * @param cursor cursor-object */ public void putCursor(final String mode, final Cursor cursor) { cursors.put(mode, cursor); } /** * Returns the cursor assigned to the given mode. * * @param mode mode as String * * @return Cursor-object or null */ public Cursor getCursor(final String mode) { return cursors.get(mode); } /** * Adds a new PBasicInputEventHandler for a specific interactionmode. * * @param mode interactionmode as string * @param listener new PBasicInputEventHandler */ public void addInputListener(final String mode, final PBasicInputEventHandler listener) { inputEventListener.put(mode, listener); } /** * Returns the PBasicInputEventHandler assigned to the committed interactionmode. * * @param mode interactionmode as string * * @return PBasicInputEventHandler-object or null */ public PInputEventListener getInputListener(final String mode) { final Object o = inputEventListener.get(mode); if (o instanceof PInputEventListener) { return (PInputEventListener)o; } else { return null; } } /** * Returns whether the features are editable or not. * * @return DOCUMENT ME! */ public boolean isReadOnly() { return readOnly; } /** * Sets all Features ReadOnly use Feature.setEditable(boolean) instead. * * @param readOnly DOCUMENT ME! */ public void setReadOnly(final boolean readOnly) { for (final Object f : featureCollection.getAllFeatures()) { ((Feature)f).setEditable(!readOnly); } this.readOnly = readOnly; handleLayer.repaint(); // if (readOnly==false) { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } snapHandleLayer.removeAllChildren(); // } } /** * Returns the current HandleInteractionMode. * * @return DOCUMENT ME! */ public String getHandleInteractionMode() { return handleInteractionMode; } /** * Changes the HandleInteractionMode. Repaints handles. * * @param handleInteractionMode the new HandleInteractionMode */ public void setHandleInteractionMode(final String handleInteractionMode) { this.handleInteractionMode = handleInteractionMode; showHandles(false); } /** * Returns whether the background is enabled or not. * * @return DOCUMENT ME! */ public boolean isBackgroundEnabled() { return backgroundEnabled; } /** * TODO. * * @param backgroundEnabled DOCUMENT ME! */ public void setBackgroundEnabled(final boolean backgroundEnabled) { if ((backgroundEnabled == false) && (isBackgroundEnabled() == true)) { featureServiceLayerVisible = featureServiceLayer.getVisible(); } this.mapServicelayer.setVisible(backgroundEnabled); this.featureServiceLayer.setVisible(backgroundEnabled && featureServiceLayerVisible); for (int i = 0; i < featureServiceLayer.getChildrenCount(); ++i) { featureServiceLayer.getChild(i).setVisible(backgroundEnabled && featureServiceLayerVisible); } if ((backgroundEnabled != isBackgroundEnabled()) && (isBackgroundEnabled() == false)) { this.queryServices(); } this.backgroundEnabled = backgroundEnabled; } /** * Returns the featurelayer. * * @return DOCUMENT ME! */ public PLayer getFeatureLayer() { return featureLayer; } /** * Adds a PFeature to the PFeatureHashmap. * * @param p PFeature to add */ public void refreshHM(final PFeature p) { pFeatureHM.put(p.getFeature(), p); } /** * Returns the selectedObjectPresenter (PCanvas). * * @return DOCUMENT ME! */ public PCanvas getSelectedObjectPresenter() { return selectedObjectPresenter; } /** * If f != null it calls the reconsiderFeature()-method of the featurecollection. * * @param f feature to reconcile */ public void reconsiderFeature(final Feature f) { if (f != null) { featureCollection.reconsiderFeature(f); } } /** * Removes all features of the collection from the hashmap. * * @param fc collection of features to remove */ public void removeFeatures(final Collection<Feature> fc) { featureLayer.setVisible(false); for (final Feature elem : fc) { removeFromHM(elem); } featureLayer.setVisible(true); } /** * Removes a Feature from the PFeatureHashmap. Uses the delivered feature as hashmap-key. * * @param f feature of the Pfeature that should be deleted */ public void removeFromHM(final Feature f) { final PFeature pf = pFeatureHM.get(f); if (pf != null) { pf.cleanup(); pFeatureHM.remove(f); stickyPNodes.remove(pf); try { log.info("Entferne Feature " + f); // NOI18N featureLayer.removeChild(pf); } catch (Exception ex) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Remove Child ging Schief. Ist beim Splitten aber normal.", ex); // NOI18N } } } } else { log.warn("Feature war nicht in pFeatureHM"); // NOI18N } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("pFeatureHM" + pFeatureHM); // NOI18N } } } /** * Zooms to the current selected node. * * @deprecated DOCUMENT ME! */ public void zoomToSelectedNode() { zoomToSelection(); } /** * Zooms to the current selected features. */ public void zoomToSelection() { final Collection<Feature> selection = featureCollection.getSelectedFeatures(); zoomToAFeatureCollection(selection, true, false); } /** * Zooms to a specific featurecollection. * * @param collection the featurecolltion * @param withHistory should the zoomaction be undoable * @param fixedScale fixedScale */ public void zoomToAFeatureCollection(final Collection<Feature> collection, final boolean withHistory, final boolean fixedScale) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("zoomToAFeatureCollection"); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } boolean first = true; Geometry g = null; for (final Feature f : collection) { if (first) { g = f.getGeometry().getEnvelope(); if (f instanceof Bufferable) { g = g.buffer(((Bufferable)f).getBuffer()); } first = false; } else { if (f.getGeometry() != null) { Geometry geometry = f.getGeometry().getEnvelope(); if (f instanceof Bufferable) { geometry = geometry.buffer(((Bufferable)f).getBuffer()); } g = g.getEnvelope().union(geometry); } } } if (g != null) { // dreisatz.de final double hBuff = g.getEnvelopeInternal().getHeight() / ((double)getHeight()) * 10; final double vBuff = g.getEnvelopeInternal().getWidth() / ((double)getWidth()) * 10; if ((getHeight() == 0) || (getWidth() == 0)) { log.fatal("DIVISION BY ZERO"); // NOI18N } double buff = 0; if (hBuff > vBuff) { buff = hBuff; } else { buff = vBuff; } g = g.buffer(buff); final BoundingBox bb = new BoundingBox(g); gotoBoundingBox(bb, withHistory, !fixedScale, animationDuration); } } /** * Deletes all present handles from the handlelayer. Tells all selected features in the featurecollection to create * their handles and to add them to the handlelayer. * * @param waitTillAllAnimationsAreComplete wait until all animations are completed before create the handles */ public void showHandles(final boolean waitTillAllAnimationsAreComplete) { // are there features selected? if (featureCollection.getSelectedFeatures().size() > 0) { // DANGER Mehrfachzeichnen von Handles durch parallelen Aufruf final Runnable handle = new Runnable() { @Override public void run() { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); while (getAnimating() && waitTillAllAnimationsAreComplete) { try { Thread.currentThread().sleep(10); } catch (Exception e) { log.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (featureCollection.areFeaturesEditable() && (getInteractionMode().equals(SELECT) || getInteractionMode().equals(LINEMEASUREMENT) || getInteractionMode().equals(PAN) || getInteractionMode().equals(ZOOM) || getInteractionMode().equals(ALKIS_PRINT) || getInteractionMode().equals(SPLIT_POLYGON))) { // Handles für alle selektierten Features der Collection hinzufügen if (getHandleInteractionMode().equals(ROTATE_POLYGON)) { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature instanceof Feature) && ((Feature)selectedFeature).isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { ((PFeature)pFeatureHM.get(selectedFeature)).addRotationHandles( handleLayer); } }); } else { log.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } } } } else { final LinkedHashSet<Feature> copy = new LinkedHashSet( featureCollection.getSelectedFeatures()); for (final Feature selectedFeature : copy) { if ((selectedFeature != null) && selectedFeature.isEditable()) { if (pFeatureHM.get(selectedFeature) != null) { // manipulates gui -> edt EventQueue.invokeLater(new Runnable() { @Override public void run() { try { ((PFeature)pFeatureHM.get(selectedFeature)).addHandles( handleLayer); } catch (Exception e) { log.error("Error bei addHandles: ", e); // NOI18N } } }); } else { log.warn("pFeatureHM.get(" + selectedFeature + ")==null"); // NOI18N } // DANGER mit break werden nur die Handles EINES slektierten Features angezeigt // wird break auskommentiert werden jedoch zu viele Handles angezeigt break; } } } } } }; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("showHandles", new CurrentStackTrace()); // NOI18N } } CismetThreadPool.execute(handle); } else { // alle bisherigen Handles entfernen EventQueue.invokeLater(new Runnable() { @Override public void run() { try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } } }); } } /** * Will return a PureNewFeature if there is only one in the featurecollection else null. * * @return DOCUMENT ME! */ public PFeature getSolePureNewFeature() { int counter = 0; PFeature sole = null; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object o = it.next(); if (o instanceof PFeature) { if (((PFeature)o).getFeature() instanceof PureNewFeature) { ++counter; sole = ((PFeature)o); } } } if (counter == 1) { return sole; } else { return null; } } /** * Sets the visibility of the children of the rasterservicelayer. * * @param visible true sets visible */ private void setRasterServiceLayerImagesVisibility(final boolean visible) { final Iterator it = mapServicelayer.getChildrenIterator(); while (it.hasNext()) { final Object o = it.next(); if (o instanceof XPImage) { ((XPImage)o).setVisible(visible); } } } /** * Returns the temporary featurelayer. * * @return DOCUMENT ME! */ public PLayer getTmpFeatureLayer() { return tmpFeatureLayer; } /** * Assigns a new temporary featurelayer. * * @param tmpFeatureLayer PLayer */ public void setTmpFeatureLayer(final PLayer tmpFeatureLayer) { this.tmpFeatureLayer = tmpFeatureLayer; } /** * Returns whether the grid is enabled or not. * * @return DOCUMENT ME! */ public boolean isGridEnabled() { return gridEnabled; } /** * Enables or disables the grid. * * @param gridEnabled true, to enable the grid */ public void setGridEnabled(final boolean gridEnabled) { this.gridEnabled = gridEnabled; } /** * Returns a String from two double-values. Serves the visualization. * * @param x X-coordinate * @param y Y-coordinate * * @return a Strin-object like "(X,Y)" */ public static String getCoordinateString(final double x, final double y) { final DecimalFormat df = new DecimalFormat("0.00"); // NOI18N final DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); df.setDecimalFormatSymbols(dfs); return "(" + df.format(x) + "," + df.format(y) + ")"; // NOI18N } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHandleLayer() { return handleLayer; } /** * DOCUMENT ME! * * @param handleLayer DOCUMENT ME! */ public void setHandleLayer(final PLayer handleLayer) { this.handleLayer = handleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingEnabled() { return visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingEnabled DOCUMENT ME! */ public void setVisualizeSnappingEnabled(final boolean visualizeSnappingEnabled) { this.visualizeSnappingEnabled = visualizeSnappingEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isVisualizeSnappingRectEnabled() { return visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @param visualizeSnappingRectEnabled DOCUMENT ME! */ public void setVisualizeSnappingRectEnabled(final boolean visualizeSnappingRectEnabled) { this.visualizeSnappingRectEnabled = visualizeSnappingRectEnabled; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getSnappingRectSize() { return snappingRectSize; } /** * DOCUMENT ME! * * @param snappingRectSize DOCUMENT ME! */ public void setSnappingRectSize(final int snappingRectSize) { this.snappingRectSize = snappingRectSize; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getSnapHandleLayer() { return snapHandleLayer; } /** * DOCUMENT ME! * * @param snapHandleLayer DOCUMENT ME! */ public void setSnapHandleLayer(final PLayer snapHandleLayer) { this.snapHandleLayer = snapHandleLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isSnappingEnabled() { return snappingEnabled; } /** * DOCUMENT ME! * * @param snappingEnabled DOCUMENT ME! */ public void setSnappingEnabled(final boolean snappingEnabled) { this.snappingEnabled = snappingEnabled; setVisualizeSnappingEnabled(snappingEnabled); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getFeatureServiceLayer() { return featureServiceLayer; } /** * DOCUMENT ME! * * @param featureServiceLayer DOCUMENT ME! */ public void setFeatureServiceLayer(final PLayer featureServiceLayer) { this.featureServiceLayer = featureServiceLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getAnimationDuration() { return animationDuration; } /** * DOCUMENT ME! * * @param animationDuration DOCUMENT ME! */ public void setAnimationDuration(final int animationDuration) { this.animationDuration = animationDuration; } /** * DOCUMENT ME! * * @param prefs DOCUMENT ME! */ @Deprecated public void setPreferences(final CismapPreferences prefs) { log.warn("involing deprecated operation setPreferences()"); // NOI18N cismapPrefs = prefs; // DefaultMappingModel mm = new DefaultMappingModel(); final ActiveLayerModel mm = new ActiveLayerModel(); final LayersPreferences layersPrefs = prefs.getLayersPrefs(); final GlobalPreferences globalPrefs = prefs.getGlobalPrefs(); setSnappingRectSize(globalPrefs.getSnappingRectSize()); setSnappingEnabled(globalPrefs.isSnappingEnabled()); setVisualizeSnappingEnabled(globalPrefs.isSnappingPreviewEnabled()); setAnimationDuration(globalPrefs.getAnimationDuration()); setInteractionMode(globalPrefs.getStartMode()); // mm.setInitialBoundingBox(globalPrefs.getInitialBoundingBox()); mm.addHome(globalPrefs.getInitialBoundingBox()); final Crs crs = new Crs(); crs.setCode(globalPrefs.getInitialBoundingBox().getSrs()); crs.setName(globalPrefs.getInitialBoundingBox().getSrs()); crs.setShortname(globalPrefs.getInitialBoundingBox().getSrs()); mm.setSrs(crs); final TreeMap raster = layersPrefs.getRasterServices(); if (raster != null) { final Iterator it = raster.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = raster.get(key); if (o instanceof MapService) { // mm.putMapService(((Integer) key).intValue(), (MapService) o); mm.addLayer((RetrievalServiceLayer)o); } } } final TreeMap features = layersPrefs.getFeatureServices(); if (features != null) { final Iterator it = features.keySet().iterator(); while (it.hasNext()) { final Object key = it.next(); final Object o = features.get(key); if (o instanceof MapService) { // TODO // mm.putMapService(((Integer) key).intValue(), (MapService) o); mm.addLayer((RetrievalServiceLayer)o); } } } setMappingModel(mm); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public CismapPreferences getCismapPrefs() { return cismapPrefs; } /** * DOCUMENT ME! * * @param duration DOCUMENT ME! * @param animationDuration DOCUMENT ME! * @param what DOCUMENT ME! * @param number DOCUMENT ME! */ public void flash(final int duration, final int animationDuration, final int what, final int number) { } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getDragPerformanceImproverLayer() { return dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @param dragPerformanceImproverLayer DOCUMENT ME! */ public void setDragPerformanceImproverLayer(final PLayer dragPerformanceImproverLayer) { this.dragPerformanceImproverLayer = dragPerformanceImproverLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ @Deprecated public PLayer getRasterServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getMapServiceLayer() { return mapServicelayer; } /** * DOCUMENT ME! * * @param rasterServiceLayer DOCUMENT ME! */ public void setRasterServiceLayer(final PLayer rasterServiceLayer) { this.mapServicelayer = rasterServiceLayer; } /** * DOCUMENT ME! * * @param f DOCUMENT ME! */ public void showGeometryInfoPanel(final Feature f) { } /** * Adds a PropertyChangeListener to the listener list. * * @param l The listener to add. */ @Override public void addPropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.addPropertyChangeListener(l); } /** * Removes a PropertyChangeListener from the listener list. * * @param l The listener to remove. */ @Override public void removePropertyChangeListener(final PropertyChangeListener l) { propertyChangeSupport.removePropertyChangeListener(l); } /** * Setter for property taskCounter. former synchronized method */ public void fireActivityChanged() { propertyChangeSupport.firePropertyChange("activityChanged", null, null); // NOI18N } /** * Returns true, if there's still one layercontrol running. Else false; former synchronized method * * @return DOCUMENT ME! */ public boolean isRunning() { for (final LayerControl lc : layerControls) { if (lc.isRunning()) { return true; } } return false; } /** * Sets the visibility of all infonodes. * * @param visible true, if infonodes should be visible */ public void setInfoNodesVisible(final boolean visible) { infoNodesVisible = visible; for (final Iterator it = featureLayer.getChildrenIterator(); it.hasNext();) { final Object elem = it.next(); if (elem instanceof PFeature) { ((PFeature)elem).setInfoNodeVisible(visible); } } if (DEBUG) { if (log.isDebugEnabled()) { log.debug("setInfoNodesVisible()"); // NOI18N } } rescaleStickyNodes(); } /** * Adds an object to the historymodel. * * @param o Object to add */ @Override public void addToHistory(final Object o) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("addToHistory:" + o.toString()); // NOI18N } } historyModel.addToHistory(o); } /** * Removes a specific HistoryModelListener from the historymodel. * * @param hml HistoryModelListener */ @Override public void removeHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.removeHistoryModelListener(hml); } /** * Adds aHistoryModelListener to the historymodel. * * @param hml HistoryModelListener */ @Override public void addHistoryModelListener(final de.cismet.tools.gui.historybutton.HistoryModelListener hml) { historyModel.addHistoryModelListener(hml); } /** * Sets the maximum value of saved historyactions. * * @param max new integer value */ @Override public void setMaximumPossibilities(final int max) { historyModel.setMaximumPossibilities(max); } /** * Redos the last undone historyaction. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the forward-action */ @Override public Object forward(final boolean external) { final PBounds fwd = (PBounds)historyModel.forward(external); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("HistoryModel.forward():" + fwd); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(fwd); } return fwd; } /** * Undos the last action. * * @param external true, if fireHistoryChanged-action should be fired * * @return PBounds of the back-action */ @Override public Object back(final boolean external) { final PBounds back = (PBounds)historyModel.back(external); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("HistoryModel.back():" + back); // NOI18N } } if (external) { this.gotoBoundsWithoutHistory(back); } return back; } /** * Returns true, if it's possible to redo an action. * * @return DOCUMENT ME! */ @Override public boolean isForwardPossible() { return historyModel.isForwardPossible(); } /** * Returns true, if it's possible to undo an action. * * @return DOCUMENT ME! */ @Override public boolean isBackPossible() { return historyModel.isBackPossible(); } /** * Returns a vector with all redo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getForwardPossibilities() { return historyModel.getForwardPossibilities(); } /** * Returns the current element of the historymodel. * * @return DOCUMENT ME! */ @Override public Object getCurrentElement() { return historyModel.getCurrentElement(); } /** * Returns a vector with all undo-possibilities. * * @return DOCUMENT ME! */ @Override public Vector getBackPossibilities() { return historyModel.getBackPossibilities(); } /** * Returns whether an internallayerwidget is available. * * @return DOCUMENT ME! */ @Deprecated public boolean isInternalLayerWidgetAvailable() { return this.getInternalWidget(LAYERWIDGET) != null; } /** * Sets the variable, if an internallayerwidget is available or not. * * @param internalLayerWidgetAvailable true, if available */ @Deprecated public void setInternalLayerWidgetAvailable(final boolean internalLayerWidgetAvailable) { if (!internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) != null)) { this.removeInternalWidget(LAYERWIDGET); } else if (internalLayerWidgetAvailable && (this.getInternalWidget(LAYERWIDGET) == null)) { final NewSimpleInternalLayerWidget simpleInternalLayerWidget = new NewSimpleInternalLayerWidget( MappingComponent.this); MappingComponent.this.addInternalWidget( LAYERWIDGET, MappingComponent.POSITION_SOUTHEAST, simpleInternalLayerWidget); } } @Override public void mapServiceLayerStructureChanged(final de.cismet.cismap.commons.MappingModelEvent mme) { } /** * Removes the mapservice from the rasterservicelayer. * * @param rasterService the removing mapservice */ @Override public void mapServiceRemoved(final MapService rasterService) { try { mapServicelayer.removeChild(rasterService.getPNode()); System.gc(); } catch (Exception e) { log.warn("Fehler bei mapServiceRemoved", e); // NOI18N } } /** * Adds the commited mapservice on the last position to the rasterservicelayer. * * @param mapService the new mapservice */ @Override public void mapServiceAdded(final MapService mapService) { addMapService(mapService, mapServicelayer.getChildrenCount()); if (mapService instanceof FeatureAwareRasterService) { ((FeatureAwareRasterService)mapService).setFeatureCollection(getFeatureCollection()); } if ((mapService instanceof ServiceLayer) && ((ServiceLayer)mapService).isEnabled()) { handleMapService(0, mapService, false); } } /** * Returns the current OGC scale. * * @return DOCUMENT ME! */ public double getCurrentOGCScale() { // funktioniert nur bei metrischen SRS's final double h = getCamera().getViewBounds().getHeight() / getHeight(); final double w = getCamera().getViewBounds().getWidth() / getWidth(); // if(DEBUG)log.debug("H�he:"+getHeight()+" Breite:"+getWidth()); // if(DEBUG)log.debug("H�heReal:"+getCamera().getViewBounds().getHeight()+" BreiteReal:"+getCamera().getViewBounds().getWidth()); return Math.sqrt((h * h) + (w * w)); // Math.sqrt((getWidth()*getWidth())*2); } /** * Returns the current BoundingBox. * * @return DOCUMENT ME! */ public BoundingBox getCurrentBoundingBox() { if (fixedBoundingBox != null) { return fixedBoundingBox; } else { try { final PBounds bounds = getCamera().getViewBounds(); final double x1 = wtst.getWorldX(bounds.getX()); final double y1 = wtst.getWorldY(bounds.getY()); final double x2 = x1 + bounds.width; final double y2 = y1 - bounds.height; currentBoundingBox = new BoundingBox(x1, y1, x2, y2); // if(DEBUG)log.debug("getCurrentBoundingBox()" + currentBoundingBox + "(" + (y2 - y1) + "," + (x2 - // x1) + ")", new CurrentStackTrace()); return currentBoundingBox; } catch (Throwable t) { log.error("Fehler in getCurrentBoundingBox()", t); // NOI18N return null; } } } /** * Returns a BoundingBox with a fixed size. * * @return DOCUMENT ME! */ public BoundingBox getFixedBoundingBox() { return fixedBoundingBox; } /** * Assigns fixedBoundingBox a new value. * * @param fixedBoundingBox new boundingbox */ public void setFixedBoundingBox(final BoundingBox fixedBoundingBox) { this.fixedBoundingBox = fixedBoundingBox; } /** * Paints the outline of the forwarded BoundingBox. * * @param bb BoundingBox */ public void outlineArea(final BoundingBox bb) { outlineArea(bb, null); } /** * Paints the outline of the forwarded PBounds. * * @param b PBounds */ public void outlineArea(final PBounds b) { outlineArea(b, null); } /** * Paints a filled rectangle of the area of the forwarded BoundingBox. * * @param bb BoundingBox * @param fillingPaint Color to fill the rectangle */ public void outlineArea(final BoundingBox bb, final Paint fillingPaint) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } outlineArea(pb, fillingPaint); } /** * Paints a filled rectangle of the area of the forwarded PBounds. * * @param b PBounds to paint * @param fillingColor Color to fill the rectangle */ public void outlineArea(final PBounds b, final Paint fillingColor) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { highlightingLayer.removeAllChildren(); } } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(fillingColor); rectangle.setStroke(new FixedWidthStroke()); rectangle.setStrokePaint(new Color(100, 100, 100, 255)); rectangle.setPathTo(b); highlightingLayer.addChild(rectangle); } } /** * Highlights the delivered BoundingBox. Calls highlightArea(PBounds b) internally. * * @param bb BoundingBox to highlight */ public void highlightArea(final BoundingBox bb) { PBounds pb = null; if (bb != null) { pb = new PBounds(wtst.getScreenX(bb.getX1()), wtst.getScreenY(bb.getY2()), bb.getX2() - bb.getX1(), bb.getY2() - bb.getY1()); } highlightArea(pb); } /** * Highlights the delivered PBounds by painting over with a transparent white. * * @param b PBounds to hightlight */ private void highlightArea(final PBounds b) { if (b == null) { if (highlightingLayer.getChildrenCount() > 0) { } highlightingLayer.animateToTransparency(0, animationDuration); highlightingLayer.removeAllChildren(); } else { highlightingLayer.removeAllChildren(); highlightingLayer.setTransparency(1); final PPath rectangle = new PPath(); rectangle.setPaint(new Color(255, 255, 255, 100)); rectangle.setStroke(null); // rectangle.setStroke(new BasicStroke((float)(1/ getCamera().getViewScale()))); // rectangle.setStrokePaint(new Color(255,255,255,20)); rectangle.setPathTo(this.getCamera().getViewBounds()); highlightingLayer.addChild(rectangle); rectangle.animateToBounds(b.x, b.y, b.width, b.height, this.animationDuration); } } /** * Paints a crosshair at the delivered coordinate. Calculates a Point from the coordinate and calls * crossHairPoint(Point p) internally. * * @param c coordinate of the crosshair's venue */ public void crossHairPoint(final Coordinate c) { Point p = null; if (c != null) { p = new Point((int)wtst.getScreenX(c.x), (int)wtst.getScreenY(c.y)); } crossHairPoint(p); } /** * Paints a crosshair at the delivered point. * * @param p point of the crosshair's venue */ public void crossHairPoint(final Point p) { if (p == null) { if (crosshairLayer.getChildrenCount() > 0) { crosshairLayer.removeAllChildren(); } } else { crosshairLayer.removeAllChildren(); crosshairLayer.setTransparency(1); final PPath lineX = new PPath(); final PPath lineY = new PPath(); lineX.setStroke(new FixedWidthStroke()); lineX.setStrokePaint(new Color(100, 100, 100, 255)); lineY.setStroke(new FixedWidthStroke()); lineY.setStrokePaint(new Color(100, 100, 100, 255)); // PBounds current=getCurrentBoundingBox().getPBounds(getWtst()); final PBounds current = getCamera().getViewBounds(); final PBounds x = new PBounds(PBounds.OUT_LEFT - current.width, p.y, 2 * current.width, 1); final PBounds y = new PBounds(p.x, PBounds.OUT_TOP - current.height, 1, current.height * 2); lineX.setPathTo(x); crosshairLayer.addChild(lineX); lineY.setPathTo(y); crosshairLayer.addChild(lineY); } } @Override public Element getConfiguration() { if (log.isDebugEnabled()) { log.debug("writing configuration <cismapMappingPreferences>"); // NOI18N } final Element ret = new Element("cismapMappingPreferences"); // NOI18N ret.setAttribute("interactionMode", getInteractionMode()); // NOI18N ret.setAttribute( "creationMode", ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).getMode()); // NOI18N ret.setAttribute("handleInteractionMode", getHandleInteractionMode()); // NOI18N ret.setAttribute("snapping", new Boolean(isSnappingEnabled()).toString()); // NOI18N // Position final Element currentPosition = new Element("Position"); // NOI18N // if (Double.isNaN(getCurrentBoundingBox().getX1())|| // Double.isNaN(getCurrentBoundingBox().getX2())|| // Double.isNaN(getCurrentBoundingBox().getY1())|| // Double.isNaN(getCurrentBoundingBox().getY2())) { // log.warn("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // gotoInitialBoundingBox(); // } currentPosition.addContent(currentBoundingBox.getJDOMElement()); currentPosition.setAttribute("CRS", CismapBroker.getInstance().getSrs().getCode()); // currentPosition.addContent(getCurrentBoundingBox().getJDOMElement()); ret.addContent(currentPosition); // Crs final Element crsListElement = new Element("crsList"); for (final Crs tmp : crsList) { crsListElement.addContent(tmp.getJDOMElement()); } ret.addContent(crsListElement); if (printingSettingsDialog != null) { ret.addContent(printingSettingsDialog.getConfiguration()); } // save internal widgets status final Element widgets = new Element("InternalWidgets"); // NOI18N for (final String name : this.internalWidgets.keySet()) { final Element widget = new Element("Widget"); // NOI18N widget.setAttribute("name", name); // NOI18N widget.setAttribute("position", String.valueOf(this.internalWidgetPositions.get(name))); // NOI18N widget.setAttribute("visible", String.valueOf(this.getInternalWidget(name).isVisible())); // NOI18N widgets.addContent(widget); } ret.addContent(widgets); return ret; } @Override public void masterConfigure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N // CRS List try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); crsList.add(s); if (s.isSelected() && s.isMetric()) { try { transformer = new CrsTransformer(s.getCode()); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (Exception skip) { log.error("Error while reading the crs list", skip); // NOI18N } if (transformer == null) { log.warn("No metric default crs found. Use EPSG:31466 to calculate geometry lengths and scales"); try { transformer = new CrsTransformer("EPSG:31466"); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs EPSG:31466", ex); } } // HOME try { if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); final Iterator<Element> it = prefs.getChildren("home").iterator(); // NOI18N if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Es gibt " + prefs.getChildren("home").size() + " Home Einstellungen"); // NOI18N } } while (it.hasNext()) { final Element elem = it.next(); final String srs = elem.getAttribute("srs").getValue(); // NOI18N boolean metric = false; try { metric = elem.getAttribute("metric").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { log.warn("Metric hat falschen Syntax", dce); // NOI18N } boolean defaultVal = false; try { defaultVal = elem.getAttribute("default").getBooleanValue(); // NOI18N } catch (DataConversionException dce) { log.warn("default hat falschen Syntax", dce); // NOI18N } final XBoundingBox xbox = new XBoundingBox(elem, srs, metric); alm.addHome(xbox); if (defaultVal) { Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(srs)) { crsObject = tmp; break; } } if (crsObject == null) { log.error("CRS " + srs + " from the default home is not found in the crs list"); crsObject = new Crs(srs, srs, srs, true, false); crsList.add(crsObject); } alm.setSrs(crsObject); alm.setDefaultSrs(crsObject); CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } } } } catch (Throwable t) { log.error("Fehler beim MasterConfigure der MappingComponent", t); // NOI18N } try { final List scalesList = prefs.getChild("printing").getChildren("scale"); // NOI18N scales.clear(); for (final Object elem : scalesList) { if (elem instanceof Element) { final Scale s = new Scale((Element)elem); scales.add(s); } } } catch (Exception skip) { log.error("Fehler beim Lesen von Scale", skip); // NOI18N } // Und jetzt noch die PriningEinstellungen initPrintingDialogs(); printingSettingsDialog.masterConfigure(prefs); } /** * Configurates this MappingComponent. * * @param e JDOM-Element with configuration */ @Override public void configure(final Element e) { final Element prefs = e.getChild("cismapMappingPreferences"); // NOI18N try { final List crsElements = prefs.getChild("crsList").getChildren("crs"); // NOI18N crsList.clear(); for (final Object elem : crsElements) { if (elem instanceof Element) { final Crs s = new Crs((Element)elem); if (!crsList.contains(s)) { crsList.add(s); } if (s.isSelected() && s.isMetric()) { try { transformer = new CrsTransformer(s.getCode()); } catch (Exception ex) { log.error("Cannot create a GeoTransformer for the crs " + s.getCode(), ex); } } } } } catch (Exception skip) { log.error("Error while reading the crs list", skip); // NOI18N } // InteractionMode try { final String interactMode = prefs.getAttribute("interactionMode").getValue(); // NOI18N setInteractionMode(interactMode); if (interactMode.equals(MappingComponent.NEW_POLYGON)) { try { final String creationMode = prefs.getAttribute("creationMode").getValue(); // NOI18N ((CreateNewGeometryListener)getInputListener(MappingComponent.NEW_POLYGON)).setMode(creationMode); } catch (Throwable t) { log.warn("Fehler beim Setzen des CreationInteractionMode", t); // NOI18N } } } catch (Throwable t) { log.warn("Fehler beim Setzen des InteractionMode", t); // NOI18N } try { final String handleInterMode = prefs.getAttribute("handleInteractionMode").getValue(); // NOI18N setHandleInteractionMode(handleInterMode); } catch (Throwable t) { log.warn("Fehler beim Setzen des HandleInteractionMode", t); // NOI18N } try { final boolean snapping = prefs.getAttribute("snapping").getBooleanValue(); // NOI18N log.info("snapping=" + snapping); // NOI18N setSnappingEnabled(snapping); setVisualizeSnappingEnabled(snapping); setInGlueIdenticalPointsMode(snapping); } catch (Throwable t) { log.warn("Fehler beim setzen von snapping und Konsorten", t); // NOI18N } // aktuelle Position try { final Element pos = prefs.getChild("Position"); // NOI18N final BoundingBox b = new BoundingBox(pos); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("Position:" + b); // NOI18N } } final PBounds pb = b.getPBounds(getWtst()); if (DEBUG) { if (log.isDebugEnabled()) { log.debug("PositionPb:" + pb); // NOI18N } } if (Double.isNaN(b.getX1()) || Double.isNaN(b.getX2()) || Double.isNaN(b.getY1()) || Double.isNaN(b.getY2())) { log.fatal("BUGFINDER:Es war ein Wert in der BoundingBox NaN. Setze auf HOME"); // NOI18N // gotoInitialBoundingBox(); this.currentBoundingBox = getMappingModel().getInitialBoundingBox(); final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); addToHistory(new PBoundsWithCleverToString( new PBounds(currentBoundingBox.getPBounds(wtst)), wtst, crsCode)); } else { // set the current crs final Attribute crsAtt = pos.getAttribute("CRS"); if (crsAtt != null) { final String currentCrs = crsAtt.getValue(); Crs crsObject = null; for (final Crs tmp : crsList) { if (tmp.getCode().equals(currentCrs)) { crsObject = tmp; break; } } if (crsObject == null) { log.error("CRS " + currentCrs + " from the position element is not found in the crs list"); } final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); if (alm instanceof ActiveLayerModel) { alm.setSrs(crsObject); } CismapBroker.getInstance().setSrs(crsObject); wtst = null; getWtst(); } this.currentBoundingBox = b; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("added to History" + b); // NOI18N } } final String crsCode = ((pos.getAttribute("CRS") != null) ? pos.getAttribute("CRS").getValue() : null); // addToHistory(new PBoundsWithCleverToString(new PBounds(currentBoundingBox.getPBounds(wtst)), wtst, crsCode )); // final BoundingBox bb=b; // EventQueue.invokeLater(new Runnable() { // public void run() { // gotoBoundingBoxWithHistory(bb); // } // }); } } catch (Throwable t) { log.error("Fehler beim lesen der aktuellen Position", t); // NOI18N // EventQueue.invokeLater(new Runnable() { // public void run() { // gotoBoundingBoxWithHistory(getMappingModel().getInitialBoundingBox()); this.currentBoundingBox = getMappingModel().getInitialBoundingBox(); // } // }); } if (printingSettingsDialog != null) { printingSettingsDialog.configure(prefs); } try { final Element widgets = prefs.getChild("InternalWidgets"); // NOI18N if (widgets != null) { for (final Object widget : widgets.getChildren()) { final String name = ((Element)widget).getAttribute("name").getValue(); // NOI18N final boolean visible = ((Element)widget).getAttribute("visible").getBooleanValue(); // NOI18N this.showInternalWidget(name, visible, 0); } } } catch (Throwable t) { log.warn("could not enable internal widgets: " + t, t); // NOI18N } } /** * Zooms to all features of the mappingcomponents featurecollection. If fixedScale is true, the mappingcomponent * will only pan to the featurecollection and not zoom. * * @param fixedScale true, if zoom is not allowed */ public void zoomToFeatureCollection(final boolean fixedScale) { zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, fixedScale); } /** * Zooms to all features of the mappingcomponents featurecollection. */ public void zoomToFeatureCollection() { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("zoomToFeatureCollection"); // NOI18N } } zoomToAFeatureCollection(featureCollection.getAllFeatures(), true, false); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration) { gotoBoundingBox(bb, history, scaleToFit, animationDuration, true); } /** * Moves the view to the target Boundingbox. * * @param bb target BoundingBox * @param history true, if the action sould be saved in the history * @param scaleToFit true, to zoom * @param animationDuration duration of the animation * @param queryServices true, if the services should be refreshed after animation */ public void gotoBoundingBox(final BoundingBox bb, final boolean history, final boolean scaleToFit, final int animationDuration, final boolean queryServices) { if (bb != null) { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("gotoBoundingBox:" + bb, new CurrentStackTrace()); // NOI18N } } try { handleLayer.removeAllChildren(); } catch (Exception e) { log.warn("Fehler bei removeAllCHildren", e); // NOI18N } final double x1 = getWtst().getScreenX(bb.getX1()); final double y1 = getWtst().getScreenY(bb.getY1()); final double x2 = getWtst().getScreenX(bb.getX2()); final double y2 = getWtst().getScreenY(bb.getY2()); final double w; final double h; final Rectangle2D pos = new Rectangle2D.Double(); pos.setRect(x1, y2, x2 - x1, y1 - y2); getCamera().animateViewToCenterBounds(pos, (x1 != x2) && (y1 != y2) && scaleToFit, animationDuration); if (getCamera().getViewTransform().getScaleY() < 0) { log.fatal("gotoBoundingBox: Problem :-( mit getViewTransform"); // NOI18N } showHandles(true); final Runnable handle = new Runnable() { @Override public void run() { while (getAnimating()) { try { Thread.currentThread().sleep(10); } catch (Exception e) { log.warn("Unterbrechung bei getAnimating()", e); // NOI18N } } if (history) { if ((x1 == x2) || (y1 == y2) || !scaleToFit) { setNewViewBounds(getCamera().getViewBounds()); } else { setNewViewBounds(pos); } if (queryServices) { queryServices(); } } else { if (queryServices) { queryServicesWithoutHistory(); } } } }; CismetThreadPool.execute(handle); } else { log.warn("Seltsam: die BoundingBox war null", new CurrentStackTrace()); // NOI18N } } /** * Moves the view to the target Boundingbox without saving the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithoutHistory(final BoundingBox bb) { gotoBoundingBox(bb, false, true, animationDuration); } /** * Moves the view to the target Boundingbox and saves the action in the history. * * @param bb target BoundingBox */ public void gotoBoundingBoxWithHistory(final BoundingBox bb) { gotoBoundingBox(bb, true, true, animationDuration); } /** * Returns a BoundingBox of the current view in another scale. * * @param scaleDenominator specific target scale * * @return DOCUMENT ME! */ public BoundingBox getBoundingBoxFromScale(final double scaleDenominator) { return getScaledBoundingBox(scaleDenominator, getCurrentBoundingBox()); } /** * Returns the BoundingBox of the delivered BoundingBox in another scale. * * @param scaleDenominator specific target scale * @param bb source BoundingBox * * @return DOCUMENT ME! */ public BoundingBox getScaledBoundingBox(final double scaleDenominator, BoundingBox bb) { final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; final double realWorldWidthInMeter = screenWidthInMeter * scaleDenominator; final double realWorldHeightInMeter = screenHeightInMeter * scaleDenominator; if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { // transform the given bounding box to a metric coordinate system bb = transformer.transformBoundingBox(bb, CismapBroker.getInstance().getSrs().getCode()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } final double midX = bb.getX1() + ((bb.getX2() - bb.getX1()) / 2); final double midY = bb.getY1() + ((bb.getY2() - bb.getY1()) / 2); BoundingBox scaledBox = new BoundingBox(midX - (realWorldWidthInMeter / 2), midY - (realWorldHeightInMeter / 2), midX + (realWorldWidthInMeter / 2), midY + (realWorldHeightInMeter / 2)); if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { // transform the scaled bounding box to the current coordinate system final CrsTransformer trans = new CrsTransformer(CismapBroker.getInstance().getSrs().getCode()); scaledBox = trans.transformBoundingBox(scaledBox, transformer.getDestinationCrs()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } return scaledBox; } /** * Calculate the current scaledenominator. * * @return DOCUMENT ME! */ public double getScaleDenominator() { BoundingBox boundingBox = getCurrentBoundingBox(); final double screenWidthInInch = getWidth() / screenResolution; final double screenWidthInMeter = screenWidthInInch * 0.0254; final double screenHeightInInch = getHeight() / screenResolution; final double screenHeightInMeter = screenHeightInInch * 0.0254; if (!CismapBroker.getInstance().getSrs().isMetric() && (transformer != null)) { try { boundingBox = transformer.transformBoundingBox( boundingBox, CismapBroker.getInstance().getSrs().getCode()); } catch (Exception e) { log.error("Cannot transform the current bounding box.", e); } } final double realWorldWidthInMeter = boundingBox.getWidth(); final double realWorldHeightInMeter = boundingBox.getHeight(); return realWorldWidthInMeter / screenWidthInMeter; } // public static Image getFeatureImage(Feature f){ // MappingComponent mc=new MappingComponent(); // mc.setSize(100,100); // pc.setInfoNodesVisible(true); // pc.setSize(100,100); // PFeature pf=new PFeature(pnf,new WorldToScreenTransform(0,0),0,0,null); // pc.getLayer().addChild(pf); // pc.getCamera().animateViewToCenterBounds(pf.getBounds(),true,0); // i=new ImageIcon(pc.getCamera().toImage(100,100,getBackground())); // } /** * Called when the drag operation has terminated with a drop on the operable part of the drop site for the <code> * DropTarget</code> registered with this listener. * * <p>This method is responsible for undertaking the transfer of the data associated with the gesture. The <code> * DropTargetDropEvent</code> provides a means to obtain a <code>Transferable</code> object that represents the data * object(s) to be transfered.</p> * * <P>From this method, the <code>DropTargetListener</code> shall accept or reject the drop via the acceptDrop(int * dropAction) or rejectDrop() methods of the <code>DropTargetDropEvent</code> parameter.</P> * * <P>Subsequent to acceptDrop(), but not before, <code>DropTargetDropEvent</code>'s getTransferable() method may be * invoked, and data transfer may be performed via the returned <code>Transferable</code>'s getTransferData() * method.</P> * * <P>At the completion of a drop, an implementation of this method is required to signal the success/failure of the * drop by passing an appropriate <code>boolean</code> to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method.</P> * * <P>Note: The data transfer should be completed before the call to the <code>DropTargetDropEvent</code>'s * dropComplete(boolean success) method. After that, a call to the getTransferData() method of the <code> * Transferable</code> returned by <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to succeed only * if the data transfer is local; that is, only if <code>DropTargetDropEvent.isLocalTransfer()</code> returns <code> * true</code>. Otherwise, the behavior of the call is implementation-dependent.</P> * * @param dtde the <code>DropTargetDropEvent</code> */ @Override public void drop(final DropTargetDropEvent dtde) { if (isDropEnabled(dtde)) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); final Point p = dtde.getLocation(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDropOnMap(mde); } catch (NoninvertibleTransformException ex) { log.error(ex, ex); } } } /** * DOCUMENT ME! * * @param dtde DOCUMENT ME! * * @return DOCUMENT ME! */ private boolean isDropEnabled(final DropTargetDropEvent dtde) { if (ALKIS_PRINT.equals(getInteractionMode())) { for (final DataFlavor flavour : dtde.getTransferable().getTransferDataFlavors()) { // necessary evil, because we have no dependecy to DefaultMetaTreeNode frome here if (String.valueOf(flavour.getRepresentationClass()).endsWith(".DefaultMetaTreeNode")) { return false; } } } return true; } /** * Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site * for the <code>DropTarget</code> registered with this listener. * * @param dte the <code>DropTargetEvent</code> */ @Override public void dragExit(final DropTargetEvent dte) { } /** * Called if the user has modified the current drop gesture. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dropActionChanged(final DropTargetDragEvent dtde) { } /** * Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the dro9p * site for the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragOver(final DropTargetDragEvent dtde) { try { final MapDnDEvent mde = new MapDnDEvent(); mde.setDte(dtde); // TODO: this seems to be buggy! final Point p = dtde.getLocation(); // Point2D p2d; // double scale = 1 / getCamera().getViewScale(); getCamera().getViewTransform().inverseTransform(p, p); mde.setXPos(getWtst().getWorldX(p.getX())); mde.setYPos(getWtst().getWorldY(p.getY())); CismapBroker.getInstance().fireDragOverMap(mde); } catch (NoninvertibleTransformException ex) { log.error(ex, ex); } // MapDnDEvent mde = new MapDnDEvent(); // mde.setDte(dtde); // Point p = dtde.getLocation(); // double scale = 1/getCamera().getViewScale(); // mde.setXPos(getWtst().getWorldX(p.getX() * scale)); // mde.setYPos(getWtst().getWorldY(p.getY() * scale)); // CismapBroker.getInstance().fireDragOverMap(mde); } /** * Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for * the <code>DropTarget</code> registered with this listener. * * @param dtde the <code>DropTargetDragEvent</code> */ @Override public void dragEnter(final DropTargetDragEvent dtde) { } /** * Returns the PfeatureHashmap which assigns a Feature to a PFeature. * * @return DOCUMENT ME! */ public ConcurrentHashMap<Feature, PFeature> getPFeatureHM() { return pFeatureHM; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapExtent() { return fixedMapExtent; } /** * DOCUMENT ME! * * @param fixedMapExtent DOCUMENT ME! */ public void setFixedMapExtent(final boolean fixedMapExtent) { this.fixedMapExtent = fixedMapExtent; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isFixedMapScale() { return fixedMapScale; } /** * DOCUMENT ME! * * @param fixedMapScale DOCUMENT ME! */ public void setFixedMapScale(final boolean fixedMapScale) { this.fixedMapScale = fixedMapScale; } /** * DOCUMENT ME! * * @param one DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public void selectPFeatureManually(final PFeature one) { // throw new UnsupportedOperationException("Not yet implemented"); if (one != null) { featureCollection.select(one.getFeature()); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! * * @deprecated DOCUMENT ME! */ public PFeature getSelectedNode() { // gehe mal davon aus dass das nur aufgerufen wird wenn sowieso nur ein node selected ist // deshalb gebe ich mal nur das erste zur�ck if (featureCollection.getSelectedFeatures().size() > 0) { final Feature selF = (Feature)featureCollection.getSelectedFeatures().toArray()[0]; if (selF == null) { return null; } return pFeatureHM.get(selF); } else { return null; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInfoNodesVisible() { return infoNodesVisible; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getPrintingFrameLayer() { return printingFrameLayer; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PrintingSettingsWidget getPrintingSettingsDialog() { return printingSettingsDialog; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean isInGlueIdenticalPointsMode() { return inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @param inGlueIdenticalPointsMode DOCUMENT ME! */ public void setInGlueIdenticalPointsMode(final boolean inGlueIdenticalPointsMode) { this.inGlueIdenticalPointsMode = inGlueIdenticalPointsMode; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public PLayer getHighlightingLayer() { return highlightingLayer; } /** * DOCUMENT ME! * * @param anno DOCUMENT ME! */ public void setPointerAnnotation(final PNode anno) { ((SimpleMoveListener)getInputListener(MOTION)).setPointerAnnotation(anno); } /** * DOCUMENT ME! * * @param visib DOCUMENT ME! */ public void setPointerAnnotationVisibility(final boolean visib) { if (getInputListener(MOTION) != null) { ((SimpleMoveListener)getInputListener(MOTION)).setAnnotationNodeVisible(visib); } } /** * Returns a boolean whether the annotationnode is visible or not. Returns false if the interactionmode doesn't * equal MOTION. * * @return DOCUMENT ME! */ public boolean isPointerAnnotationVisible() { if (getInputListener(MOTION) != null) { return ((SimpleMoveListener)getInputListener(MOTION)).isAnnotationNodeVisible(); } else { return false; } } /** * Returns a vector with different scales. * * @return DOCUMENT ME! */ public List<Scale> getScales() { return scales; } /** * Returns a list with different crs. * * @return DOCUMENT ME! */ public List<Crs> getCrsList() { return crsList; } /** * DOCUMENT ME! * * @return a transformer with the default crs as destination crs. The default crs is the first crs in the * configuration file that has set the selected attribut on true). This crs must be metric. */ public CrsTransformer getMetricTransformer() { return transformer; } /** * Locks the MappingComponent. */ public void lock() { locked = true; } /** * Unlocks the MappingComponent. */ public void unlock() { if (DEBUG) { if (log.isDebugEnabled()) { log.debug("unlock"); // NOI18N } } locked = false; if (DEBUG) { if (log.isDebugEnabled()) { log.debug("currentBoundingBox:" + currentBoundingBox); // NOI18N } } gotoBoundingBoxWithHistory(currentBoundingBox); } /** * Returns whether the MappingComponent is locked or not. * * @return DOCUMENT ME! */ public boolean isLocked() { return locked; } /** * Returns the MementoInterface for redo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemRedo() { return memRedo; } /** * Returns the MementoInterface for undo-actions. * * @return DOCUMENT ME! */ public MementoInterface getMemUndo() { return memUndo; } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public HashMap<String, PBasicInputEventHandler> getInputEventListener() { return inputEventListener; } /** * DOCUMENT ME! * * @param inputEventListener DOCUMENT ME! */ public void setInputEventListener(final HashMap<String, PBasicInputEventHandler> inputEventListener) { this.inputEventListener.clear(); this.inputEventListener.putAll(inputEventListener); } @Override public synchronized void crsChanged(final CrsChangedEvent event) { if ((event.getFormerCrs() != null) && (fixedBoundingBox == null) && !resetCrs) { if (locked) { return; } try { // the wtst object should not be null, so teh getWtst method will be invoked getWtst(); final BoundingBox bbox = getCurrentBoundingBox(); // getCurrentBoundingBox(); final CrsTransformer crsTransformer = new CrsTransformer(event.getCurrentCrs().getCode()); final BoundingBox newBbox = crsTransformer.transformBoundingBox(bbox, event.getFormerCrs().getCode()); if (getMappingModel() instanceof ActiveLayerModel) { final ActiveLayerModel alm = (ActiveLayerModel)getMappingModel(); alm.setSrs(event.getCurrentCrs()); } wtst = null; getWtst(); gotoBoundingBoxWithoutHistory(newBbox); // transform all features for (final Feature f : featureCollection.getAllFeatures()) { final Geometry geom = crsTransformer.transformGeometry(f.getGeometry(), event.getFormerCrs().getCode()); f.setGeometry(geom); final PFeature feature = pFeatureHM.get(f); feature.setFeature(f); Coordinate[] coordArray = feature.getCoordArr(); coordArray = crsTransformer.transformGeometry(coordArray, event.getFormerCrs().getCode()); feature.setCoordArr(coordArray); } final ArrayList<Feature> list = new ArrayList<Feature>(featureCollection.getAllFeatures()); // list.add(f); removeFeatures(list); addFeaturesToMap(list.toArray(new Feature[list.size()])); } catch (Exception e) { JOptionPane.showMessageDialog( this, org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.message"), org.openide.util.NbBundle.getMessage( MappingComponent.class, "MappingComponent.crsChanged(CrsChangedEvent).JOptionPane.title"), JOptionPane.ERROR_MESSAGE); log.error("Cannot transform the current bounding box to the CRS " + event.getCurrentCrs(), e); resetCrs = true; CismapBroker.getInstance().setSrs(event.getFormerCrs()); } } else { resetCrs = false; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public JInternalFrame getInternalWidget(final String name) { if (this.internalWidgets.containsKey(name)) { return this.internalWidgets.get(name); } else { log.warn("unknown internal widget '" + name + "'"); // NOI18N return null; } } /** * DOCUMENT ME! * * @param name DOCUMENT ME! * * @return DOCUMENT ME! */ public int getInternalWidgetPosition(final String name) { if (this.internalWidgetPositions.containsKey(name)) { return this.internalWidgetPositions.get(name); } else { log.warn("unknown position for '" + name + "'"); // NOI18N return -1; } } //~ Inner Classes ---------------------------------------------------------- /** * /////////////////////////////////////////////// CLASS MappingComponentRasterServiceListener // * ///////////////////////////////////////////////. * * @version $Revision$, $Date$ */ private class MappingComponentRasterServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private Logger logger = Logger.getLogger(this.getClass()); private int position = -1; private XPImage pi = null; private ServiceLayer rasterService = null; //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentRasterServiceListener object. * * @param position DOCUMENT ME! * @param pn DOCUMENT ME! * @param rasterService DOCUMENT ME! */ public MappingComponentRasterServiceListener(final int position, final PNode pn, final ServiceLayer rasterService) { this.position = position; if (pn instanceof XPImage) { this.pi = (XPImage)pn; } this.rasterService = rasterService; } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { fireActivityChanged(); if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } } @Override public void retrievalProgress(final RetrievalEvent e) { } @Override public void retrievalError(final RetrievalEvent e) { this.logger.error(rasterService + ": Fehler beim Laden des Bildes! " + e.getErrorType() + " Errors: " + e.getErrors() + " Cause: " + e.getRetrievedObject()); // NOI18N fireActivityChanged(); if (DEBUG) { if (log.isDebugEnabled()) { log.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } } @Override public void retrievalComplete(final RetrievalEvent e) { final Point2D localOrigin = getCamera().getViewBounds().getOrigin(); final double localScale = getCamera().getViewScale(); final PBounds localBounds = getCamera().getViewBounds(); final Object o = e.getRetrievedObject(); // log.fatal(localBounds+ " "+localScale); if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(rasterService + ": TaskCounter:" + taskCounter); // NOI18N } } final Runnable paintImageOnMap = new Runnable() { @Override public void run() { fireActivityChanged(); if ((o instanceof Image) && (e.isHasErrors() == false)) { // TODO Hier ist noch ein Fehler die Sichtbarkeit muss vom Layer erfragt werden if (isBackgroundEnabled()) { // Image i=Static2DTools.toCompatibleImage((Image)o); final Image i = (Image)o; if (rasterService.getName().startsWith("prefetching")) { // NOI18N final double x = localOrigin.getX() - localBounds.getWidth(); final double y = localOrigin.getY() - localBounds.getHeight(); pi.setImage(i, 0); pi.setScale(3 / localScale); pi.setOffset(x, y); } else { pi.setImage(i, 1000); pi.setScale(1 / localScale); pi.setOffset(localOrigin); MappingComponent.this.repaint(); } } } } }; if (EventQueue.isDispatchThread()) { paintImageOnMap.run(); } else { EventQueue.invokeLater(paintImageOnMap); } } @Override public void retrievalAborted(final RetrievalEvent e) { this.logger.warn(rasterService + ": retrievalAborted: " + e.getRequestIdentifier()); // NOI18N } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public int getPosition() { return position; } /** * DOCUMENT ME! * * @param position DOCUMENT ME! */ public void setPosition(final int position) { this.position = position; } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ private class DocumentProgressListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- private Logger logger = Logger.getLogger(this.getClass()); private long requestId = -1; /** Displays the loading progress of Documents, e.g. SHP Files */ private final DocumentProgressWidget documentProgressWidget = new DocumentProgressWidget(); //~ Constructors ------------------------------------------------------- /** * Creates a new DocumentProgressListener object. */ public DocumentProgressListener() { documentProgressWidget.setVisible(false); if (MappingComponent.this.getInternalWidget(MappingComponent.PROGRESSWIDGET) == null) { MappingComponent.this.addInternalWidget( MappingComponent.PROGRESSWIDGET, MappingComponent.POSITION_SOUTHWEST, documentProgressWidget); } } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != -1) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalStarted: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = e.getRequestIdentifier(); this.documentProgressWidget.setServiceName(e.getRetrievalService().toString()); this.documentProgressWidget.setProgress(-1); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, true, 100); // MappingComponent.this.showInternalWidget(ZOOM, DEBUG, animationDuration); // MappingComponent.this.isInternalWidgetVisible(ZOOM); } @Override public void retrievalProgress(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalProgress: another initialisation thread is still running: " + requestId); // NOI18N } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: initialisation progress: " + e.getPercentageDone()); // NOI18N } } this.documentProgressWidget.setProgress(e.getPercentageDone()); } @Override public void retrievalComplete(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalComplete: another initialisation thread is still running: " + requestId); // NOI18N } e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(100); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 200); } @Override public void retrievalAborted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalAborted: another initialisation thread is still running: " + requestId); // NOI18N } // e.getRetrievalService().removeRetrievalListener(this); this.requestId = -1; this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } @Override public void retrievalError(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError aborted, no initialisation event"); // NOI18N return; } if (this.requestId != e.getRequestIdentifier()) { logger.warn(e.getRetrievalService() + "[" + e.getRequestIdentifier() + "]: retrievalError: another initialisation thread is still running: " + requestId); // NOI18N } this.requestId = -1; e.getRetrievalService().removeRetrievalListener(this); this.documentProgressWidget.setProgress(0); MappingComponent.this.showInternalWidget(MappingComponent.PROGRESSWIDGET, false, 25); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public long getRequestId() { return this.requestId; } } /** * //////////////////////////////////////////////// CLASS MappingComponentFeatureServiceListener // * ////////////////////////////////////////////////. * * @version $Revision$, $Date$ */ private class MappingComponentFeatureServiceListener implements RetrievalListener { //~ Instance fields ---------------------------------------------------- ServiceLayer featureService; PLayer parent; long requestIdentifier; Thread completionThread = null; private Logger logger = Logger.getLogger(this.getClass()); private Vector deletionCandidates = new Vector(); private Vector twins = new Vector(); //~ Constructors ------------------------------------------------------- /** * Creates a new MappingComponentFeatureServiceListener. * * @param featureService the featureretrievalservice * @param parent the featurelayer (PNode) connected with the servicelayer */ public MappingComponentFeatureServiceListener(final ServiceLayer featureService, final PLayer parent) { this.featureService = featureService; this.parent = parent; } //~ Methods ------------------------------------------------------------ @Override public void retrievalStarted(final RetrievalEvent e) { if (!e.isInitialisationEvent()) { requestIdentifier = e.getRequestIdentifier(); } if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " started"); // NOI18N } } fireActivityChanged(); } @Override public void retrievalProgress(final RetrievalEvent e) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " Progress: " + e.getPercentageDone() + " (" + ((RetrievalServiceLayer)featureService).getProgress() + ")"); // NOI18N } } fireActivityChanged(); // TODO Hier besteht auch die Möglichkeit jedes einzelne Polygon hinzuzufügen. ausprobieren, ob das // flüssiger ist } @Override public void retrievalError(final RetrievalEvent e) { this.logger.error(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " error"); // NOI18N fireActivityChanged(); } @Override public void retrievalComplete(final RetrievalEvent e) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: " + (e.isInitialisationEvent() ? "initialisation" : "retrieval") + " complete"); // NOI18N } } if (e.isInitialisationEvent()) { this.logger.info(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: initialisation complete"); // NOI18N fireActivityChanged(); return; } if ((completionThread != null) && completionThread.isAlive() && !completionThread.isInterrupted()) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: retrievalComplete: old completion thread still running, trying to interrupt thread"); // NOI18N completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: retrievalComplete: another retrieval process is still running, aborting retrievalComplete"); // NOI18N } ((RetrievalServiceLayer)featureService).setProgress(-1); fireActivityChanged(); return; } final Vector newFeatures = new Vector(); EventQueue.invokeLater(new Runnable() { @Override public void run() { ((RetrievalServiceLayer)featureService).setProgress(-1); parent.setVisible(isBackgroundEnabled() && featureService.isEnabled() && parent.getVisible()); // parent.removeAllChildren(); } }); // clear all old data to delete twins deletionCandidates.removeAllElements(); twins.removeAllElements(); // if it's a refresh, add all old features which should be deleted in the // newly acquired featurecollection if (!e.isRefreshExisting()) { deletionCandidates.addAll(parent.getChildrenReference()); } if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + this.requestIdentifier + ")]: deletionCandidates (" + deletionCandidates.size() + ")"); // + deletionCandidates);//NOI18N } } // only start parsing the features if there are no errors and a correct collection if ((e.isHasErrors() == false) && (e.getRetrievedObject() instanceof Collection)) { completionThread = new Thread() { @Override public void run() { // this is the collection with the retrieved features // Collection c = ((Collection) e.getRetrievedObject()); final List features = new ArrayList((Collection)e.getRetrievedObject()); final int size = features.size(); int counter = 0; final Iterator it = features.iterator(); if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Anzahl Features: " + size); // NOI18N } } while ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted() && it.hasNext()) { counter++; final Object o = it.next(); if (o instanceof Feature) { final PFeature p = new PFeature(((Feature)o), wtst, clip_offset_x, clip_offset_y, MappingComponent.this); PFeature twin = null; for (final Object tester : deletionCandidates) { // if tester and PFeature are FeatureWithId-objects if ((((PFeature)tester).getFeature() instanceof FeatureWithId) && (p.getFeature() instanceof FeatureWithId)) { final int id1 = ((FeatureWithId)((PFeature)tester).getFeature()).getId(); final int id2 = ((FeatureWithId)(p.getFeature())).getId(); if ((id1 != -1) && (id2 != -1)) { // check if they've got the same id if (id1 == id2) { twin = ((PFeature)tester); break; } } else { // else test the geometry for equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } else { // no FeatureWithId, test geometries for // equality if (((PFeature)tester).getFeature().getGeometry().equals( p.getFeature().getGeometry())) { twin = ((PFeature)tester); break; } } } // if a twin is found remove him from the deletion candidates // and add him to the twins if (twin != null) { deletionCandidates.remove(twin); twins.add(twin); } else { // else add the PFeature to the new features newFeatures.add(p); } // calculate the advance of the progressbar // fire event only wheen needed final int currentProgress = (int)((double)counter / (double)size * 100d); /*if(currentProgress % 10 == 0 && currentProgress > lastUpdateProgress) * { lastUpdateProgress = currentProgress; if(DEBUG)log.debug("fire progress changed * "+currentProgress); fireActivityChanged();}*/ if ((currentProgress >= 10) && ((currentProgress % 10) == 0)) { ((RetrievalServiceLayer)featureService).setProgress(currentProgress); fireActivityChanged(); } } } if ((requestIdentifier == e.getRequestIdentifier()) && !isInterrupted()) { // after all features are computed do stuff on the EDT EventQueue.invokeLater(new Runnable() { @Override public void run() { try { if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: MappingComponentFeaturelistener.retrievalComplete()"); // NOI18N } } // if it's a refresh, delete all previous features if (e.isRefreshExisting()) { parent.removeAllChildren(); } final Vector deleteFeatures = new Vector(); for (final Object o : newFeatures) { parent.addChild((PNode)o); } // for (Object o : twins) { // TODO only nesseccary if style has changed // ((PFeature) o).refreshDesign(); // if(DEBUG)log.debug("twin refresh"); // } // set the prograssbar to full if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: set progress to 100"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(100); fireActivityChanged(); // repaint the featurelayer parent.repaint(); // remove stickyNode from all deletionCandidates and add // each to the new deletefeature-collection for (final Object o : deletionCandidates) { if (o instanceof PFeature) { final PNode p = ((PFeature)o).getPrimaryAnnotationNode(); if (p != null) { removeStickyNode(p); } deleteFeatures.add(o); } } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount before:" + parent.getChildrenCount()); // NOI18N } } if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: deleteFeatures=" + deleteFeatures.size()); // + " :" + // deleteFeatures);//NOI18N } } parent.removeChildren(deleteFeatures); if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: parentCount after:" + parent.getChildrenCount()); // NOI18N } } log.info( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: " + parent.getChildrenCount() + " features retrieved or updated"); // NOI18N rescaleStickyNodes(); } catch (Exception exception) { logger.warn( featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: Fehler beim Aufr\u00E4umen", exception); // NOI18N } } }); } else { if (DEBUG) { if (logger.isDebugEnabled()) { logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } }; completionThread.setPriority(Thread.NORM_PRIORITY); if (requestIdentifier == e.getRequestIdentifier()) { completionThread.start(); } else { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: completion thread Interrupted or synchronisation lost"); // NOI18N } } } } fireActivityChanged(); } @Override public void retrievalAborted(final RetrievalEvent e) { this.logger.warn(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: aborted, TaskCounter:" + taskCounter); // NOI18N if (completionThread != null) { completionThread.interrupt(); } if (e.getRequestIdentifier() < requestIdentifier) { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: another retrieval process is still running, setting the retrieval progress to indeterminate"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(-1); } else { if (DEBUG) { if (this.logger.isDebugEnabled()) { this.logger.debug(featureService + "[" + e.getRequestIdentifier() + " (" + requestIdentifier + ")]: this is the last retrieval process, settign the retrieval progress to 0 (aborted)"); // NOI18N } } ((RetrievalServiceLayer)featureService).setProgress(0); } fireActivityChanged(); } } }
diff --git a/src/org/eclipse/jface/viewers/TreeViewer.java b/src/org/eclipse/jface/viewers/TreeViewer.java index f185db90..8811d706 100644 --- a/src/org/eclipse/jface/viewers/TreeViewer.java +++ b/src/org/eclipse/jface/viewers/TreeViewer.java @@ -1,1017 +1,1023 @@ /******************************************************************************* * Copyright (c) 2004, 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 * Tom Schindl <[email protected]> - concept of ViewerRow, * refactoring (bug 153993), bug 167323 *******************************************************************************/ package org.eclipse.jface.viewers; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.util.Policy; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.TreeEvent; import org.eclipse.swt.events.TreeListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.swt.widgets.Widget; /** * A concrete viewer based on an SWT <code>Tree</code> control. * <p> * This class is not intended to be subclassed outside the viewer framework. It * is designed to be instantiated with a pre-existing SWT tree control and * configured with a domain-specific content provider, label provider, element * filter (optional), and element sorter (optional). * </p> * <p> * Content providers for tree viewers must implement either the * {@link ITreeContentProvider} interface, (as of 3.2) the * {@link ILazyTreeContentProvider} interface, or (as of 3.3) the * {@link ILazyTreePathContentProvider}. If the content provider is an * <code>ILazyTreeContentProvider</code> or an * <code>ILazyTreePathContentProvider</code>, the underlying Tree must be * created using the {@link SWT#VIRTUAL} style bit, and the tree viewer will not * support sorting or filtering. * </p> */ public class TreeViewer extends AbstractTreeViewer { private static final String VIRTUAL_DISPOSE_KEY = Policy.JFACE + ".DISPOSE_LISTENER"; //$NON-NLS-1$ /** * This viewer's control. */ private Tree tree; /** * Flag for whether the tree has been disposed of. */ private boolean treeIsDisposed = false; private boolean contentProviderIsLazy; private boolean contentProviderIsTreeBased; /** * The row object reused */ private TreeViewerRow cachedRow; /** * true if we are inside a preservingSelection() call */ private boolean preservingSelection; /** * Creates a tree viewer on a newly-created tree control under the given * parent. The tree control is created using the SWT style bits * <code>MULTI, H_SCROLL, V_SCROLL,</code> and <code>BORDER</code>. The * viewer has no input, no content provider, a default label provider, no * sorter, and no filters. * * @param parent * the parent control */ public TreeViewer(Composite parent) { this(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); } /** * Creates a tree viewer on a newly-created tree control under the given * parent. The tree control is created using the given SWT style bits. The * viewer has no input, no content provider, a default label provider, no * sorter, and no filters. * * @param parent * the parent control * @param style * the SWT style bits used to create the tree. */ public TreeViewer(Composite parent, int style) { this(new Tree(parent, style)); } /** * Creates a tree viewer on the given tree control. The viewer has no input, * no content provider, a default label provider, no sorter, and no filters. * * @param tree * the tree control */ public TreeViewer(Tree tree) { super(); this.tree = tree; hookControl(tree); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected void addTreeListener(Control c, TreeListener listener) { ((Tree) c).addTreeListener(listener); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.ColumnViewer#getColumnViewerOwner(int) */ protected Widget getColumnViewerOwner(int columnIndex) { if (columnIndex < 0 || ( columnIndex > 0 && columnIndex >= getTree().getColumnCount() ) ) { return null; } if (getTree().getColumnCount() == 0)// Hang it off the table if it return getTree(); return getTree().getColumn(columnIndex); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected Item[] getChildren(Widget o) { if (o instanceof TreeItem) { return ((TreeItem) o).getItems(); } if (o instanceof Tree) { return ((Tree) o).getItems(); } return null; } /* * (non-Javadoc) Method declared in Viewer. */ public Control getControl() { return tree; } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected boolean getExpanded(Item item) { return ((TreeItem) item).getExpanded(); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.ColumnViewer#getItemAt(org.eclipse.swt.graphics.Point) */ protected Item getItemAt(Point p) { return getTree().getItem(p); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected int getItemCount(Control widget) { return ((Tree) widget).getItemCount(); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected int getItemCount(Item item) { return ((TreeItem) item).getItemCount(); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected Item[] getItems(Item item) { return ((TreeItem) item).getItems(); } /** * The tree viewer implementation of this <code>Viewer</code> framework * method ensures that the given label provider is an instance of either * <code>ITableLabelProvider</code> or <code>ILabelProvider</code>. If * it is an <code>ITableLabelProvider</code>, then it provides a separate * label text and image for each column. If it is an * <code>ILabelProvider</code>, then it provides only the label text and * image for the first column, and any remaining columns are blank. */ public IBaseLabelProvider getLabelProvider() { return super.getLabelProvider(); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected Item getParentItem(Item item) { return ((TreeItem) item).getParentItem(); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected Item[] getSelection(Control widget) { return ((Tree) widget).getSelection(); } /** * Returns this tree viewer's tree control. * * @return the tree control */ public Tree getTree() { return tree; } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.AbstractTreeViewer#hookControl(org.eclipse.swt.widgets.Control) */ protected void hookControl(Control control) { super.hookControl(control); Tree treeControl = (Tree) control; if ((treeControl.getStyle() & SWT.VIRTUAL) != 0) { treeControl.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { treeIsDisposed = true; unmapAllElements(); } }); treeControl.addListener(SWT.SetData, new Listener() { public void handleEvent(Event event) { if (contentProviderIsLazy) { TreeItem item = (TreeItem) event.item; TreeItem parentItem = item.getParentItem(); int index = event.index; virtualLazyUpdateWidget( parentItem == null ? (Widget) getTree() : parentItem, index); } } }); } } protected ColumnViewerEditor createViewerEditor() { return new TreeViewerEditor(this,null,new ColumnViewerEditorActivationStrategy(this),ColumnViewerEditor.DEFAULT); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected Item newItem(Widget parent, int flags, int ix) { TreeItem item; if (parent instanceof TreeItem) { item = (TreeItem) createNewRowPart(getViewerRowFromItem(parent), flags, ix).getItem(); } else { item = (TreeItem) createNewRowPart(null, flags, ix).getItem(); } return item; } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected void removeAll(Control widget) { ((Tree) widget).removeAll(); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected void setExpanded(Item node, boolean expand) { ((TreeItem) node).setExpanded(expand); if (contentProviderIsLazy) { // force repaints to happen getControl().update(); } } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected void setSelection(List items) { Item[] current = getSelection(getTree()); // Don't bother resetting the same selection if (isSameSelection(items, current)) { return; } TreeItem[] newItems = new TreeItem[items.size()]; items.toArray(newItems); getTree().setSelection(newItems); } /* * (non-Javadoc) Method declared in AbstractTreeViewer. */ protected void showItem(Item item) { getTree().showItem((TreeItem) item); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.AbstractTreeViewer#getChild(org.eclipse.swt.widgets.Widget, * int) */ protected Item getChild(Widget widget, int index) { if (widget instanceof TreeItem) { return ((TreeItem) widget).getItem(index); } if (widget instanceof Tree) { return ((Tree) widget).getItem(index); } return null; } protected void assertContentProviderType(IContentProvider provider) { if (provider instanceof ILazyTreeContentProvider || provider instanceof ILazyTreePathContentProvider) { return; } super.assertContentProviderType(provider); } protected Object[] getRawChildren(Object parent) { if (contentProviderIsLazy) { return new Object[0]; } return super.getRawChildren(parent); } void preservingSelection(Runnable updateCode, boolean reveal) { if (preservingSelection){ // avoid preserving the selection if called reentrantly updateCode.run(); return; } preservingSelection = true; try { super.preservingSelection(updateCode, reveal); } finally { preservingSelection = false; } } /** * For a TreeViewer with a tree with the VIRTUAL style bit set, set the * number of children of the given element or tree path. To set the number * of children of the invisible root of the tree, you can pass the input * object or an empty tree path. * * @param elementOrTreePath * the element, or tree path * @param count * * @since 3.2 */ public void setChildCount(final Object elementOrTreePath, final int count) { preservingSelection(new Runnable() { public void run() { if (internalIsInputOrEmptyPath(elementOrTreePath)) { getTree().setItemCount(count); return; } Widget[] items = internalFindItems(elementOrTreePath); for (int i = 0; i < items.length; i++) { TreeItem treeItem = (TreeItem) items[i]; treeItem.setItemCount(count); } } }); } /** * For a TreeViewer with a tree with the VIRTUAL style bit set, replace the * given parent's child at index with the given element. If the given parent * is this viewer's input or an empty tree path, this will replace the root * element at the given index. * <p> * This method should be called by implementers of ILazyTreeContentProvider * to populate this viewer. * </p> * * @param parentElementOrTreePath * the parent of the element that should be updated, or the tree * path to that parent * @param index * the index in the parent's children * @param element * the new element * * @see #setChildCount(Object, int) * @see ILazyTreeContentProvider * @see ILazyTreePathContentProvider * * @since 3.2 */ public void replace(final Object parentElementOrTreePath, final int index, final Object element) { preservingSelection(new Runnable() { public void run() { Widget[] itemsToDisassociate; if (parentElementOrTreePath instanceof TreePath) { TreePath elementPath = ((TreePath)parentElementOrTreePath).createChildPath(element); itemsToDisassociate = internalFindItems(elementPath); } else { itemsToDisassociate = internalFindItems(element); } if (internalIsInputOrEmptyPath(parentElementOrTreePath)) { if (index < tree.getItemCount()) { TreeItem item = tree.getItem(index); // disassociate any differen item that represents the // same element under the same parent (the tree) for (int i = 0; i < itemsToDisassociate.length; i++) { if (itemsToDisassociate[i] instanceof TreeItem) { TreeItem itemToDisassociate = (TreeItem)itemsToDisassociate[i]; if (itemToDisassociate != item && itemToDisassociate.getParentItem() == null) { int index = getTree().indexOf(itemToDisassociate); disassociate(itemToDisassociate); getTree().clear(index, true); } } } + Object oldData = item.getData(); updateItem(item, element); - item.clearAll(true); + if (!TreeViewer.this.equals(oldData, element)) { + item.clearAll(true); + } } } else { Widget[] parentItems = internalFindItems(parentElementOrTreePath); for (int i = 0; i < parentItems.length; i++) { TreeItem parentItem = (TreeItem) parentItems[i]; if (index < parentItem.getItemCount()) { TreeItem item = parentItem.getItem(index); // disassociate any differen item that represents the // same element under the same parent (the tree) for (int j = 0; j < itemsToDisassociate.length; j++) { if (itemsToDisassociate[j] instanceof TreeItem) { TreeItem itemToDisassociate = (TreeItem)itemsToDisassociate[j]; if (itemToDisassociate != item && itemToDisassociate.getParentItem() == parentItem) { int index = parentItem.indexOf(itemToDisassociate); disassociate(itemToDisassociate); parentItem.clear(index, true); } } } + Object oldData = item.getData(); updateItem(item, element); - item.clearAll(true); + if (!TreeViewer.this.equals(oldData, element)) { + item.clearAll(true); + } } } } } }); } public boolean isExpandable(Object element) { if (contentProviderIsLazy) { TreeItem treeItem = (TreeItem) internalExpand(element, false); if (treeItem == null) { return false; } virtualMaterializeItem(treeItem); return treeItem.getItemCount() > 0; } return super.isExpandable(element); } protected Object getParentElement(Object element) { if (contentProviderIsLazy && !contentProviderIsTreeBased && !(element instanceof TreePath)) { ILazyTreeContentProvider lazyTreeContentProvider = (ILazyTreeContentProvider) getContentProvider(); return lazyTreeContentProvider.getParent(element); } if (contentProviderIsLazy && contentProviderIsTreeBased && !(element instanceof TreePath)) { ILazyTreePathContentProvider lazyTreePathContentProvider = (ILazyTreePathContentProvider) getContentProvider(); TreePath[] parents = lazyTreePathContentProvider .getParents(element); if (parents != null && parents.length > 0) { return parents[0]; } } return super.getParentElement(element); } protected void createChildren(Widget widget) { if (contentProviderIsLazy) { Object element = widget.getData(); if (element == null && widget instanceof TreeItem) { // parent has not been materialized virtualMaterializeItem((TreeItem) widget); // try getting the element now that updateElement was called element = widget.getData(); } if (element == null) { // give up because the parent is still not materialized return; } Item[] children = getChildren(widget); if (children.length == 1 && children[0].getData() == null) { // found a dummy node virtualLazyUpdateChildCount(widget, children.length); children = getChildren(widget); } // touch all children to make sure they are materialized for (int i = 0; i < children.length; i++) { if (children[i].getData() == null) { virtualLazyUpdateWidget(widget, i); } } return; } super.createChildren(widget); } protected void internalAdd(Widget widget, Object parentElement, Object[] childElements) { if (contentProviderIsLazy) { if (widget instanceof TreeItem) { TreeItem ti = (TreeItem) widget; int count = ti.getItemCount() + childElements.length; ti.setItemCount(count); ti.clearAll(false); } else { Tree t = (Tree) widget; t.setItemCount(t.getItemCount() + childElements.length); t.clearAll(false); } return; } super.internalAdd(widget, parentElement, childElements); } private void virtualMaterializeItem(TreeItem treeItem) { if (treeItem.getData() != null) { // already materialized return; } if (!contentProviderIsLazy) { return; } int index; Widget parent = treeItem.getParentItem(); if (parent == null) { parent = treeItem.getParent(); } Object parentElement = parent.getData(); if (parentElement != null) { if (parent instanceof Tree) { index = ((Tree) parent).indexOf(treeItem); } else { index = ((TreeItem) parent).indexOf(treeItem); } virtualLazyUpdateWidget(parent, index); } } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.AbstractTreeViewer#internalRefreshStruct(org.eclipse.swt.widgets.Widget, * java.lang.Object, boolean) */ protected void internalRefreshStruct(Widget widget, Object element, boolean updateLabels) { if (contentProviderIsLazy) { // clear all starting with the given widget if (widget instanceof Tree) { ((Tree) widget).clearAll(true); } else if (widget instanceof TreeItem) { ((TreeItem) widget).clearAll(true); } int index = 0; Widget parent = null; if (widget instanceof TreeItem) { TreeItem treeItem = (TreeItem) widget; parent = treeItem.getParentItem(); if (parent == null) { parent = treeItem.getParent(); } if (parent instanceof Tree) { index = ((Tree) parent).indexOf(treeItem); } else { index = ((TreeItem) parent).indexOf(treeItem); } } virtualRefreshExpandedItems(parent, widget, element, index); return; } super.internalRefreshStruct(widget, element, updateLabels); } /** * Traverses the visible (expanded) part of the tree and updates child * counts. * * @param parent the parent of the widget, or <code>null</code> if the widget is the tree * @param widget * @param element * @param index the index of the widget in the children array of its parent, or 0 if the widget is the tree */ private void virtualRefreshExpandedItems(Widget parent, Widget widget, Object element, int index) { if (widget instanceof Tree) { if (element == null) { ((Tree) widget).setItemCount(0); return; } virtualLazyUpdateChildCount(widget, getChildren(widget).length); } else if (((TreeItem) widget).getExpanded()) { // prevent SetData callback ((TreeItem)widget).setText(" "); //$NON-NLS-1$ virtualLazyUpdateWidget(parent, index); } else { return; } Item[] items = getChildren(widget); for (int i = 0; i < items.length; i++) { Item item = items[i]; Object data = item.getData(); virtualRefreshExpandedItems(widget, item, data, i); } } /* * To unmap elements correctly, we need to register a dispose listener with * the item if the tree is virtual. */ protected void mapElement(Object element, final Widget item) { super.mapElement(element, item); // make sure to unmap elements if the tree is virtual if ((getTree().getStyle() & SWT.VIRTUAL) != 0) { // only add a dispose listener if item hasn't already on assigned // because it is reused if (item.getData(VIRTUAL_DISPOSE_KEY) == null) { item.setData(VIRTUAL_DISPOSE_KEY, Boolean.TRUE); item.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { if (!treeIsDisposed) { Object data = item.getData(); if (usingElementMap() && data != null) { unmapElement(data, item); } } } }); } } } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.ColumnViewer#getRowPartFromItem(org.eclipse.swt.widgets.Widget) */ protected ViewerRow getViewerRowFromItem(Widget item) { if( cachedRow == null ) { cachedRow = new TreeViewerRow((TreeItem) item); } else { cachedRow.setItem((TreeItem) item); } return cachedRow; } /** * Create a new ViewerRow at rowIndex * * @param parent * @param style * @param rowIndex * @return ViewerRow */ private ViewerRow createNewRowPart(ViewerRow parent, int style, int rowIndex) { if (parent == null) { if (rowIndex >= 0) { return getViewerRowFromItem(new TreeItem(tree, style, rowIndex)); } return getViewerRowFromItem(new TreeItem(tree, style)); } if (rowIndex >= 0) { return getViewerRowFromItem(new TreeItem((TreeItem) parent.getItem(), SWT.NONE, rowIndex)); } return getViewerRowFromItem(new TreeItem((TreeItem) parent.getItem(), SWT.NONE)); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.AbstractTreeViewer#internalInitializeTree(org.eclipse.swt.widgets.Control) */ protected void internalInitializeTree(Control widget) { if (contentProviderIsLazy) { if (widget instanceof Tree && widget.getData() != null) { virtualLazyUpdateChildCount(widget, 0); return; } } super.internalInitializeTree(tree); } /* * (non-Javadoc) * * @see org.eclipse.jface.viewers.AbstractTreeViewer#updatePlus(org.eclipse.swt.widgets.Item, * java.lang.Object) */ protected void updatePlus(Item item, Object element) { if (contentProviderIsLazy) { Object data = item.getData(); int itemCount = 0; if (data != null) { // item is already materialized itemCount = ((TreeItem) item).getItemCount(); } virtualLazyUpdateHasChildren(item, itemCount); } else { super.updatePlus(item, element); } } /** * Removes the element at the specified index of the parent. The selection is updated if required. * * @param parentOrTreePath the parent element, the input element, or a tree path to the parent element * @param index child index * @since 3.3 */ public void remove(final Object parentOrTreePath, final int index) { final List oldSelection = new LinkedList(Arrays .asList(((TreeSelection) getSelection()).getPaths())); preservingSelection(new Runnable() { public void run() { TreePath removedPath = null; if (internalIsInputOrEmptyPath(parentOrTreePath)) { Tree tree = (Tree) getControl(); if (index < tree.getItemCount()) { TreeItem item = tree.getItem(index); if (item.getData() != null) { removedPath = getTreePathFromItem(item); disassociate(item); } item.dispose(); } } else { Widget[] parentItems = internalFindItems(parentOrTreePath); for (int i = 0; i < parentItems.length; i++) { TreeItem parentItem = (TreeItem) parentItems[i]; if (index < parentItem.getItemCount()) { TreeItem item = parentItem.getItem(index); if (item.getData() != null) { removedPath = getTreePathFromItem(item); disassociate(item); } item.dispose(); } } } if (removedPath != null) { boolean removed = false; for (Iterator it = oldSelection.iterator(); it .hasNext();) { TreePath path = (TreePath) it.next(); if (path.startsWith(removedPath, getComparer())) { it.remove(); removed = true; } } if (removed) { setSelection(new TreeSelection( (TreePath[]) oldSelection .toArray(new TreePath[oldSelection .size()]), getComparer()), false); } } } }); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.AbstractTreeViewer#handleTreeExpand(org.eclipse.swt.events.TreeEvent) */ protected void handleTreeExpand(TreeEvent event) { if (contentProviderIsLazy) { if (event.item.getData() != null) { Item[] children = getChildren(event.item); if (children.length == 1 && children[0].getData()==null) { // we have a dummy child node, ask for an updated child // count virtualLazyUpdateChildCount(event.item, children.length); } fireTreeExpanded(new TreeExpansionEvent(this, event.item .getData())); } return; } super.handleTreeExpand(event); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.AbstractTreeViewer#setContentProvider(org.eclipse.jface.viewers.IContentProvider) */ public void setContentProvider(IContentProvider provider) { contentProviderIsLazy = (provider instanceof ILazyTreeContentProvider) || (provider instanceof ILazyTreePathContentProvider); contentProviderIsTreeBased = provider instanceof ILazyTreePathContentProvider; super.setContentProvider(provider); } /** * For a TreeViewer with a tree with the VIRTUAL style bit set, inform the * viewer about whether the given element or tree path has children. Avoid * calling this method if the number of children has already been set. * * @param elementOrTreePath * the element, or tree path * @param hasChildren * * @since 3.3 */ public void setHasChildren(final Object elementOrTreePath, final boolean hasChildren) { preservingSelection(new Runnable() { public void run() { if (internalIsInputOrEmptyPath(elementOrTreePath)) { if (hasChildren) { virtualLazyUpdateChildCount(getTree(), getChildren(getTree()).length); } else { setChildCount(elementOrTreePath, 0); } return; } Widget[] items = internalFindItems(elementOrTreePath); for (int i = 0; i < items.length; i++) { TreeItem item = (TreeItem) items[i]; if (!hasChildren) { item.setItemCount(0); } else { if (!item.getExpanded()) { item.setItemCount(1); TreeItem child = item.getItem(0); if (child.getData() != null) { disassociate(child); } item.clear(0, true); } else { virtualLazyUpdateChildCount(item, item.getItemCount()); } } } } }); } /** * Update the widget at index. * @param widget * @param index */ private void virtualLazyUpdateWidget(Widget widget, int index) { if (contentProviderIsTreeBased) { TreePath treePath; if (widget instanceof Item) { if (widget.getData() == null) { // we need to materialize the parent first // see bug 167668 // however, that would be too risky // see bug 182782 and bug 182598 // so we just ignore this call altogether // and don't do this: virtualMaterializeItem((TreeItem) widget); return; } treePath = getTreePathFromItem((Item) widget); } else { treePath = TreePath.EMPTY; } ((ILazyTreePathContentProvider) getContentProvider()) .updateElement(treePath, index); } else { ((ILazyTreeContentProvider) getContentProvider()).updateElement( widget.getData(), index); } } /** * Update the child count * @param widget * @param currentChildCount */ private void virtualLazyUpdateChildCount(Widget widget, int currentChildCount) { if (contentProviderIsTreeBased) { TreePath treePath; if (widget instanceof Item) { treePath = getTreePathFromItem((Item) widget); } else { treePath = TreePath.EMPTY; } ((ILazyTreePathContentProvider) getContentProvider()) .updateChildCount(treePath, currentChildCount); } else { ((ILazyTreeContentProvider) getContentProvider()).updateChildCount(widget.getData(), currentChildCount); } } /** * Update the item with the current child count. * @param item * @param currentChildCount */ private void virtualLazyUpdateHasChildren(Item item, int currentChildCount) { if (contentProviderIsTreeBased) { TreePath treePath; treePath = getTreePathFromItem(item); if (currentChildCount == 0) { // item is not expanded (but may have a plus currently) ((ILazyTreePathContentProvider) getContentProvider()) .updateHasChildren(treePath); } else { ((ILazyTreePathContentProvider) getContentProvider()) .updateChildCount(treePath, currentChildCount); } } else { ((ILazyTreeContentProvider) getContentProvider()).updateChildCount(item.getData(), currentChildCount); } } protected void disassociate(Item item) { if (contentProviderIsLazy) { // avoid causing a callback: item.setText(" "); //$NON-NLS-1$ } super.disassociate(item); } protected int doGetColumnCount() { return tree.getColumnCount(); } /** * Sets a new selection for this viewer and optionally makes it visible. * <p> * <b>Currently the <code>reveal</code> parameter is not honored because * {@link Tree} does not provide an API to only select an item without * scrolling it into view</b> * </p> * * @param selection * the new selection * @param reveal * <code>true</code> if the selection is to be made visible, * and <code>false</code> otherwise */ public void setSelection(ISelection selection, boolean reveal) { super.setSelection(selection, reveal); } public void editElement(Object element, int column) { if( element instanceof TreePath ) { setSelection(new TreeSelection((TreePath) element)); TreeItem[] items = tree.getSelection(); if( items.length == 1 ) { ViewerRow row = getViewerRowFromItem(items[0]); if (row != null) { ViewerCell cell = row.getCell(column); if (cell != null) { getControl().setRedraw(false); triggerEditorActivationEvent(new ColumnViewerEditorActivationEvent(cell)); getControl().setRedraw(true); } } } } else { super.editElement(element, column); } } }
false
true
public void replace(final Object parentElementOrTreePath, final int index, final Object element) { preservingSelection(new Runnable() { public void run() { Widget[] itemsToDisassociate; if (parentElementOrTreePath instanceof TreePath) { TreePath elementPath = ((TreePath)parentElementOrTreePath).createChildPath(element); itemsToDisassociate = internalFindItems(elementPath); } else { itemsToDisassociate = internalFindItems(element); } if (internalIsInputOrEmptyPath(parentElementOrTreePath)) { if (index < tree.getItemCount()) { TreeItem item = tree.getItem(index); // disassociate any differen item that represents the // same element under the same parent (the tree) for (int i = 0; i < itemsToDisassociate.length; i++) { if (itemsToDisassociate[i] instanceof TreeItem) { TreeItem itemToDisassociate = (TreeItem)itemsToDisassociate[i]; if (itemToDisassociate != item && itemToDisassociate.getParentItem() == null) { int index = getTree().indexOf(itemToDisassociate); disassociate(itemToDisassociate); getTree().clear(index, true); } } } updateItem(item, element); item.clearAll(true); } } else { Widget[] parentItems = internalFindItems(parentElementOrTreePath); for (int i = 0; i < parentItems.length; i++) { TreeItem parentItem = (TreeItem) parentItems[i]; if (index < parentItem.getItemCount()) { TreeItem item = parentItem.getItem(index); // disassociate any differen item that represents the // same element under the same parent (the tree) for (int j = 0; j < itemsToDisassociate.length; j++) { if (itemsToDisassociate[j] instanceof TreeItem) { TreeItem itemToDisassociate = (TreeItem)itemsToDisassociate[j]; if (itemToDisassociate != item && itemToDisassociate.getParentItem() == parentItem) { int index = parentItem.indexOf(itemToDisassociate); disassociate(itemToDisassociate); parentItem.clear(index, true); } } } updateItem(item, element); item.clearAll(true); } } } } }); }
public void replace(final Object parentElementOrTreePath, final int index, final Object element) { preservingSelection(new Runnable() { public void run() { Widget[] itemsToDisassociate; if (parentElementOrTreePath instanceof TreePath) { TreePath elementPath = ((TreePath)parentElementOrTreePath).createChildPath(element); itemsToDisassociate = internalFindItems(elementPath); } else { itemsToDisassociate = internalFindItems(element); } if (internalIsInputOrEmptyPath(parentElementOrTreePath)) { if (index < tree.getItemCount()) { TreeItem item = tree.getItem(index); // disassociate any differen item that represents the // same element under the same parent (the tree) for (int i = 0; i < itemsToDisassociate.length; i++) { if (itemsToDisassociate[i] instanceof TreeItem) { TreeItem itemToDisassociate = (TreeItem)itemsToDisassociate[i]; if (itemToDisassociate != item && itemToDisassociate.getParentItem() == null) { int index = getTree().indexOf(itemToDisassociate); disassociate(itemToDisassociate); getTree().clear(index, true); } } } Object oldData = item.getData(); updateItem(item, element); if (!TreeViewer.this.equals(oldData, element)) { item.clearAll(true); } } } else { Widget[] parentItems = internalFindItems(parentElementOrTreePath); for (int i = 0; i < parentItems.length; i++) { TreeItem parentItem = (TreeItem) parentItems[i]; if (index < parentItem.getItemCount()) { TreeItem item = parentItem.getItem(index); // disassociate any differen item that represents the // same element under the same parent (the tree) for (int j = 0; j < itemsToDisassociate.length; j++) { if (itemsToDisassociate[j] instanceof TreeItem) { TreeItem itemToDisassociate = (TreeItem)itemsToDisassociate[j]; if (itemToDisassociate != item && itemToDisassociate.getParentItem() == parentItem) { int index = parentItem.indexOf(itemToDisassociate); disassociate(itemToDisassociate); parentItem.clear(index, true); } } } Object oldData = item.getData(); updateItem(item, element); if (!TreeViewer.this.equals(oldData, element)) { item.clearAll(true); } } } } } }); }
diff --git a/src/main/java/com/alexrnl/commons/utils/object/ReflectUtils.java b/src/main/java/com/alexrnl/commons/utils/object/ReflectUtils.java index 8e71447..03f0a6b 100644 --- a/src/main/java/com/alexrnl/commons/utils/object/ReflectUtils.java +++ b/src/main/java/com/alexrnl/commons/utils/object/ReflectUtils.java @@ -1,83 +1,82 @@ package com.alexrnl.commons.utils.object; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * Utilities methods for reflection and dynamic Java usage.<br /> * @author Alex */ public final class ReflectUtils { /** Logger */ private static Logger lg = Logger.getLogger(ReflectUtils.class.getName()); /** * Constructor #1.<br /> * Private default constructor. */ private ReflectUtils () { super(); } /** * Retrieve the methods for the class marked with the specified annotation.<br /> * @param objClass * the class to parse. * @param annotationClass * the annotation to find. * @return a {@link Set} with the {@link Method} annotated with <code>annotationClass</code>. * @see Class#getMethods() */ public static Set<Method> retrieveMethods (final Class<?> objClass, final Class<? extends Annotation> annotationClass) { final Set<Method> fieldMethods = new HashSet<>(); for (final Method method : objClass.getMethods()) { - final Annotation annotation = method.getAnnotation(annotationClass); - if (annotationClass == null || annotation != null) { + if (annotationClass == null || method.getAnnotation(annotationClass) != null) { if (lg.isLoggable(Level.FINE)) { lg.fine("Added method: " + method.getName()); } fieldMethods.add(method); } } return fieldMethods; } /** * Invoke the following list of methods (with no parameter) and return the result in a * {@link List}. * @param target * the target object. * @param methods * the methods to invoke. * @return the result of the method call. * @throws InvocationTargetException * if one of the underlying method throws an exception * @throws IllegalArgumentException * if the method is an instance method and the specified object argument is not an * instance of the class or interface declaring the underlying method (or of a subclass * or implementor thereof); if the number of actual and formal parameters differ; if an * unwrapping conversion for primitive arguments fails; or if, after possible * unwrapping, a parameter value cannot be converted to the corresponding formal * parameter type by a method invocation conversion. * @throws IllegalAccessException * if one of the Method object is enforcing Java language access control and the underlying * method is inaccessible. */ public static List<Object> invokeMethods (final Object target, final List<Method> methods) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { final List<Object> results = new ArrayList<>(methods.size()); for (final Method method : methods) { results.add(method.invoke(target, (Object[]) null)); } return results; } }
true
true
public static Set<Method> retrieveMethods (final Class<?> objClass, final Class<? extends Annotation> annotationClass) { final Set<Method> fieldMethods = new HashSet<>(); for (final Method method : objClass.getMethods()) { final Annotation annotation = method.getAnnotation(annotationClass); if (annotationClass == null || annotation != null) { if (lg.isLoggable(Level.FINE)) { lg.fine("Added method: " + method.getName()); } fieldMethods.add(method); } } return fieldMethods; }
public static Set<Method> retrieveMethods (final Class<?> objClass, final Class<? extends Annotation> annotationClass) { final Set<Method> fieldMethods = new HashSet<>(); for (final Method method : objClass.getMethods()) { if (annotationClass == null || method.getAnnotation(annotationClass) != null) { if (lg.isLoggable(Level.FINE)) { lg.fine("Added method: " + method.getName()); } fieldMethods.add(method); } } return fieldMethods; }
diff --git a/guma/arithmetic/Praxis.java b/guma/arithmetic/Praxis.java index a7f149b..32d5dcb 100644 --- a/guma/arithmetic/Praxis.java +++ b/guma/arithmetic/Praxis.java @@ -1,288 +1,288 @@ /** *GUMA a simple math game for elementary school students * Copyright (C) 2011-1012 Dimitrios Desyllas (pc_magas) * * 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/>. * * Contact with me by main at thes address: [email protected] */ package guma.arithmetic; import java.util.Random; import java.io.Serializable; import java.util.Arrays; /** *A class that simulates a basic Arithmetic Praxis */ public abstract class Praxis implements Serializable { /** *The first operator of an arithmatic praxis. In case of substraction can be the second operator. */ private int telestis1; /** *The second Operator of a arithmetic praxis. In case of substraction can be the first operator. */ private int telestis2; /** *The results of an arithmetic praxis */ protected int[] apotelesma=new int[2]; /** This variable helps us to count how many resurs are required in order to check oif this arithmetic praxis is correct */ protected int results=1; /** *The symbol of ADDING */ public static final char ADDING='+'; /** *The symbol of Substraction */ public static final char SUBSTRACTION='-'; /** *The symbol of multiplication */ public static final char MULTIPLICATION='*'; /** *The symbol of division */ public static final char DIVISION='/'; /** *Modulo Position */ public static final int MODULO_POS=1; /** *Returns the praxis type */ protected char praxistype; /** *Constructor method that creates a random arithmetic praxis eg 2+2 *@param maxNum: The maximum value that can have a number as Operator. */ public Praxis(int maxNum) { Random r=new Random(); apotelesma=new int[results]; setTelestes(r.nextInt(maxNum),r.nextInt(maxNum)); } /** *Constructor method that creates a random arithmetic praxis eg. 2+2,5-3,12/3 etc etc *The operators will get values : minNum<=operator<=maxNum *@param maxNum: The maximum value that can have a number as operator. *@param minNUM: The minumum value that can have a number as operator. */ public Praxis(int maxNum,int minNum,int results) { Random r=new Random(); setTelestes(r.nextInt(maxNum-minNum-1)+1,r.nextInt(maxNum-minNum-1)+1); this.results=results; } /** *Constructor methos that creates a basic arithmetic praxis with operetors telestis1 and telestis2 *@param telestis1: The first operator of an arithmetic praxis *@param telestis2: The second operator of an arithmetic praxis */ public Praxis(int telestis1, int telestis2) { setTelestes(telestis1,telestis2); } /** *Compares and tells us if thew giver result is correct *@param apotelesma: The result that we want to check if it is correct */ public boolean checkResult(int[] apotelesma) { return (getWrongResult(apotelesma)<0)?true:false; } /** *Returns the position of the wrong result *@param apotelesma: The results that we want to search the wrong one */ public int getWrongResult(int[] apotelesma) { for(int i=0;i<results;i++) { if(this.apotelesma[i]!=apotelesma[i]) { return i; } } return -1; } /** *With this method we set the telestes od an arithmetic praxis *@param telestis1: The first operator of an arithmetic praxis *@param telestis2: The second operator of an arithmetic praxis */ public void setTelestes(int telestis1,int telestis2) { this.telestis1=telestis1; this.telestis2=telestis2; doPraxis(); } /** *With this method we get the first parameter of an arithmetic praxis */ public int getTelestis1() { return telestis1; } /** *With this method we get the second parameter of an arithmetic praxis */ public int getTelestis2() { return telestis2; } /** *With this we get the result of an arithmetic praxis */ public int getApotelesma() { return apotelesma[0]; } /** *Getting the results of the Game */ public int[] getResultsVal() { return Arrays.copyOf(apotelesma,apotelesma.length); } /** *We check if an arithmetic praxis equals with an another one */ public boolean equals(Praxis other) { if(((telestis1==other.getTelestis1())&& (telestis2==other.getTelestis2())) && apotelesma[0]==other.getApotelesma()) { return true; } else { return false; } } /** *This method returns the number ot the results required */ public int getResults() { return results; } /** *Returns the operationSymbol */ public char getPraxisType() { return praxistype; } /** *This method executes the arithmetic praxis */ protected abstract void doPraxis(); /** *Return a string form of the Praxis */ public abstract String toString(); /** *Returns a string form of the praxis Including the result */ public abstract String toFullString(); /** *Create the correct type of arithmetic Operation *@param praxistype: This param tells us what kind of arithmetic Operation you want to have *@param telestis1: This param tells you the first numper that will participate into this Operation *@param telestis2: This param tells you the second number that will participate into this Operation */ public static Praxis makePraxis(char praxisType,int telestis1, int telestis2) { Praxis p=null; switch(praxisType) { case Praxis.ADDING: p=new Prosthesis(telestis1,telestis2); break; case Praxis.SUBSTRACTION: p=new Afairesis(telestis1,telestis2); break; case Praxis.DIVISION: p=new Diairesis(telestis1,telestis2); break; case Praxis.MULTIPLICATION: p=new Multiplication(telestis1,telestis2); } return p; } /** *Create the correct type of arithmetic Operation *@param praxistype: This param tells us what kind of arithmetic Operation you want to have *@param telestis1: This param tells you the first numbers that will participate into this Operation */ public static Praxis makePraxis(char praxisType,int maxNum) { Praxis p=null; switch(praxisType) { case Praxis.ADDING: - p=new Prosthesis(maxNum+1); + p=new Prosthesis(maxNum); break; case Praxis.SUBSTRACTION: - p=new Afairesis(maxNum+1); + p=new Afairesis(maxNum); break; case Praxis.DIVISION: - p=new Diairesis(maxNum+1); + p=new Diairesis(maxNum); break; case Praxis.MULTIPLICATION: - p=new Multiplication(maxNum+1); + p=new Multiplication(maxNum); } return p; } }
false
true
public static Praxis makePraxis(char praxisType,int maxNum) { Praxis p=null; switch(praxisType) { case Praxis.ADDING: p=new Prosthesis(maxNum+1); break; case Praxis.SUBSTRACTION: p=new Afairesis(maxNum+1); break; case Praxis.DIVISION: p=new Diairesis(maxNum+1); break; case Praxis.MULTIPLICATION: p=new Multiplication(maxNum+1); } return p; }
public static Praxis makePraxis(char praxisType,int maxNum) { Praxis p=null; switch(praxisType) { case Praxis.ADDING: p=new Prosthesis(maxNum); break; case Praxis.SUBSTRACTION: p=new Afairesis(maxNum); break; case Praxis.DIVISION: p=new Diairesis(maxNum); break; case Praxis.MULTIPLICATION: p=new Multiplication(maxNum); } return p; }
diff --git a/src/main/MainWindow.java b/src/main/MainWindow.java index b9f475b..4e93813 100644 --- a/src/main/MainWindow.java +++ b/src/main/MainWindow.java @@ -1,119 +1,120 @@ /* * MainWindow.java * * Created on 2010/05/16, 0:56:28 */ package main; import java.awt.event.KeyEvent; /** * * @author yayugu */ public class MainWindow extends javax.swing.JFrame { Data data = Data.getInstance(); boolean ctrlPressed = false; /** Creates new form MainWindow */ public MainWindow() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { textArea = new javax.swing.JTextArea(); labelCount = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("そーめん大陸"); textArea.setColumns(20); textArea.setLineWrap(true); textArea.setRows(5); + textArea.setMinimumSize(new java.awt.Dimension(1, 1)); textArea.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { MainWindow.this.keyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { MainWindow.this.keyReleased(evt); } }); labelCount.setText("140"); labelCount.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { labelCountClick(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(labelCount)) .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelCount)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void labelCountClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_labelCountClick if(javax.swing.SwingUtilities.isRightMouseButton(evt)){ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AuthWindow().setVisible(true); } }); } else if(javax.swing.SwingUtilities.isMiddleMouseButton(evt)){ } else if(javax.swing.SwingUtilities.isLeftMouseButton(evt)){ this.dispose(); this.setUndecorated( !this.isUndecorated() ); this.setVisible( true ); } }//GEN-LAST:event_labelCountClick private void keyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyPressed if(evt.getKeyCode() == KeyEvent.VK_ENTER && ctrlPressed){ try{ data.twitter.updateStatus(textArea.getText()); }catch(Exception e){ e.printStackTrace(); } textArea.setText(""); } else if(evt.getKeyCode() == KeyEvent.VK_CONTROL) { ctrlPressed = true; } labelCount.setText(Integer.toString(140 - textArea.getText().length())); }//GEN-LAST:event_keyPressed private void keyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_keyReleased if(evt.getKeyCode() == KeyEvent.VK_CONTROL) { ctrlPressed = false; } }//GEN-LAST:event_keyReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel labelCount; private javax.swing.JTextArea textArea; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { textArea = new javax.swing.JTextArea(); labelCount = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("そーめん大陸"); textArea.setColumns(20); textArea.setLineWrap(true); textArea.setRows(5); textArea.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { MainWindow.this.keyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { MainWindow.this.keyReleased(evt); } }); labelCount.setText("140"); labelCount.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { labelCountClick(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(labelCount)) .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelCount)) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { textArea = new javax.swing.JTextArea(); labelCount = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("そーめん大陸"); textArea.setColumns(20); textArea.setLineWrap(true); textArea.setRows(5); textArea.setMinimumSize(new java.awt.Dimension(1, 1)); textArea.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { MainWindow.this.keyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { MainWindow.this.keyReleased(evt); } }); labelCount.setText("140"); labelCount.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { labelCountClick(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(labelCount)) .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(textArea, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelCount)) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/Cube.java b/Cube.java index 1a9335e..f981300 100644 --- a/Cube.java +++ b/Cube.java @@ -1,507 +1,507 @@ import java.util.*; /* * Cube.java * making a test comment */ public class Cube { // Constants public static int X = 0; public static int Y = 1; public static int Z = 2; public static int BLACK = 0; public static int WHITE = 1; public static int EMPTY = 2; public static int DOME = 3; public static int XUP = 0; public static int XDOWN = 1; public static int YUP = 2; public static int YDOWN = 3; public static int ZUP = 4; public static int ZDOWN = 5; public static int NONE = -1; // Data members private int[] location; private int[] faces; private int color; private HashMap<String, Cube> board; // Constructor public Cube (int x, int y, int z, int d1, int d2, int color) { location = new int[3]; location[X] = x; location[Y] = y; location[Z] = z; faces = new int[6]; for (int i = 0; i < faces.length; i++) { if (i == d1 || i == d2) { faces[i] = DOME; } else { faces[i] = EMPTY; } } this.color = color; } public void setBoard(HashMap<String, Cube> b) { this.board = b; } public int getFace(int f) { if (f == NONE) { return NONE; } return faces[f]; } public String getName() { return "" + getX() + "," + getY() + "," + getZ(); } public int getColor() { return color; } public int getX() { return location[X]; } public int getY() { return location[Y]; } public int getZ() { return location[Z]; } public Cube clone() { Cube c = new Cube(location[X], location[Y], location[Z], firstDome(), secondDome(), color); if (c.addSceptre(firstSceptre(), getFace(firstSceptre()))) { c.addSceptre(secondSceptre(), getFace(secondSceptre())); } return c; } public int firstDome() { for (int i = 0; i < faces.length; i++) { if (faces[i] == DOME) { return i; } } // should NEVER happen System.err.println("UHOH!!!"); return NONE; } public int secondDome() { for (int i = firstDome() + 1; i < faces.length; i++) { if (faces[i] == DOME) { return i; } } return NONE; } public int firstSceptre() { for (int i = 0; i < faces.length; i++) { if (faces[i] == BLACK || faces[i] == WHITE) { return i; } } return NONE; } public int secondSceptre() { int f = firstSceptre(); if (f == NONE) { return NONE; } for (int i = f + 1; i < faces.length; i++) { if (faces[i] == BLACK || faces[i] == WHITE) { return i; } } return NONE; } public boolean addSceptre(int f, int color) { if (f != NONE && isEmpty(f)) { faces[f] = color; return true; } return false; } public int removeSceptre(int f) { if (faces[f] == WHITE || faces[f] == BLACK) { int temp = faces[f]; faces[f] = EMPTY; // return temp; } return -1; } public boolean isEncroached() { for (int i = 0; i < faces.length; i++) { if (faces[i] == WHITE && color == BLACK) { return true; } if (faces[i] == BLACK && color == WHITE) { return true; } } return false; } public boolean isOccupied() { for (int i = 0; i < faces.length; i++) { if (faces[i] == WHITE || faces[i] == BLACK) { return true; } } return false; } public boolean isFree() { if (isOccupied()) { return false; } String above = "" + location[X] + "," + location[Y] + "," + (location[Z] + 1); if (board.get(above) == null) { return true; } return false; } public Cube getNeighbor(int f) { if (f == ZUP) { return board.get("" + getX() + "," + getY() + "," + (getZ() + 1)); } else if (f == ZDOWN) { return board.get("" + getX() + "," + getY() + "," + (getZ() - 1)); } else if (f == YUP) { return board.get("" + getX() + "," + (getY() + 1) + "," + getZ()); } else if (f == YDOWN) { return board.get("" + getX() + "," + (getY() - 1) + "," + getZ()); } else if (f == XUP) { return board.get("" + (getX() + 1) + "," + getY() + "," + getZ()); } else if (f == XDOWN) { return board.get("" + (getX() - 1)+ "," + getY() + "," + getZ()); } return null; } public Cube getNeighbor(int dx, int dy, int dz) { return board.get("" + (getX() + dx) + "," + (getY() + dy) + "," + (getZ() + dz)); } public ArrayList<Integer> freeFaces() { ArrayList<Integer> free = new ArrayList<Integer>(); for (int i = 0; i < faces.length; i++) { if (faces[i] == EMPTY || faces[i] == DOME) { String neighbor = null; String support = null; if (i == XUP) { support = "" + (location[X] + 1) + "," + location[Y] + "," + (location[Z] -1); if (location[Z] == 1 || board.get(support) != null) { neighbor = "" + (location[X] + 1) + "," + location[Y] + "," + location[Z]; } } else if (i == YUP) { support = "" + location[X] + "," + (location[Y] + 1) + "," + (location[Z] -1); if (location[Z] == 1 || board.get(support) != null) { neighbor = "" + location[X] + "," + (location[Y] + 1) + "," + location[Z]; } } else if (i == ZUP) { neighbor = "" + location[X] + "," + location[Y] + "," + (location[Z] + 1); } else if (i == XDOWN) { support = "" + (location[X] + 1) + "," + location[Y] + "," + (location[Z] - 1); if (location[Z] == 1 || board.get(support) != null) { neighbor = "" + (location[X] - 1) + "," + location[Y] + "," + location[Z]; } } else if (i == YDOWN) { support = "" + location[X] + "," + (location[Y] - 1) + "," + (location[Z] -1); if (location[Z] == 1 || board.get(support) != null) { neighbor = "" + location[X] + "," + (location[Y] - 1) + "," + location[Z]; } } if (neighbor != null && board.get(neighbor) == null) { free.add(i); } } } return free; } public boolean lockedDome() { // do you have a locked dome? *Denotes legal positioning* for (int i = 0; i < faces.length; i++) { String neighbor = null; if (faces[i] == XUP) { neighbor = "" + (location[X] + 1) + "," + location[Y] + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == XDOWN) { neighbor = "" + (location[X] - 1) + "," + location[Y] + "," + location[Z]; if (board.containsKey(neighbor)) { - if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ + if ((faces[i] == DOME && board.get(neighbor).getFace(XUP) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XUP) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == YUP) { neighbor = "" + location[X] + "," + (location[Y] + 1) + "," + location[Z]; if (board.containsKey(neighbor)) { - if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ + if ((faces[i] == DOME && board.get(neighbor).getFace(YDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(YDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == YDOWN) { neighbor = "" + location[X] + "," + (location[Y] - 1) + "," + location[Z]; if (board.containsKey(neighbor)) { - if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ + if ((faces[i] == DOME && board.get(neighbor).getFace(YUP) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(YUP) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == ZUP) { neighbor = "" + location[X] + "," + location[Y] + "," + (location[Z] + 1); if (board.containsKey(neighbor)) { - if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ + if ((faces[i] == DOME && board.get(neighbor).getFace(ZDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(ZDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == ZDOWN) { neighbor = "" + location[X] + "," + location[Y] + "," + (location[Z] - 1); if (board.containsKey(neighbor)) { - if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ + if ((faces[i] == DOME && board.get(neighbor).getFace(ZUP) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(ZUP) == DOME)){ System.out.println("did it work?"); return true; } } } } return false; } public boolean twoSceptreSameColor() { int first = getFace(firstSceptre()); int second = getFace(secondSceptre()); if (first != NONE) { return first == second; } return false; } public boolean twoSceptreDifferentColor() { int first = getFace(firstSceptre()); int second = getFace(secondSceptre()); if (first != NONE && second != NONE) { return first != second; } return false; } public boolean isEmpty(int f) { return faces[f] == EMPTY; } // Rotate the cube in the direction d, being one of X, Y or Z public void rotate(int d) { if (d == Y) { int temp = faces[XUP]; faces[XUP] = faces[ZUP]; faces[ZUP] = faces[XDOWN]; faces[XDOWN] = faces[ZDOWN]; faces[ZDOWN] = temp; } else if (d == X) { int temp = faces[YUP]; faces[YUP] = faces[ZUP]; faces[ZUP] = faces[YDOWN]; faces[YDOWN] = faces[ZDOWN]; faces[ZDOWN] = temp; } else if (d == Z) { int temp = faces[XUP]; faces[XUP] = faces[YDOWN]; faces[YDOWN] = faces[XDOWN]; faces[XDOWN] = faces[YUP]; faces[YUP] = temp; } } // Use the notation from the play by email paper public String toString() { String c = "C (" + getX() + "," + getY() + "," + getZ() + ")"; int fd = firstDome(); if (fd == XUP) { c += "x+"; } else if (fd == XDOWN) { c += "x-"; } else if (fd == YUP) { c += "y+"; } else if (fd == YDOWN) { c += "y-"; } else if (fd == ZUP) { c += "z+"; } else if (fd == ZDOWN) { c += "z-"; } if (secondDome() != NONE) { int sd = secondDome(); if (sd == XUP) { c += " x+"; } else if (sd == XDOWN) { c += " x-"; } else if (sd == YUP) { c += " y+"; } else if (sd == YDOWN) { c += " y-"; } else if (sd == ZUP) { c += " z+"; } else if (sd == ZDOWN) { c += " z-"; } } if (color == WHITE) { c += " (white) "; } else { c += " (black) "; } return c; } // Use the notation from the play by email paper public String toSceptreString() { String t = ""; String s = "S (" + getX() + "," + getY() + "," + getZ() + ")"; if (firstSceptre() != NONE) { t += s; int fs = firstSceptre(); if (fs == XUP) { t += "x+"; } else if (fs == XDOWN) { t += "x-"; } else if (fs == YUP) { t += "y+"; } else if (fs == YDOWN) { t += "y-"; } else if (fs == ZUP) { t += "z+"; } else if (fs == ZDOWN) { t += "z-"; } if (getFace(firstSceptre()) == WHITE) { t += " (white) "; } else { t += " (black) "; } if (secondSceptre() != NONE) { t += "\n" + s; int ss = secondSceptre(); if (ss == XUP) { t += " x+"; } else if (ss == XDOWN) { t += " x-"; } else if (ss == YUP) { t += " y+"; } else if (ss == YDOWN) { t += " y-"; } else if (ss == ZUP) { t += " z+"; } else if (ss == ZDOWN) { t += " z-"; } if (getFace(secondSceptre()) == WHITE) { t += " (white) "; } else { t += " (black) "; } } } return t; } public static void main (String args[]) { HashMap<String, Cube> b = new HashMap<String, Cube>(); Cube stuff = new Cube(-1, 0, 2, XUP, NONE, BLACK); stuff.addSceptre(ZUP, BLACK); stuff.setBoard(b); b.put(stuff.getName(), stuff); System.out.println(stuff); System.out.println(stuff.toSceptreString()); System.out.println("rotating"); stuff.rotate(X); System.out.println(stuff); System.out.println(stuff.toSceptreString()); } }
false
true
public boolean lockedDome() { // do you have a locked dome? *Denotes legal positioning* for (int i = 0; i < faces.length; i++) { String neighbor = null; if (faces[i] == XUP) { neighbor = "" + (location[X] + 1) + "," + location[Y] + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == XDOWN) { neighbor = "" + (location[X] - 1) + "," + location[Y] + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == YUP) { neighbor = "" + location[X] + "," + (location[Y] + 1) + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == YDOWN) { neighbor = "" + location[X] + "," + (location[Y] - 1) + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == ZUP) { neighbor = "" + location[X] + "," + location[Y] + "," + (location[Z] + 1); if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == ZDOWN) { neighbor = "" + location[X] + "," + location[Y] + "," + (location[Z] - 1); if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } } return false; }
public boolean lockedDome() { // do you have a locked dome? *Denotes legal positioning* for (int i = 0; i < faces.length; i++) { String neighbor = null; if (faces[i] == XUP) { neighbor = "" + (location[X] + 1) + "," + location[Y] + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == XDOWN) { neighbor = "" + (location[X] - 1) + "," + location[Y] + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(XUP) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(XUP) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == YUP) { neighbor = "" + location[X] + "," + (location[Y] + 1) + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(YDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(YDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == YDOWN) { neighbor = "" + location[X] + "," + (location[Y] - 1) + "," + location[Z]; if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(YUP) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(YUP) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == ZUP) { neighbor = "" + location[X] + "," + location[Y] + "," + (location[Z] + 1); if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(ZDOWN) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(ZDOWN) == DOME)){ System.out.println("did it work?"); return true; } } } if (faces[i] == ZDOWN) { neighbor = "" + location[X] + "," + location[Y] + "," + (location[Z] - 1); if (board.containsKey(neighbor)) { if ((faces[i] == DOME && board.get(neighbor).getFace(ZUP) == EMPTY) || (faces[i] == EMPTY && board.get(neighbor).getFace(ZUP) == DOME)){ System.out.println("did it work?"); return true; } } } } return false; }
diff --git a/car.ioMockup/src/car/io/application/ECApplication.java b/car.ioMockup/src/car/io/application/ECApplication.java index 8bff4d44..a938d07e 100644 --- a/car.ioMockup/src/car/io/application/ECApplication.java +++ b/car.ioMockup/src/car/io/application/ECApplication.java @@ -1,865 +1,874 @@ package car.io.application; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import android.app.Application; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.ParseException; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import car.io.adapter.DbAdapter; import car.io.adapter.DbAdapterLocal; import car.io.adapter.DbAdapterRemote; import car.io.adapter.Measurement; import car.io.adapter.Track; import car.io.commands.CommonCommand; import car.io.commands.MAF; import car.io.commands.Speed; import car.io.exception.FuelConsumptionException; import car.io.exception.LocationInvalidException; import car.io.exception.MeasurementsException; import car.io.exception.TracksException; import car.io.obd.BackgroundService; import car.io.obd.Listener; import car.io.obd.ServiceConnector; /** * This is the main application that is the central linking component for all adapters, services and so on. * This application is implemented like a singleton, it exists only once while the app is running. * @author gerald, jakob * */ public class ECApplication extends Application implements LocationListener { public static final String BASE_URL = "https://giv-car.uni-muenster.de/stable/rest"; public static final String PREF_KEY_CAR_MODEL = "carmodel"; public static final String PREF_KEY_CAR_MANUFACTURER = "manufacturer"; public static final String PREF_KEY_CAR_CONSTRUCTION_YEAR = "constructionyear"; public static final String PREF_KEY_FUEL_TYPE = "fueltype"; public static final String PREF_KEY_SENSOR_ID = "sensorid"; private SharedPreferences preferences = null; private DbAdapter dbAdapterLocal; private DbAdapter dbAdapterRemote; private final ScheduledExecutorService scheduleTaskExecutor = Executors .newScheduledThreadPool(1); // get the default Bluetooth adapter private final BluetoothAdapter bluetoothAdapter = BluetoothAdapter .getDefaultAdapter(); private ServiceConnector serviceConnector = null; private Intent backgroundService = null; private Handler handler = new Handler(); private Listener listener = null; private LocationManager locationManager; private float locationLatitude; private float locationLongitude; private int speedMeasurement = 0; private double co2Measurement = 0.0; private double mafMeasurement; private Measurement measurement = null; private long lastInsertTime = 0; private Track track; private String trackName = "Some Name"; private String trackDescription = "Some Description"; private boolean requirementsFulfilled = true; private static User user; /** * Returns the service connector of the server * @return the serviceConnector */ public ServiceConnector getServiceConnector() { return serviceConnector; } /** * Returns whether requirements were fulfilled (bluetooth activated) * @return requirementsFulfilled? */ public boolean requirementsFulfilled() { return requirementsFulfilled; } /** * This method updates the attributes of the current sensor (=car) * @param sensorid the id that is stored on the server * @param carManufacturer the car manufacturer * @param carModel the car model * @param fuelType the fuel type of the car * @param year construction year of the car */ public void updateCurrentSensor(String sensorid, String carManufacturer, String carModel, String fuelType, int year) { Editor e = preferences.edit(); e.putString(PREF_KEY_SENSOR_ID, sensorid); e.putString(PREF_KEY_CAR_MANUFACTURER, carManufacturer); e.putString(PREF_KEY_CAR_MODEL, carModel); e.putString(PREF_KEY_FUEL_TYPE, fuelType); e.putString(PREF_KEY_CAR_CONSTRUCTION_YEAR, year + ""); e.commit(); } @Override public void onCreate() { super.onCreate(); // TODO: Create something like a first-start method that determines the // BT-Adapter, VIN etc. ... something like a setup method initDbAdapter(); checkRequirementsForBluetooth(); initLocationManager(); // AutoConnect checkbox and service // TODO settings -> automatic connection to bt adapter // startServiceConnector(); // Make a new listener to interpret the measurement values that are // returned Log.e("obd2", "init listener"); startListener(); // If everything is available, start the service connector and listener startBackgroundService(); // createNewTrackIfNecessary(); try { measurement = new Measurement(locationLatitude, locationLongitude); } catch (LocationInvalidException e) { e.printStackTrace(); } preferences = PreferenceManager.getDefaultSharedPreferences(this); user = getUserFromSharedPreferences(); } /** * This method determines whether it is necessary to create a new track or * of the current/last used track should be reused */ private void createNewTrackIfNecessary() { // TODO decode vin or read from shared preferences... // setting undefined, will hopefully prevent correct uploading. // but this shouldn't be possible to record tracks without these values String fuelType = preferences .getString(PREF_KEY_FUEL_TYPE, "undefined"); String carManufacturer = preferences.getString( PREF_KEY_CAR_MANUFACTURER, "undefined"); String carModel = preferences .getString(PREF_KEY_CAR_MODEL, "undefined"); String sensorId = preferences .getString(PREF_KEY_SENSOR_ID, "undefined"); // if track is null, create a new one or take the last one from the // database if (track == null) { Log.e("obd2", "The track was null"); Track lastUsedTrack; try { lastUsedTrack = dbAdapterLocal.getLastUsedTrack(); try { // New track if last measurement is more than 60 minutes // ago if ((System.currentTimeMillis() - lastUsedTrack .getLastMeasurement().getMeasurementTime()) > 3600000) { // TODO: make parameters dynamic Log.e("obd2", "I create a new track because the last measurement is more than 60 mins ago"); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); return; } // new track if last position is significantly different // from the current position (more than 3 km) if (getDistance(lastUsedTrack.getLastMeasurement(), locationLatitude, locationLongitude) > 3.0) { Log.e("obd2", "The last measurement's position is more than 3 km away. I will create a new track"); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); return; } // TODO: New track if user clicks on create new track button // TODO: new track if VIN changed else { Log.e("obd2", "I will append to the last track because that still makes sense"); track = lastUsedTrack; return; } } catch (MeasurementsException e) { - Log.e("obd", "Track is empty, so I take the last track."); - track = lastUsedTrack; - e.printStackTrace(); + Log.e("obd", "The last track contains no measurements. I will delete it and create a new one."); + dbAdapterLocal.deleteTrack(lastUsedTrack.getId()); + track = new Track("123456", fuelType, carManufacturer, + carModel, sensorId, dbAdapterLocal); // TODO: + track.setName(trackName); + track.setDescription(trackDescription); + track.commitTrackToDatabase(); } } catch (TracksException e) { track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO: track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); e.printStackTrace(); Log.e("obd2", "There was no track in the database so I created a new one"); } return; } // if track is not null, determine whether it is useful to create a new // track and store the current one //TODO: is it necessary to store // this? normally, this is already in the database if (track != null) { Log.e("obd2", "the track was not null"); Track currentTrack = track; try { // New track if last measurement is more than 60 minutes // ago if ((System.currentTimeMillis() - currentTrack .getLastMeasurement().getMeasurementTime()) > 3600000) { // TODO: make parameters dynamic track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); Log.e("obd2", "I create a new track because the last measurement is more than 60 mins ago"); return; } // TODO: New track if user clicks on create new track button // new track if last position is significantly different from // the // current position (more than 3 km) if (getDistance(currentTrack.getLastMeasurement(), locationLatitude, locationLongitude) > 3.0) { track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); Log.e("obd2", "The last measurement's position is more than 3 km away. I will create a new track"); return; } // TODO: new track if VIN changed else { Log.e("obd2", "I will append to the last track because that still makes sense"); return; } } catch (MeasurementsException e) { - Log.e("obd2", "The track was empty so I will use this track"); - e.printStackTrace(); + Log.e("obd", "The last track contains no measurements. I will delete it and create a new one."); + dbAdapterLocal.deleteTrack(currentTrack.getId()); + track = new Track("123456", fuelType, carManufacturer, + carModel, sensorId, dbAdapterLocal); // TODO: + track.setName(trackName); + track.setDescription(trackDescription); + track.commitTrackToDatabase(); } } } /** * Returns the distance between a measurement and a coordinate in kilometers * * @param m1 * Measurement * @param lat2 * Latitude of coordinate * @param lng2 * Longitude of coordinate * @return */ public double getDistance(Measurement m1, double lat2, double lng2) { double lat1 = m1.getLatitude(); double lng1 = m1.getLongitude(); double earthRadius = 6369; double dLat = Math.toRadians(lat2 - lat1); double dLng = Math.toRadians(lng2 - lng1); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double dist = earthRadius * c; return dist; } /** * This method opens both dbadapters or also gets them and opens them afterwards. */ private void initDbAdapter() { if (dbAdapterLocal == null) { dbAdapterLocal = new DbAdapterLocal(this.getApplicationContext()); dbAdapterLocal.open(); } else { if (!dbAdapterLocal.isOpen()) dbAdapterLocal.open(); } if (dbAdapterRemote == null) { dbAdapterRemote = new DbAdapterRemote(this.getApplicationContext()); dbAdapterRemote.open(); } else { if (!dbAdapterRemote.isOpen()) dbAdapterRemote.open(); } } /** * This checks whether the bluetooth adadpter exists and whether it is enabled. * You can get the result by calling the requirementsFulfilled() funtion. */ private void checkRequirementsForBluetooth() { if (bluetoothAdapter == null) { requirementsFulfilled = false; } else { if (!bluetoothAdapter.isEnabled()) { requirementsFulfilled = false; } } } /** * Checks if a track with specific index is already present in the * dbAdapterRemote * * @param index * @return true if track already stored, false if track is new */ public boolean trackAlreadyInDB(String index) { boolean matchFound = false; ArrayList<Track> allStoredTracks = dbAdapterRemote.getAllTracks(); for (Track trackCompare : allStoredTracks) { Log.i("obd2", "comparing: " + index + ""); Log.i("obd2", "to: " + trackCompare.getId() + ""); if (trackCompare.getId().equals(index)) { Log.i("obd2", "match found"); matchFound = true; return matchFound; } } return matchFound; } /** * Get a user object from the shared preferences * @return the user that is stored on the device */ private User getUserFromSharedPreferences() { if (preferences.contains("username") && preferences.contains("token")) { return new User(preferences.getString("username", "anonymous"), preferences.getString("token", "anon")); } return null; } /** * Set the user (to the application and also store it in the preferences) * @param user The user you want to set */ public void setUser(User user) { ECApplication.user = user; Editor e = preferences.edit(); e.putString("username", user.getUsername()); e.putString("token", user.getToken()); e.apply(); } /** * Get the user * @return user */ public User getUser() { return user; } /** * Determines whether the user is logged in. A user is logged in when * the application has a user as a variable. * @return */ public boolean isLoggedIn() { return user != null; } /** * Logs out the user. */ public void logOut() { if (preferences.contains("username")) preferences.edit().remove("username"); if (preferences.contains("token")) preferences.edit().remove("token"); preferences.edit().apply(); user = null; } /** * Returns the local db adadpter. This has to be called by other * functions in order to work with the data (change tracks and measurements). * @return the local db adapter */ public DbAdapter getDbAdapterLocal() { initDbAdapter(); return dbAdapterLocal; } /** * Get the remote db adapter (to work with the measurements from the server). * @return the remote dbadapter */ public DbAdapter getDbAdapterRemote() { initDbAdapter(); return dbAdapterRemote; } /** * Starts the location manager again after an resume. */ public void startLocationManager() { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } /** * Stops the location manager (removeUpdates) for pause. */ public void stopLocating() { locationManager.removeUpdates(this); } /** * This method starts the service that connects to the adapter to the app. */ public void startBackgroundService() { if (requirementsFulfilled) { Log.e("obd2", "requirements met"); backgroundService = new Intent(this, BackgroundService.class); serviceConnector = new ServiceConnector(); serviceConnector.setServiceListener(listener); bindService(backgroundService, serviceConnector, Context.BIND_AUTO_CREATE); } else { Log.e("obd2", "requirements not met"); } } /** * This method starts the service connector every five minutes if the user * wants an autoconnection */ public void startServiceConnector() { scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() { public void run() { if (requirementsFulfilled) { if (!serviceConnector.isRunning()) { startConnection(); } else { Log.e("obd2", "serviceConnector not running"); } } else { Log.e("obd2", "requirementsFulfilled was false!"); } } }, 0, 5, TimeUnit.MINUTES); } /** * This method starts the listener that interprets the answers from the BT adapter. */ public void startListener() { listener = new Listener() { public void receiveUpdate(CommonCommand job) { Log.e("obd2", "update received"); // Get the name and the result of the Command String commandName = job.getCommandName(); String commandResult = job.getResult(); Log.i("btlogger", commandName + " " + commandResult); if (commandResult.equals("NODATA")) return; /* * Check which measurent is returned and save the value in the * previously created measurement */ // Speed if (commandName.equals("Vehicle Speed")) { try { speedMeasurement = Integer.valueOf(commandResult); } catch (NumberFormatException e) { Log.e("obd2", "speed parse exception"); e.printStackTrace(); } } // MAF if (commandName.equals("Mass Air Flow")) { String maf = commandResult; try { NumberFormat format = NumberFormat .getInstance(Locale.GERMAN); Number number; number = format.parse(maf); mafMeasurement = number.doubleValue(); // Dashboard Co2 current value preparation double consumption = 0.0; if (mafMeasurement != -1.0) { if (preferences.getString(PREF_KEY_FUEL_TYPE, "gasoline").equals("gasoline")) { consumption = (mafMeasurement / 14.7) / 747; } else if (preferences.getString( PREF_KEY_FUEL_TYPE, "gasoline").equals( "diesel")) { consumption = (mafMeasurement / 14.5) / 832; } } if (preferences.getString(PREF_KEY_FUEL_TYPE, "gasoline").equals("gasoline")) { co2Measurement = consumption * 2.35; } else if (preferences.getString(PREF_KEY_FUEL_TYPE, "gasoline").equals("diesel")) { co2Measurement = consumption * 2.65; } } catch (ParseException e) { Log.e("obd", "parse exception maf"); e.printStackTrace(); } catch (java.text.ParseException e) { Log.e("obd", "parse exception maf"); e.printStackTrace(); } } // Update and insert the measurement updateMeasurement(); } }; } /** * Stop the service connector and therefore the scheduled tasks. */ public void stopServiceConnector() { scheduleTaskExecutor.shutdown(); } /** * Connects to the Bluetooth Adapter and starts the execution of the * commands. also opens the db and starts the gps. */ public void startConnection() { openDb(); startLocationManager(); createNewTrackIfNecessary(); if (!serviceConnector.isRunning()) { Log.e("obd2", "service start"); startService(backgroundService); bindService(backgroundService, serviceConnector, Context.BIND_AUTO_CREATE); } handler.post(waitingListRunnable); } /** * Ends the connection with the Bluetooth Adapter. also stops gps and closes the db. */ public void stopConnection() { if (serviceConnector.isRunning()) { stopService(backgroundService); unbindService(serviceConnector); } handler.removeCallbacks(waitingListRunnable); stopLocating(); closeDb(); } /** * Handles the waiting-list */ private Runnable waitingListRunnable = new Runnable() { public void run() { if (serviceConnector.isRunning()) addCommandstoWaitinglist(); handler.postDelayed(waitingListRunnable, 2000); } }; /** * Helper method that adds the desired commands to the waiting list where * all commands are executed */ private void addCommandstoWaitinglist() { final CommonCommand speed = new Speed(); final CommonCommand maf = new MAF(); serviceConnector.addJobToWaitingList(speed); serviceConnector.addJobToWaitingList(maf); } /** * Helper Command that updates the current measurement with the last * measurement data and inserts it into the database if the measurements is * young enough */ public void updateMeasurement() { // Create track new measurement if necessary if (measurement == null) { try { measurement = new Measurement(locationLatitude, locationLongitude); } catch (LocationInvalidException e) { e.printStackTrace(); } } // Insert the values if the measurement (with the coordinates) is young // enough (5000ms) or create track new one if it is too old if (measurement != null) { if (Math.abs(measurement.getMeasurementTime() - System.currentTimeMillis()) < 5000) { measurement.setSpeed(speedMeasurement); measurement.setMaf(mafMeasurement); Log.e("obd2", "new measurement"); Log.e("obd2", measurement.getLatitude() + " " + measurement.getLongitude()); Log.e("obd2", measurement.toString()); insertMeasurement(measurement); } else { try { measurement = new Measurement(locationLatitude, locationLongitude); } catch (LocationInvalidException e) { e.printStackTrace(); } } } } /** * Helper method to insert track measurement into the database (ensures that * track measurement is only stored every 5 seconds and not faster...) * * @param measurement2 * The measurement you want to insert */ private void insertMeasurement(Measurement measurement2) { // TODO: This has to be added with the following conditions: /* * 1)New measurement if more than 50 meters away 2)New measurement if * last measurement more than 1 minute ago 3)New measurement if MAF * value changed significantly (whatever this means... we will have to * investigate on that. also it is not clear whether we should use this * condition because we are vulnerable to noise from the sensor. * therefore, we should include a minimum time between measurements (1 * sec) as well.) */ if (Math.abs(lastInsertTime - measurement2.getMeasurementTime()) > 5000) { lastInsertTime = measurement2.getMeasurementTime(); track.addMeasurement(measurement2); Log.i("obd2", measurement2.toString()); Toast.makeText(getApplicationContext(), measurement2.toString(), Toast.LENGTH_SHORT).show(); } } /** * Init the location Manager */ private void initLocationManager() { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, // 0, // 0, this); } /** * Stops gps, kills service, kills service connector, kills listener and handler */ public void destroyStuff() { stopLocating(); locationManager = null; backgroundService = null; serviceConnector = null; listener = null; handler = null; } /** * updates the location variables when the device moved */ @Override public void onLocationChanged(Location location) { locationLatitude = (float) location.getLatitude(); locationLongitude = (float) location.getLongitude(); } @Override public void onProviderDisabled(String arg0) { } @Override public void onProviderEnabled(String arg0) { } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { } /** * Opens the databases. */ public void openDb() { initDbAdapter(); } /** * Closes both databases. */ public void closeDb() { if (dbAdapterLocal != null) { dbAdapterLocal.close(); // dbAdapterLocal = null; } if (dbAdapterRemote != null) { dbAdapterRemote.close(); // dbAdapterRemote = null; } } /** * @return the speedMeasurement */ public int getSpeedMeasurement() { return speedMeasurement; } /** * @return the track */ public Track getTrack() { return track; } /** * @param track * the track to set */ public void setTrack(Track track) { this.track = track; } /** * * @return the current co2 value */ public double getCo2Measurement() { return co2Measurement; } }
false
true
private void createNewTrackIfNecessary() { // TODO decode vin or read from shared preferences... // setting undefined, will hopefully prevent correct uploading. // but this shouldn't be possible to record tracks without these values String fuelType = preferences .getString(PREF_KEY_FUEL_TYPE, "undefined"); String carManufacturer = preferences.getString( PREF_KEY_CAR_MANUFACTURER, "undefined"); String carModel = preferences .getString(PREF_KEY_CAR_MODEL, "undefined"); String sensorId = preferences .getString(PREF_KEY_SENSOR_ID, "undefined"); // if track is null, create a new one or take the last one from the // database if (track == null) { Log.e("obd2", "The track was null"); Track lastUsedTrack; try { lastUsedTrack = dbAdapterLocal.getLastUsedTrack(); try { // New track if last measurement is more than 60 minutes // ago if ((System.currentTimeMillis() - lastUsedTrack .getLastMeasurement().getMeasurementTime()) > 3600000) { // TODO: make parameters dynamic Log.e("obd2", "I create a new track because the last measurement is more than 60 mins ago"); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); return; } // new track if last position is significantly different // from the current position (more than 3 km) if (getDistance(lastUsedTrack.getLastMeasurement(), locationLatitude, locationLongitude) > 3.0) { Log.e("obd2", "The last measurement's position is more than 3 km away. I will create a new track"); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); return; } // TODO: New track if user clicks on create new track button // TODO: new track if VIN changed else { Log.e("obd2", "I will append to the last track because that still makes sense"); track = lastUsedTrack; return; } } catch (MeasurementsException e) { Log.e("obd", "Track is empty, so I take the last track."); track = lastUsedTrack; e.printStackTrace(); } } catch (TracksException e) { track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO: track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); e.printStackTrace(); Log.e("obd2", "There was no track in the database so I created a new one"); } return; } // if track is not null, determine whether it is useful to create a new // track and store the current one //TODO: is it necessary to store // this? normally, this is already in the database if (track != null) { Log.e("obd2", "the track was not null"); Track currentTrack = track; try { // New track if last measurement is more than 60 minutes // ago if ((System.currentTimeMillis() - currentTrack .getLastMeasurement().getMeasurementTime()) > 3600000) { // TODO: make parameters dynamic track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); Log.e("obd2", "I create a new track because the last measurement is more than 60 mins ago"); return; } // TODO: New track if user clicks on create new track button // new track if last position is significantly different from // the // current position (more than 3 km) if (getDistance(currentTrack.getLastMeasurement(), locationLatitude, locationLongitude) > 3.0) { track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); Log.e("obd2", "The last measurement's position is more than 3 km away. I will create a new track"); return; } // TODO: new track if VIN changed else { Log.e("obd2", "I will append to the last track because that still makes sense"); return; } } catch (MeasurementsException e) { Log.e("obd2", "The track was empty so I will use this track"); e.printStackTrace(); } } }
private void createNewTrackIfNecessary() { // TODO decode vin or read from shared preferences... // setting undefined, will hopefully prevent correct uploading. // but this shouldn't be possible to record tracks without these values String fuelType = preferences .getString(PREF_KEY_FUEL_TYPE, "undefined"); String carManufacturer = preferences.getString( PREF_KEY_CAR_MANUFACTURER, "undefined"); String carModel = preferences .getString(PREF_KEY_CAR_MODEL, "undefined"); String sensorId = preferences .getString(PREF_KEY_SENSOR_ID, "undefined"); // if track is null, create a new one or take the last one from the // database if (track == null) { Log.e("obd2", "The track was null"); Track lastUsedTrack; try { lastUsedTrack = dbAdapterLocal.getLastUsedTrack(); try { // New track if last measurement is more than 60 minutes // ago if ((System.currentTimeMillis() - lastUsedTrack .getLastMeasurement().getMeasurementTime()) > 3600000) { // TODO: make parameters dynamic Log.e("obd2", "I create a new track because the last measurement is more than 60 mins ago"); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); return; } // new track if last position is significantly different // from the current position (more than 3 km) if (getDistance(lastUsedTrack.getLastMeasurement(), locationLatitude, locationLongitude) > 3.0) { Log.e("obd2", "The last measurement's position is more than 3 km away. I will create a new track"); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); return; } // TODO: New track if user clicks on create new track button // TODO: new track if VIN changed else { Log.e("obd2", "I will append to the last track because that still makes sense"); track = lastUsedTrack; return; } } catch (MeasurementsException e) { Log.e("obd", "The last track contains no measurements. I will delete it and create a new one."); dbAdapterLocal.deleteTrack(lastUsedTrack.getId()); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO: track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); } } catch (TracksException e) { track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO: track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); e.printStackTrace(); Log.e("obd2", "There was no track in the database so I created a new one"); } return; } // if track is not null, determine whether it is useful to create a new // track and store the current one //TODO: is it necessary to store // this? normally, this is already in the database if (track != null) { Log.e("obd2", "the track was not null"); Track currentTrack = track; try { // New track if last measurement is more than 60 minutes // ago if ((System.currentTimeMillis() - currentTrack .getLastMeasurement().getMeasurementTime()) > 3600000) { // TODO: make parameters dynamic track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); Log.e("obd2", "I create a new track because the last measurement is more than 60 mins ago"); return; } // TODO: New track if user clicks on create new track button // new track if last position is significantly different from // the // current position (more than 3 km) if (getDistance(currentTrack.getLastMeasurement(), locationLatitude, locationLongitude) > 3.0) { track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); Log.e("obd2", "The last measurement's position is more than 3 km away. I will create a new track"); return; } // TODO: new track if VIN changed else { Log.e("obd2", "I will append to the last track because that still makes sense"); return; } } catch (MeasurementsException e) { Log.e("obd", "The last track contains no measurements. I will delete it and create a new one."); dbAdapterLocal.deleteTrack(currentTrack.getId()); track = new Track("123456", fuelType, carManufacturer, carModel, sensorId, dbAdapterLocal); // TODO: track.setName(trackName); track.setDescription(trackDescription); track.commitTrackToDatabase(); } } }
diff --git a/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/controller/NetCheckState.java b/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/controller/NetCheckState.java index 89ac66f..4a751aa 100644 --- a/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/controller/NetCheckState.java +++ b/BusesSpb/src/main/java/ru/slavabulgakov/busesspb/controller/NetCheckState.java @@ -1,49 +1,51 @@ package ru.slavabulgakov.busesspb.controller; import android.util.Log; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.Timer; import java.util.TimerTask; public class NetCheckState extends State { RequestQueue _queue; Timer _timer; @Override public void start() { super.start(); _queue = Volley.newRequestQueue(_controller.getModel()); _timer = new Timer(); _timer.schedule(new CheckInternetConnectionTimerTask(), 0); } class CheckInternetConnectionTimerTask extends TimerTask { @Override public void run() { StringRequest request = new StringRequest("http://futbix.ru/busesspb/v1_0/list/version/", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("internet", "success"); _controller.switchToLastState(); _controller.getMainActivity().getInternetDenyButtonController().hideInternetDenyIcon(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("internet", "retry"); _timer.schedule(new CheckInternetConnectionTimerTask(), 3000); - _controller.getMainActivity().getInternetDenyButtonController().showInternetDenyIcon(); + if (_controller.getMainActivity() != null) { + _controller.getMainActivity().getInternetDenyButtonController().showInternetDenyIcon(); + } } }); _queue.add(request); } } }
true
true
public void run() { StringRequest request = new StringRequest("http://futbix.ru/busesspb/v1_0/list/version/", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("internet", "success"); _controller.switchToLastState(); _controller.getMainActivity().getInternetDenyButtonController().hideInternetDenyIcon(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("internet", "retry"); _timer.schedule(new CheckInternetConnectionTimerTask(), 3000); _controller.getMainActivity().getInternetDenyButtonController().showInternetDenyIcon(); } }); _queue.add(request); }
public void run() { StringRequest request = new StringRequest("http://futbix.ru/busesspb/v1_0/list/version/", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("internet", "success"); _controller.switchToLastState(); _controller.getMainActivity().getInternetDenyButtonController().hideInternetDenyIcon(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("internet", "retry"); _timer.schedule(new CheckInternetConnectionTimerTask(), 3000); if (_controller.getMainActivity() != null) { _controller.getMainActivity().getInternetDenyButtonController().showInternetDenyIcon(); } } }); _queue.add(request); }
diff --git a/DanmakuFlameMaster/src/main/java/master/flame/danmaku/ui/widget/DanmakuSurfaceView.java b/DanmakuFlameMaster/src/main/java/master/flame/danmaku/ui/widget/DanmakuSurfaceView.java index 7b8ac5c..0656886 100644 --- a/DanmakuFlameMaster/src/main/java/master/flame/danmaku/ui/widget/DanmakuSurfaceView.java +++ b/DanmakuFlameMaster/src/main/java/master/flame/danmaku/ui/widget/DanmakuSurfaceView.java @@ -1,412 +1,413 @@ /* * Copyright (C) 2013 Chen Hui <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package master.flame.danmaku.ui.widget; import android.app.ActivityManager; import android.content.Context; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import master.flame.danmaku.controller.CacheManagingDrawTask; import master.flame.danmaku.controller.DrawHelper; import master.flame.danmaku.controller.DrawTask; import master.flame.danmaku.controller.IDrawTask; import master.flame.danmaku.danmaku.model.BaseDanmaku; import master.flame.danmaku.danmaku.model.DanmakuTimer; import master.flame.danmaku.danmaku.parser.BaseDanmakuParser; public class DanmakuSurfaceView extends SurfaceView implements SurfaceHolder.Callback, View.OnClickListener { public static final String TAG = "DanmakuSurfaceView"; private Callback mCallback; private SurfaceHolder mSurfaceHolder; private HandlerThread mDrawThread; private DrawHandler handler; private DanmakuTimer timer; private IDrawTask drawTask; private long mTimeBase; private boolean isSurfaceCreated; private boolean mEnableDanmakuDrwaingCache; private OnClickListener mOnClickListener; private BaseDanmakuParser mParser; private boolean mShowFps; public DanmakuSurfaceView(Context context) { super(context); init(); } private void init() { setZOrderMediaOverlay(true); mSurfaceHolder = getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT); if (timer == null) { timer = new DanmakuTimer(); } setOnClickListener(this); } @Override public void setOnClickListener(OnClickListener l) { if (l != this) { mOnClickListener = l; } else super.setOnClickListener(l); } public DanmakuSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DanmakuSurfaceView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public void addDanmaku(BaseDanmaku item) { if(drawTask != null){ drawTask.addDanmaku(item); } } public void setCallback(Callback callback) { mCallback = callback; } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { isSurfaceCreated = true; Canvas canvas = surfaceHolder.lockCanvas(); if(canvas!=null){ DrawHelper.clearCanvas(canvas); surfaceHolder.unlockCanvasAndPost(canvas); } } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { } public void release() { stop(); } public void stop() { stopDraw(); } private void stopDraw() { if (drawTask != null) { drawTask.quit(); } if (handler != null) { handler.quit(); handler = null; } if (mDrawThread != null) { mDrawThread.quit(); try { mDrawThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } mDrawThread = null; } } public void prepare() { if (mDrawThread == null) { mDrawThread = new HandlerThread("draw thread"); mDrawThread.start(); handler = new DrawHandler(mDrawThread.getLooper()); handler.sendEmptyMessage(DrawHandler.PREPARE); } } public void prepare(BaseDanmakuParser parser) { prepare(); mParser = parser; } public boolean isPrepared(){ return handler!=null && handler.isPrepared(); } public void showFPS(boolean show){ mShowFps = show; } long drawDanmakus() { if (!isSurfaceCreated) return 0; if(!isShown()) return 0; long stime = System.currentTimeMillis(); long dtime = 0; Canvas canvas = mSurfaceHolder.lockCanvas(); if (canvas != null) { drawTask.draw(canvas); dtime = System.currentTimeMillis() - stime; if(mShowFps){ String fps = String.format("%02d MS, fps %.2f",dtime, 1000 / (float) dtime); DrawHelper.drawText(canvas, fps); } mSurfaceHolder.unlockCanvasAndPost(canvas); } return dtime; } public void toggle() { if (isSurfaceCreated) { if (handler == null) start(); else if (handler.isStop()) { resume(); } else pause(); } } public void pause() { if (handler != null) handler.quit(); } public void resume() { if (handler != null && mDrawThread != null && handler.isPrepared()) handler.sendEmptyMessage(DrawHandler.RESUME); else { restart(); } } public void restart() { stop(); start(); } public void start() { start(0); } public void start(long postion) { if (handler == null) { prepare(); } handler.obtainMessage(DrawHandler.START, postion).sendToTarget(); } @Override public void onClick(View view) { if (mOnClickListener != null) { mOnClickListener.onClick(view); } } public void seekTo(Long ms) { seekBy(ms - timer.currMillisecond); } public void seekBy(Long deltaMs) { if (handler != null) { handler.obtainMessage(DrawHandler.SEEK_POS, deltaMs).sendToTarget(); } } public void enableDanmakuDrawingCache(boolean enable) { mEnableDanmakuDrwaingCache = enable; } private IDrawTask createTask(boolean useDrwaingCache, DanmakuTimer timer, Context context, int width, int height, IDrawTask.TaskListener taskListener) { IDrawTask task = useDrwaingCache ? new CacheManagingDrawTask(timer, context, width, height, taskListener, 1024 * 1024 * getMemoryClass(getContext()) / 3) : new DrawTask(timer, context, width, height, taskListener); task.setParser(mParser); task.prepare(); return task; } public static int getMemoryClass(final Context context) { return ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)) .getMemoryClass(); } public interface Callback { public void prepared(); public void updateTimer(DanmakuTimer timer); } public class DrawHandler extends Handler { private static final int START = 1; private static final int UPDATE = 2; private static final int RESUME = 3; private static final int SEEK_POS = 4; private static final int PREPARE = 5; private long pausedPostion = 0; private boolean quitFlag = true; private boolean mReady; public DrawHandler(Looper looper) { super(looper); } public void quit() { quitFlag = true; pausedPostion = timer.currMillisecond; removeCallbacksAndMessages(null); } public boolean isStop() { return quitFlag; } @Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case PREPARE: if(mParser==null || !isSurfaceCreated){ sendEmptyMessageDelayed(PREPARE,100); }else{ prepare(new Runnable() { @Override public void run() { mReady = true; if (mCallback != null) { mCallback.prepared(); } } }); } break; case START: removeCallbacksAndMessages(null); Long startTime = (Long) msg.obj; if(startTime!=null){ pausedPostion = startTime.longValue(); }else{ pausedPostion = 0; } case RESUME: quitFlag = false; if (mReady) { mTimeBase = System.currentTimeMillis() - pausedPostion; timer.update(pausedPostion); removeMessages(RESUME); sendEmptyMessage(UPDATE); drawTask.start(); } else { sendEmptyMessageDelayed(RESUME, 100); } break; case SEEK_POS: removeMessages(UPDATE); Long deltaMs = (Long) msg.obj; mTimeBase -= deltaMs; timer.update(System.currentTimeMillis() - mTimeBase); - drawTask.seek(timer.currMillisecond); + if (drawTask != null) + drawTask.seek(timer.currMillisecond); pausedPostion = timer.currMillisecond; sendEmptyMessage(RESUME); break; case UPDATE: if (quitFlag) { break; } long startMS = System.currentTimeMillis(); long d = timer.update(startMS - mTimeBase); if (mCallback != null) { mCallback.updateTimer(timer); } if(d<=0){ removeMessages(UPDATE); sendEmptyMessageDelayed(UPDATE, 60 - d); break; } d = drawDanmakus(); removeMessages(UPDATE); if (d < 15) { sendEmptyMessageDelayed(UPDATE, 15 - d); break; } sendEmptyMessage(UPDATE); break; } } private void prepare(final Runnable runnable) { if (drawTask == null) { drawTask = createTask(mEnableDanmakuDrwaingCache, timer, getContext(), getWidth(), getHeight(), new IDrawTask.TaskListener() { @Override public void ready() { Log.i(TAG, "start drawing multiThread enabled:" + mEnableDanmakuDrwaingCache); runnable.run(); } }); } else { runnable.run(); } } public boolean isPrepared(){ return mReady; } } }
true
true
public void handleMessage(Message msg) { int what = msg.what; switch (what) { case PREPARE: if(mParser==null || !isSurfaceCreated){ sendEmptyMessageDelayed(PREPARE,100); }else{ prepare(new Runnable() { @Override public void run() { mReady = true; if (mCallback != null) { mCallback.prepared(); } } }); } break; case START: removeCallbacksAndMessages(null); Long startTime = (Long) msg.obj; if(startTime!=null){ pausedPostion = startTime.longValue(); }else{ pausedPostion = 0; } case RESUME: quitFlag = false; if (mReady) { mTimeBase = System.currentTimeMillis() - pausedPostion; timer.update(pausedPostion); removeMessages(RESUME); sendEmptyMessage(UPDATE); drawTask.start(); } else { sendEmptyMessageDelayed(RESUME, 100); } break; case SEEK_POS: removeMessages(UPDATE); Long deltaMs = (Long) msg.obj; mTimeBase -= deltaMs; timer.update(System.currentTimeMillis() - mTimeBase); drawTask.seek(timer.currMillisecond); pausedPostion = timer.currMillisecond; sendEmptyMessage(RESUME); break; case UPDATE: if (quitFlag) { break; } long startMS = System.currentTimeMillis(); long d = timer.update(startMS - mTimeBase); if (mCallback != null) { mCallback.updateTimer(timer); } if(d<=0){ removeMessages(UPDATE); sendEmptyMessageDelayed(UPDATE, 60 - d); break; } d = drawDanmakus(); removeMessages(UPDATE); if (d < 15) { sendEmptyMessageDelayed(UPDATE, 15 - d); break; } sendEmptyMessage(UPDATE); break; } }
public void handleMessage(Message msg) { int what = msg.what; switch (what) { case PREPARE: if(mParser==null || !isSurfaceCreated){ sendEmptyMessageDelayed(PREPARE,100); }else{ prepare(new Runnable() { @Override public void run() { mReady = true; if (mCallback != null) { mCallback.prepared(); } } }); } break; case START: removeCallbacksAndMessages(null); Long startTime = (Long) msg.obj; if(startTime!=null){ pausedPostion = startTime.longValue(); }else{ pausedPostion = 0; } case RESUME: quitFlag = false; if (mReady) { mTimeBase = System.currentTimeMillis() - pausedPostion; timer.update(pausedPostion); removeMessages(RESUME); sendEmptyMessage(UPDATE); drawTask.start(); } else { sendEmptyMessageDelayed(RESUME, 100); } break; case SEEK_POS: removeMessages(UPDATE); Long deltaMs = (Long) msg.obj; mTimeBase -= deltaMs; timer.update(System.currentTimeMillis() - mTimeBase); if (drawTask != null) drawTask.seek(timer.currMillisecond); pausedPostion = timer.currMillisecond; sendEmptyMessage(RESUME); break; case UPDATE: if (quitFlag) { break; } long startMS = System.currentTimeMillis(); long d = timer.update(startMS - mTimeBase); if (mCallback != null) { mCallback.updateTimer(timer); } if(d<=0){ removeMessages(UPDATE); sendEmptyMessageDelayed(UPDATE, 60 - d); break; } d = drawDanmakus(); removeMessages(UPDATE); if (d < 15) { sendEmptyMessageDelayed(UPDATE, 15 - d); break; } sendEmptyMessage(UPDATE); break; } }
diff --git a/HomeProtector9000/src/controller/HomeProtectorFrame.java b/HomeProtector9000/src/controller/HomeProtectorFrame.java index b24353a..5977704 100644 --- a/HomeProtector9000/src/controller/HomeProtectorFrame.java +++ b/HomeProtector9000/src/controller/HomeProtectorFrame.java @@ -1,358 +1,358 @@ package controller; import java.awt.Component; import java.awt.Font; import java.awt.Point; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JLabel; import ai.AiState; import ai.BotAiStateManager; import java.util.Random; import model.*; import view.*; @SuppressWarnings("serial") public class HomeProtectorFrame extends JFrame implements ActionsPanelDelegate, StageBasedLoopDelegate { private final int defaultWorldWidth = 10; private final int defaultWorldHeight = 10; private final double randomActionProbability = .1; public World worldModel; public WorldPanel worldPanel; public BotAiStateManager aiManager; public JLabel stateLabel; public JLabel stateValue; public JLabel inventoryLabel; public JLabel inventoryValue; public JLabel energyLabel; public EnergyLevelPanel energyValue; public JLabel actionsLabel; public ActionsPanel actionsPanel; private boolean runWorld = false; private boolean randomActionsEnabled = false; private StageBasedLoop loopController; public int preferredWidth() { return 900; } public int preferredHeight() { return 600; } private ArrayList<Model> defaultObjects() { ArrayList<Model> ret = new ArrayList<Model>(); //protector bot ProtectorBot bot = new ProtectorBot(9, 5); ret.add(bot); this.worldModel.setBot(bot); //add base station BaseStation baseStation = new BaseStation(0, 5); baseStation.setHasExtinguisher(true); ret.add(baseStation); this.worldModel.setStation(baseStation); ArrayList<Point> openPoints = openPoints(); Random generator = new Random(); //add dirt for(int i = 0; i < 10 && !openPoints.isEmpty(); i++) { int r = Math.abs(generator.nextInt()) % openPoints.size(); Point p = openPoints.get(r); Dirt d = new Dirt(p.x, p.y); ret.add(d); openPoints.remove(r); } //add obstructions for(int i = 0; i < 20 && !openPoints.isEmpty(); i++) { int r = Math.abs(generator.nextInt()) % openPoints.size(); Point p = openPoints.get(r); Obstruction o = new Obstruction(p.x, p.y); ret.add(o); openPoints.remove(r); } return ret; } public HomeProtectorFrame(String title) { super(title); this.setLayout(null); worldModel = new World(defaultWorldWidth, defaultWorldHeight); worldPanel = new WorldPanel(worldModel); worldPanel.setBounds(15, 15, 540, 540); this.add(worldPanel); ArrayList<Model> startingObjects = defaultObjects(); for(Model m : startingObjects) { worldModel.addObject(m); } aiManager = new BotAiStateManager(worldModel, worldModel.getBot()); Font font = new Font(null, Font.BOLD, 20); stateLabel = new JLabel("AI State:", (int)Component.CENTER_ALIGNMENT); stateLabel.setBounds(600, 25, 250, 34); stateLabel.setFont(new Font(null, Font.BOLD, 30)); this.add(stateLabel); stateValue = new JLabel("Idle", (int)Component.CENTER_ALIGNMENT); stateValue.setBounds(600, 65, 250, 30); stateValue.setFont(new Font(null, Font.BOLD, 16)); this.add(stateValue); energyLabel = new JLabel("Power:", (int)Component.CENTER_ALIGNMENT); - energyLabel.setBounds(585, 130, 100, 40); + energyLabel.setBounds(585, 110, 100, 40); energyLabel.setFont(font); this.add(energyLabel); energyValue = new EnergyLevelPanel(worldModel.getBot()); - energyValue.setBounds(585, 170, 100, 40); + energyValue.setBounds(585, 150, 100, 40); this.add(energyValue); inventoryLabel = new JLabel("Extinguisher:", (int)Component.CENTER_ALIGNMENT); - inventoryLabel.setBounds(720, 130, 150, 40); + inventoryLabel.setBounds(720, 110, 150, 40); inventoryLabel.setFont(font); this.add(inventoryLabel); inventoryValue = new JLabel("Unequipped", (int)Component.CENTER_ALIGNMENT); - inventoryValue.setBounds(720, 170, 150, 30); + inventoryValue.setBounds(720, 150, 150, 30); inventoryValue.setFont(font); this.add(inventoryValue); - actionsLabel = new JLabel("Actions:", (int)Component.CENTER_ALIGNMENT); + actionsLabel = new JLabel("User Actions:", (int)Component.CENTER_ALIGNMENT); actionsLabel.setBounds(600, 250, 250, 40); - actionsLabel.setFont(font); + actionsLabel.setFont(new Font(null, Font.BOLD, 30)); this.add(actionsLabel); actionsPanel = new ActionsPanel(); actionsPanel.setBounds(600, 300, 250, 250); actionsPanel.setDelegate(this); this.add(actionsPanel); loopController = new StageBasedLoop(this); } private void updateDisplay() { ProtectorBot b = this.worldModel.getBot(); AiState state = this.worldModel.getBot().getAiState(); if(state != null) { this.stateValue.setText(state.prettyName()); } else { this.stateValue.setText("Idle"); } if(b.hasExtinguisher()) { this.inventoryValue.setText("Equipped"); } else { this.inventoryValue.setText("Unequipped"); } this.energyValue.repaint(); this.worldPanel.repaint(); } private ArrayList<Point> openPoints() { ArrayList<Point> openPoints = new ArrayList<Point>(); for(int r = 0; r < this.worldModel.getHeight(); r++) { for(int c = 0; c < this.worldModel.getWidth(); c++) { Point point = new Point(c, r); if(this.worldModel.objectAtPosition(point) == null) { openPoints.add(point); } } } return openPoints; } private Point getRandomOpenSpace() { ArrayList<Point> openPoints = openPoints(); if(openPoints.size() > 0) { Random generator = new Random(); return openPoints.get(Math.abs(generator.nextInt()) % openPoints.size()); } return null; } //StageBasedLoopDelegate methods public void stage1() { if(randomActionsEnabled) { Random generator = new Random(); int r = Math.abs(generator.nextInt()) % 100; double p = randomActionProbability * 100; if(p > r) { Point openPoint = this.getRandomOpenSpace(); if(openPoint != null) { if(Math.abs(generator.nextInt()) % 5 == 0) { System.out.println("Adding Fire"); Fire fire = new Fire(openPoint.x, openPoint.y); worldModel.addObject(fire); } else { System.out.println("Adding Dirt"); Dirt dirt = new Dirt(openPoint.x, openPoint.y); worldModel.addObject(dirt); } this.updateDisplay(); } } } } public void stage2() { aiManager.updateBotAiState(); updateDisplay(); } public void stage3() { ProtectorBot bot = this.worldModel.getBot(); Action action = bot.getAiState().action(); this.worldModel.executeAction(action); updateDisplay(); } public boolean keepLooping() { return true; } //ActionsPanelDelegate methods public void addDirt() { Point openPoint = this.getRandomOpenSpace(); if(openPoint != null) { Dirt dirt = new Dirt(openPoint.x, openPoint.y); worldModel.addObject(dirt); this.updateDisplay(); } if(runWorld) loopController.restart(); } public void addFire() { Point openPoint = this.getRandomOpenSpace(); if(openPoint != null) { Fire fire = new Fire(openPoint.x, openPoint.y); worldModel.addObject(fire); this.updateDisplay(); } if(runWorld) loopController.restart(); } public void removeAllDirt() { for(int r = 0; r < this.worldModel.getHeight(); r++) { for(int c = 0; c < this.worldModel.getWidth(); c++) { Point point = new Point(c, r); Model m = this.worldModel.objectAtPosition(point); if(m != null && m instanceof Dirt) { Model stackedObject = ((GroundObject)m).getStackedObject(); this.worldModel.removeObjectAtPosition(point); if(stackedObject != null) { this.worldModel.addObject(stackedObject); } } } } this.updateDisplay(); if(runWorld) loopController.restart(); } public void removeAllFire() { for(int r = 0; r < this.worldModel.getHeight(); r++) { for(int c = 0; c < this.worldModel.getWidth(); c++) { Point point = new Point(c, r); Model m = this.worldModel.objectAtPosition(point); if(m != null && m instanceof Fire) { this.worldModel.removeObjectAtPosition(point); } } } this.updateDisplay(); if(runWorld) loopController.restart(); } public void aquireExtinguisher() { this.worldModel.getBot().pickupFireExtinguisher(); this.worldModel.getStation().setHasExtinguisher(false); this.updateDisplay(); } public void replaceExtinguisher() { this.worldModel.getBot().dropFireExtinguisher(); this.worldModel.getStation().setHasExtinguisher(true); this.updateDisplay(); } public void fillEnergey() { this.worldModel.getBot().chargeBattery(); this.updateDisplay(); } public void depleteEnergy() { this.worldModel.getBot().drainBattery(); this.updateDisplay(); } public void enableRandomActions() { randomActionsEnabled = true; } public void disableRandomActions() { randomActionsEnabled = false; } public void start() { runWorld = true; loopController.run(); } public void stop() { runWorld = false; loopController.stop(); } @Override public void addObstruction() { Point openPoint = this.getRandomOpenSpace(); if(openPoint != null) { Obstruction o = new Obstruction(openPoint.x, openPoint.y); worldModel.addObject(o); this.updateDisplay(); } if(runWorld) loopController.restart(); } @Override public void removeAllObstructions() { for(int r = 0; r < this.worldModel.getHeight(); r++) { for(int c = 0; c < this.worldModel.getWidth(); c++) { Point point = new Point(c, r); Model m = this.worldModel.objectAtPosition(point); if(m != null && m instanceof Obstruction) { this.worldModel.removeObjectAtPosition(point); } } } this.updateDisplay(); if(runWorld) loopController.restart(); } }
false
true
public HomeProtectorFrame(String title) { super(title); this.setLayout(null); worldModel = new World(defaultWorldWidth, defaultWorldHeight); worldPanel = new WorldPanel(worldModel); worldPanel.setBounds(15, 15, 540, 540); this.add(worldPanel); ArrayList<Model> startingObjects = defaultObjects(); for(Model m : startingObjects) { worldModel.addObject(m); } aiManager = new BotAiStateManager(worldModel, worldModel.getBot()); Font font = new Font(null, Font.BOLD, 20); stateLabel = new JLabel("AI State:", (int)Component.CENTER_ALIGNMENT); stateLabel.setBounds(600, 25, 250, 34); stateLabel.setFont(new Font(null, Font.BOLD, 30)); this.add(stateLabel); stateValue = new JLabel("Idle", (int)Component.CENTER_ALIGNMENT); stateValue.setBounds(600, 65, 250, 30); stateValue.setFont(new Font(null, Font.BOLD, 16)); this.add(stateValue); energyLabel = new JLabel("Power:", (int)Component.CENTER_ALIGNMENT); energyLabel.setBounds(585, 130, 100, 40); energyLabel.setFont(font); this.add(energyLabel); energyValue = new EnergyLevelPanel(worldModel.getBot()); energyValue.setBounds(585, 170, 100, 40); this.add(energyValue); inventoryLabel = new JLabel("Extinguisher:", (int)Component.CENTER_ALIGNMENT); inventoryLabel.setBounds(720, 130, 150, 40); inventoryLabel.setFont(font); this.add(inventoryLabel); inventoryValue = new JLabel("Unequipped", (int)Component.CENTER_ALIGNMENT); inventoryValue.setBounds(720, 170, 150, 30); inventoryValue.setFont(font); this.add(inventoryValue); actionsLabel = new JLabel("Actions:", (int)Component.CENTER_ALIGNMENT); actionsLabel.setBounds(600, 250, 250, 40); actionsLabel.setFont(font); this.add(actionsLabel); actionsPanel = new ActionsPanel(); actionsPanel.setBounds(600, 300, 250, 250); actionsPanel.setDelegate(this); this.add(actionsPanel); loopController = new StageBasedLoop(this); }
public HomeProtectorFrame(String title) { super(title); this.setLayout(null); worldModel = new World(defaultWorldWidth, defaultWorldHeight); worldPanel = new WorldPanel(worldModel); worldPanel.setBounds(15, 15, 540, 540); this.add(worldPanel); ArrayList<Model> startingObjects = defaultObjects(); for(Model m : startingObjects) { worldModel.addObject(m); } aiManager = new BotAiStateManager(worldModel, worldModel.getBot()); Font font = new Font(null, Font.BOLD, 20); stateLabel = new JLabel("AI State:", (int)Component.CENTER_ALIGNMENT); stateLabel.setBounds(600, 25, 250, 34); stateLabel.setFont(new Font(null, Font.BOLD, 30)); this.add(stateLabel); stateValue = new JLabel("Idle", (int)Component.CENTER_ALIGNMENT); stateValue.setBounds(600, 65, 250, 30); stateValue.setFont(new Font(null, Font.BOLD, 16)); this.add(stateValue); energyLabel = new JLabel("Power:", (int)Component.CENTER_ALIGNMENT); energyLabel.setBounds(585, 110, 100, 40); energyLabel.setFont(font); this.add(energyLabel); energyValue = new EnergyLevelPanel(worldModel.getBot()); energyValue.setBounds(585, 150, 100, 40); this.add(energyValue); inventoryLabel = new JLabel("Extinguisher:", (int)Component.CENTER_ALIGNMENT); inventoryLabel.setBounds(720, 110, 150, 40); inventoryLabel.setFont(font); this.add(inventoryLabel); inventoryValue = new JLabel("Unequipped", (int)Component.CENTER_ALIGNMENT); inventoryValue.setBounds(720, 150, 150, 30); inventoryValue.setFont(font); this.add(inventoryValue); actionsLabel = new JLabel("User Actions:", (int)Component.CENTER_ALIGNMENT); actionsLabel.setBounds(600, 250, 250, 40); actionsLabel.setFont(new Font(null, Font.BOLD, 30)); this.add(actionsLabel); actionsPanel = new ActionsPanel(); actionsPanel.setBounds(600, 300, 250, 250); actionsPanel.setDelegate(this); this.add(actionsPanel); loopController = new StageBasedLoop(this); }
diff --git a/android/ShareBox/src/de/tubs/ibr/dtn/sharebox/TarExtractor.java b/android/ShareBox/src/de/tubs/ibr/dtn/sharebox/TarExtractor.java index 072275e8..f78e84c7 100644 --- a/android/ShareBox/src/de/tubs/ibr/dtn/sharebox/TarExtractor.java +++ b/android/ShareBox/src/de/tubs/ibr/dtn/sharebox/TarExtractor.java @@ -1,115 +1,115 @@ package de.tubs.ibr.dtn.sharebox; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.LinkedList; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.utils.IOUtils; import android.util.Log; public class TarExtractor implements Runnable { private static final String TAG = "TarExtractor"; private InputStream mInput = null; private File mTargetDir = null; private LinkedList<File> mExtractedFiles = null; private OnStateChangeListener mListener = null; public interface OnStateChangeListener { void onStateChanged(TarExtractor extractor, int state); } public TarExtractor(InputStream is, File targetDir) { mInput = is; mTargetDir = targetDir; } @Override public void run() { mExtractedFiles = new LinkedList<File>(); if (mListener != null) mListener.onStateChanged(this, 0); try { final TarArchiveInputStream tais = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", mInput); TarArchiveEntry entry = null; while ((entry = (TarArchiveEntry)tais.getNextEntry()) != null) { File outputFile = new File(mTargetDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { // check if the full path exists File parent = outputFile.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", parent.getAbsolutePath())); } } // rename if the file already exists if (outputFile.exists()) { String full_path = outputFile.getAbsolutePath(); int ext_delimiter = full_path.lastIndexOf('.'); int i = 1; - File newfile = new File(full_path.substring(0, ext_delimiter) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); + File newfile = new File(full_path.substring(0, ext_delimiter - 1) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); while (newfile.exists()) { i++; - newfile = new File(full_path.substring(0, ext_delimiter) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); + newfile = new File(full_path.substring(0, ext_delimiter - 1) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); } outputFile = newfile; } final OutputStream ofs = new FileOutputStream(outputFile.getAbsolutePath()); IOUtils.copy(tais, ofs); ofs.close(); } mExtractedFiles.add(outputFile); } tais.close(); if (mListener != null) mListener.onStateChanged(this, 1); } catch (ArchiveException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IOException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IllegalStateException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IllegalArgumentException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } } public LinkedList<File> getFiles() { return mExtractedFiles; } public OnStateChangeListener getOnStateChangeListener() { return mListener; } public void setOnStateChangeListener(OnStateChangeListener listener) { mListener = listener; } }
false
true
public void run() { mExtractedFiles = new LinkedList<File>(); if (mListener != null) mListener.onStateChanged(this, 0); try { final TarArchiveInputStream tais = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", mInput); TarArchiveEntry entry = null; while ((entry = (TarArchiveEntry)tais.getNextEntry()) != null) { File outputFile = new File(mTargetDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { // check if the full path exists File parent = outputFile.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", parent.getAbsolutePath())); } } // rename if the file already exists if (outputFile.exists()) { String full_path = outputFile.getAbsolutePath(); int ext_delimiter = full_path.lastIndexOf('.'); int i = 1; File newfile = new File(full_path.substring(0, ext_delimiter) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); while (newfile.exists()) { i++; newfile = new File(full_path.substring(0, ext_delimiter) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); } outputFile = newfile; } final OutputStream ofs = new FileOutputStream(outputFile.getAbsolutePath()); IOUtils.copy(tais, ofs); ofs.close(); } mExtractedFiles.add(outputFile); } tais.close(); if (mListener != null) mListener.onStateChanged(this, 1); } catch (ArchiveException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IOException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IllegalStateException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IllegalArgumentException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } }
public void run() { mExtractedFiles = new LinkedList<File>(); if (mListener != null) mListener.onStateChanged(this, 0); try { final TarArchiveInputStream tais = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", mInput); TarArchiveEntry entry = null; while ((entry = (TarArchiveEntry)tais.getNextEntry()) != null) { File outputFile = new File(mTargetDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { // check if the full path exists File parent = outputFile.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IllegalStateException(String.format("Couldn't create directory %s.", parent.getAbsolutePath())); } } // rename if the file already exists if (outputFile.exists()) { String full_path = outputFile.getAbsolutePath(); int ext_delimiter = full_path.lastIndexOf('.'); int i = 1; File newfile = new File(full_path.substring(0, ext_delimiter - 1) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); while (newfile.exists()) { i++; newfile = new File(full_path.substring(0, ext_delimiter - 1) + "_" + String.valueOf(i) + full_path.substring(ext_delimiter)); } outputFile = newfile; } final OutputStream ofs = new FileOutputStream(outputFile.getAbsolutePath()); IOUtils.copy(tais, ofs); ofs.close(); } mExtractedFiles.add(outputFile); } tais.close(); if (mListener != null) mListener.onStateChanged(this, 1); } catch (ArchiveException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IOException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IllegalStateException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } catch (IllegalArgumentException e) { Log.e(TAG, null, e); if (mListener != null) mListener.onStateChanged(this, -1); } }
diff --git a/sikuli-ide/src/main/java/edu/mit/csail/uid/SikuliPane.java b/sikuli-ide/src/main/java/edu/mit/csail/uid/SikuliPane.java index 731463cc..61469739 100644 --- a/sikuli-ide/src/main/java/edu/mit/csail/uid/SikuliPane.java +++ b/sikuli-ide/src/main/java/edu/mit/csail/uid/SikuliPane.java @@ -1,1139 +1,1139 @@ package edu.mit.csail.uid; import java.io.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.image.*; import java.awt.event.*; import java.net.URL; import java.util.Date; import java.util.regex.Pattern; import java.util.regex.Matcher; import javax.swing.*; import javax.swing.text.*; import javax.swing.filechooser.FileFilter; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.imageio.*; import org.python.util.PythonInterpreter; import org.python.core.*; public class SikuliPane extends JTextPane implements KeyListener, CaretListener{ private String _editingFilename; private String _srcBundlePath = null; private boolean _dirty = false; private Class _historyBtnClass; private CurrentLineHighlighter _highlighter; private String _tabString = " "; public SikuliPane(){ setEditorKitForContentType("text/python", new SikuliEditorKit()); setContentType("text/python"); addKeyListener(this); _highlighter = new CurrentLineHighlighter(this); addCaretListener(_highlighter); addCaretListener(this); setFont(new Font("Osaka-Mono", Font.PLAIN, 18)); setMargin( new Insets( 3, 3, 3, 3 ) ); setTabs(3); setBackground(Color.WHITE); } public void setTabs(int spaceForTab) { String t = ""; for(int i=0;i<spaceForTab;i++) t += " "; _tabString = t; } public int getLineAtCaret(int caretPosition) { Element root = getDocument().getDefaultRootElement(); return root.getElementIndex( caretPosition ) + 1; } public int getLineAtCaret() { int caretPosition = getCaretPosition(); Element root = getDocument().getDefaultRootElement(); return root.getElementIndex( caretPosition ) + 1; } public int getColumnAtCaret() { int offset = getCaretPosition(); int column; try { column = offset - Utilities.getRowStart(this, offset); } catch (BadLocationException e) { column = -1; } return column+1; } public String getSrcBundle(){ if( _srcBundlePath == null ){ File tmp = Utils.createTempDir(); _srcBundlePath = Utils.slashify(tmp.getAbsolutePath(),true); } return _srcBundlePath; } public void setErrorHighlight(int lineNo){ _highlighter.setErrorLine(lineNo); try{ if(lineNo>0) jumpTo(lineNo); } catch(Exception e){ e.printStackTrace(); } repaint(); } public void setHistoryCaptureButton(CaptureButton btn){ _historyBtnClass = btn.getClass(); } public boolean close() throws IOException{ if( _dirty ){ Object[] options = {"Yes", "No", "Cancel"}; int ans = JOptionPane.showOptionDialog(this, getCurrentShortFilename() + " has been modified. Save changes?", "Do you want to close this tab?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if( ans == JOptionPane.CANCEL_OPTION || ans == JOptionPane.CLOSED_OPTION ) return false; else if( ans == JOptionPane.YES_OPTION ) saveFile(); } return true; } public String getCurrentShortFilename(){ if(_srcBundlePath != null){ File f = new File(_srcBundlePath); return f.getName(); } return "Untitled"; } public String getCurrentFilename(){ if(_editingFilename==null){ try{ saveAsFile(); return _editingFilename; } catch(IOException e){ e.printStackTrace(); } } return _editingFilename; } static InputStream SikuliToHtmlConverter = SikuliIDE.class.getResourceAsStream("/scripts/sikuli2html.py"); static String pyConverter = Utils.convertStreamToString(SikuliToHtmlConverter); private void convertSrcToHtml(String bundle){ PythonInterpreter py = new PythonInterpreter(); Debug.log(1, "Convert Sikuli source code " + bundle + " to HTML"); py.set("local_convert", true); py.set("sikuli_src", bundle); py.exec(pyConverter); } private void writeFile() throws IOException{ this.write(new FileWriter(_editingFilename)); convertSrcToHtml(getSrcBundle()); _dirty = false; } public String saveFile() throws IOException{ if(_editingFilename==null) return saveAsFile(); else{ writeFile(); return getCurrentShortFilename(); } } public String saveAsFile() throws IOException{ JFileChooser fcSave = new JFileChooser(); //fcSave.setCurrentDirectory(new File(System.getProperty("user.dir"))); fcSave.setAcceptAllFileFilterUsed(false); fcSave.setFileFilter(new SourceFileFilter()); fcSave.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES ); fcSave.setSelectedFile(null); if(fcSave.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) return null; File file = fcSave.getSelectedFile(); String bundlePath = file.getAbsolutePath(); if( !file.getAbsolutePath().endsWith(".sikuli") ) bundlePath += ".sikuli"; bundlePath = Utils.slashify(bundlePath, true); if(_srcBundlePath != null) Utils.xcopy( _srcBundlePath, bundlePath ); else Utils.mkdir(bundlePath); _srcBundlePath = bundlePath; _editingFilename = getSourceFilename(bundlePath); System.out.println("save to " + _editingFilename); writeFile(); return getCurrentShortFilename(); } private String getSourceFilename(String filename){ if( filename.endsWith(".sikuli") || filename.endsWith(".sikuli" + "/") ){ File f = new File(filename); String dest = f.getName(); dest = dest.replace(".sikuli", ".py"); return _srcBundlePath + dest; } return filename; } public void loadFile(String filename) throws IOException{ if( filename.endsWith("/") ) filename = filename.substring(0, filename.length()-1); _srcBundlePath = filename + "/"; _editingFilename = getSourceFilename(filename); this.read(new FileReader(_editingFilename), null); } public String loadFile() throws IOException{ JFileChooser fcLoad = new JFileChooser(); fcLoad.setCurrentDirectory(new File(System.getProperty("user.dir"))); fcLoad.setAcceptAllFileFilterUsed(false); fcLoad.setFileFilter(new SourceFileFilter()); fcLoad.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES ); fcLoad.setSelectedFile(null); if(fcLoad.showDialog(this, null) != JFileChooser.APPROVE_OPTION) return null; File file = fcLoad.getSelectedFile(); String fname = Utils.slashify(file.getAbsolutePath(),false); loadFile(fname); return fname; } @Override public void paste() { int start = getCaretPosition(); super.paste(); int end = getCaretPosition(); Debug.log(9,"paste: %d %d", start, end); try{ end = parseLine(start, end, patPatternStr); parseLine(start, end, patPngStr); } catch(BadLocationException e){ e.printStackTrace(); } _dirty = true; } int _caret_last_x = -1; boolean _can_update_caret_last_x = true; public void caretUpdate(CaretEvent evt){ if(_can_update_caret_last_x) _caret_last_x = -1; else _can_update_caret_last_x = true; } // see: getMagicCaretPosition, getNextVisualPositionFrom // FIXME: dirty hack for fixing cursor movement public void keyPressed(java.awt.event.KeyEvent ke) { boolean up = false; int pos; if(ke.getModifiers()!=0) return; switch(ke.getKeyCode()){ case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: _caret_last_x = -1; break; case KeyEvent.VK_UP: up = true; case KeyEvent.VK_DOWN: int line = getLineAtCaret(); int tarLine = up? line-1 : line+1; try{ if(tarLine<=0){ jumpTo(1,1); return; } if(tarLine>getNumLines()){ setCaretPosition(getDocument().getLength()-1); return; } Rectangle curRect = modelToView(getCaretPosition()); Rectangle tarEndRect; if(tarLine < getNumLines()) tarEndRect = modelToView(getLineStartOffset(tarLine)-1); else tarEndRect = modelToView(getDocument().getLength()-1); Debug.log(7, "curRect: " + curRect + ", tarEnd: " + tarEndRect); if(_caret_last_x == -1) _caret_last_x = curRect.x; if( _caret_last_x > tarEndRect.x ){ pos = viewToModel(new Point(tarEndRect.x, tarEndRect.y)); _can_update_caret_last_x = false; } else{ pos = viewToModel(new Point(_caret_last_x, tarEndRect.y)); if(up && getLineAtCaret(pos)==getLineAtCaret(pos+1) /*&& _caret_last_x == curRect.x*/) pos++; } setCaretPosition(pos); } catch(BadLocationException e){ e.printStackTrace(); } ke.consume(); break; } } public void keyReleased(java.awt.event.KeyEvent ke) { /* final int S_MOD = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); if( ke.getModifiers()==S_MOD ) { if (ke.getKeyCode()==KeyEvent.VK_X){ this.cut(); } else if (ke.getKeyCode()==KeyEvent.VK_C) { this.copy(); } else if (ke.getKeyCode()==KeyEvent.VK_V) { this.paste(); } } */ } private void expandTab() throws BadLocationException{ int pos = getCaretPosition(); Document doc = getDocument(); doc.remove(pos-1, 1); doc.insertString(pos-1, _tabString, null); } public void keyTyped(java.awt.event.KeyEvent ke) { _dirty = true; try{ if(ke.getKeyChar() == '\t') expandTab(); checkCompletion(ke); } catch(BadLocationException e){ e.printStackTrace(); } } @Override public void read(Reader in, Object desc) throws IOException{ super.read(in, desc); Document doc = getDocument(); Element root = doc.getDefaultRootElement(); parse(root); setCaretPosition(0); } public void jumpTo(int lineNo, int column) throws BadLocationException{ Debug.log(6, "jumpTo: " + lineNo+","+column); int off = getLineStartOffset(lineNo-1)+column-1; int nextLine = getLineStartOffset(lineNo); if( off >= nextLine ) off = nextLine-1; if(off < 0) off = 0; setCaretPosition( off ); } public void jumpTo(int lineNo) throws BadLocationException{ Debug.log(6,"jumpTo: " + lineNo); setCaretPosition( getLineStartOffset(lineNo-1) ); } public void jumpTo(String funcName) throws BadLocationException{ Debug.log(6, "jumpTo: " + funcName); Element root = getDocument().getDefaultRootElement(); int pos = getFunctionStartOffset(funcName, root); if(pos>=0) setCaretPosition(pos); else throw new BadLocationException("Can't find function " + funcName,-1); } private int getFunctionStartOffset(String func, Element node) throws BadLocationException{ Document doc = getDocument(); int count = node.getElementCount(); Pattern patDef = Pattern.compile("def\\s+"+func+"\\s*\\("); for(int i=0;i<count;i++){ Element elm = node.getElement(i); if( elm.isLeaf() ){ int start = elm.getStartOffset(), end = elm.getEndOffset(); String line = doc.getText(start, end-start); Matcher matcher = patDef.matcher(line); if(matcher.find()) return start; } else{ int p = getFunctionStartOffset(func, elm); if(p>=0) return p; } } return -1; } public int getNumLines(){ Document doc = getDocument(); Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(doc.getLength()-1); return lineIdx+1; } public void indent(int startLine, int endLine, int level){ Document doc = getDocument(); String strIndent = ""; if(level>0){ for(int i=0;i<level;i++) strIndent += " "; } else{ System.err.println("negative indentation not supported yet!!"); } for(int i=startLine;i<endLine;i++){ try{ int off = getLineStartOffset(i); if(level>0) doc.insertString(off, strIndent, null); } catch(Exception e){ e.printStackTrace(); } } } // line starting from 0 private int getLineStartOffset(int line) throws BadLocationException { Element map = getDocument().getDefaultRootElement(); if (line < 0) { throw new BadLocationException("Negative line", -1); } else if (line >= map.getElementCount()) { throw new BadLocationException("No such line", getDocument().getLength()+1); } else { Element lineElem = map.getElement(line); return lineElem.getStartOffset(); } } void parse(Element node){ int count = node.getElementCount(); for(int i=0;i<count;i++){ Element elm = node.getElement(i); Debug.log(8, elm.toString() ); if( elm.isLeaf() ){ int start = elm.getStartOffset(), end = elm.getEndOffset(); try{ end = parseLine(start, end, patPatternStr); end = parseLine(start, end, patSubregionStr); parseLine(start, end, patPngStr); } catch(BadLocationException e){ e.printStackTrace(); } } else parse(elm); } } static Pattern patPngStr = Pattern.compile("(\".+?\\.png\")"); static Pattern patHistoryBtnStr = Pattern.compile("(\"\\[SIKULI-(CAPTURE|DIFF)\\]\")"); static Pattern patPatternStr = Pattern.compile( "\\b(Pattern\\s*\\(\".*?\"\\)(\\.\\w+\\([^)]*\\))*)"); static Pattern patSubregionStr = Pattern.compile( "\\b(Subregion\\s*\\(.*?\\))"); int parseLine(int startOff, int endOff, Pattern ptn) throws BadLocationException{ //System.out.println(startOff + " " + endOff); Document doc = getDocument(); while(true){ String line = doc.getText(startOff, endOff-startOff); Matcher m = ptn.matcher(line); //System.out.println("["+line+"]"); if( m.find() ){ int len = m.end() - m.start(); if(replaceWithImage(startOff+m.start(), startOff+m.end())){ startOff += m.start()+1; endOff -= len-1; } else startOff += m.end()+1; } else break; } return endOff; } public File getFileInBundle(String filename){ File f = new File(filename); String bundlePath = getSrcBundle(); if(f.exists()){ try{ Utils.xcopy(filename, bundlePath); filename = f.getName(); } catch(IOException e){ e.printStackTrace(); return f; } } filename = bundlePath + "/" + filename; f = new File(filename); if(f.exists()) return f; return null; } boolean replaceWithImage(int startOff, int endOff) throws BadLocationException{ Document doc = getDocument(); String imgStr = doc.getText(startOff, endOff - startOff); String filename = imgStr.substring(1,endOff-startOff-1);; boolean useParameters = false; boolean exact = false; int numMatches = -1; float similarity = -1f; //Debug.log("imgStr: " + imgStr); //Debug.log("filename " + filename); if( imgStr.startsWith("Pattern") ){ useParameters = true; String[] tokens = imgStr.split("\\)\\s*\\.?"); for(String str : tokens){ //System.out.println("token: " + str); if( str.startsWith("exact") ) exact = true; if( str.startsWith("Pattern") ) filename = str.substring( str.indexOf("\"")+1,str.lastIndexOf("\"")); if( str.startsWith("similar") ){ String strArg = str.substring(str.lastIndexOf("(")+1); similarity = Float.valueOf(strArg); } if( str.startsWith("firstN") ){ String strArg = str.substring(str.lastIndexOf("(")+1); numMatches = Integer.valueOf(strArg); } } } else if( imgStr.startsWith("Subregion") ){ String[] tokens = imgStr.split("[(),]"); int x = Integer.valueOf(tokens[1]), y = Integer.valueOf(tokens[2]), w = Integer.valueOf(tokens[3]), h = Integer.valueOf(tokens[4]); this.select(startOff, endOff); RegionButton icon = new RegionButton(this, x, y, w, h); this.insertComponent(icon); return true; } else if( patHistoryBtnStr.matcher(imgStr).matches() ){ Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(startOff); Element line = root.getElement(lineIdx); try{ CaptureButton btnCapture = (CaptureButton)_historyBtnClass.newInstance(); if( imgStr.indexOf("DIFF") >= 0 ) btnCapture.setDiffMode(true); btnCapture.setSrcElement(line); btnCapture.setParentPane(this); //System.out.println("new btn: " + btnCapture.getSrcElement()); this.select(startOff, endOff); if( btnCapture.hasNext() ){ int pos = startOff; doc.insertString(pos++, "[", null); this.insertComponent(btnCapture); pos++; while(btnCapture.hasNext()){ CaptureButton btn = btnCapture.getNextDiffButton(); doc.insertString(pos++, ",", null); this.insertComponent(btn); pos++; } doc.insertString(pos, "]", null); } else this.insertComponent(btnCapture); } catch(Exception e){ e.printStackTrace(); } return true; } File f = getFileInBundle(filename); Debug.log(7,"replaceWithImage: " + filename); - if( f.exists() ){ + if( f != null && f.exists() ){ this.select(startOff, endOff); ImageButton icon = new ImageButton(this, f.getAbsolutePath()); if(useParameters) icon.setParameters(exact, similarity, numMatches); this.insertComponent(icon); return true; } return false; } void checkCompletion(java.awt.event.KeyEvent ke) throws BadLocationException{ Document doc = getDocument(); Element root = doc.getDefaultRootElement(); int pos = getCaretPosition(); int lineIdx = root.getElementIndex(pos); Element line = root.getElement(lineIdx); int start = line.getStartOffset(), len = line.getEndOffset() - start; String strLine = doc.getText(start, len-1); Debug.log(9,"["+strLine+"]"); if( strLine.endsWith("find") && ke.getKeyChar()=='(' ){ ke.consume(); doc.insertString( pos, "(", null); CaptureButton btnCapture = new CaptureButton(this, line); insertComponent(btnCapture); doc.insertString( pos+2, ")", null); } } void appendString(String str){ Document doc = getDocument(); try{ int start = doc.getLength(); doc.insertString( doc.getLength(), str, null ); int end = doc.getLength(); end = parseLine(start, end, patHistoryBtnStr); } catch(Exception e){ e.printStackTrace(); } } } class CaptureButton extends JButton implements ActionListener, Cloneable{ protected Element _line; protected SikuliPane _codePane; /* public String toString(){ return " \"CAPTURE-BUTTON\" "; } */ public CaptureButton(){ super(); URL imageURL = SikuliIDE.class.getResource("/icons/capture.png"); setIcon(new ImageIcon(imageURL)); setToolTipText("Take a screenshot"); setBorderPainted(false); setMaximumSize(new Dimension(26,26)); addActionListener(this); _line = null; } public CaptureButton(SikuliPane codePane, Element elmLine){ this(); _line = elmLine; _codePane = codePane; setBorderPainted(true); setCursor(new Cursor (Cursor.HAND_CURSOR)); } public boolean hasNext(){ return false; } public CaptureButton getNextDiffButton(){ return null; } public void setParentPane(SikuliPane parent){ _codePane = parent; } public void setDiffMode(boolean flag){} public void setSrcElement(Element elmLine){ _line = elmLine; } public Element getSrcElement(){ return _line; } protected void insertAtCursor(JTextPane pane, String imgFilename){ ImageButton icon = new ImageButton(pane, imgFilename); pane.insertComponent(icon); } public void captureCompleted(String imgFullPath){ Debug.log("captureCompleted: " + imgFullPath); Element src = getSrcElement(); if( src == null ){ if(_codePane == null) insertAtCursor(SikuliIDE.getInstance().getCurrentCodePane(), imgFullPath); else insertAtCursor(_codePane, imgFullPath); return; } int start = src.getStartOffset(); int end = src.getEndOffset(); try{ StyledDocument doc = (StyledDocument)src.getDocument(); String text = doc.getText(start, end-start); Debug.log(text); for(int i=start;i<end;i++){ Element elm = doc.getCharacterElement(i); if(elm.getName().equals(StyleConstants.ComponentElementName)){ AttributeSet attr=elm.getAttributes(); Component com=StyleConstants.getComponent(attr); if( com instanceof CaptureButton ){ Debug.log("button is at " + i); int oldCaretPos = _codePane.getCaretPosition(); _codePane.select(i, i+1); ImageButton icon = new ImageButton(_codePane, imgFullPath); _codePane.insertComponent(icon); _codePane.setCaretPosition(oldCaretPos); break; } } } } catch(BadLocationException ble){ ble.printStackTrace(); } } public void capture(final int delay){ Thread t = new Thread("capture"){ public void run(){ SikuliIDE ide = SikuliIDE.getInstance(); if(delay!=0) ide.setVisible(false); try{ Thread.sleep(delay); } catch(Exception e){} new ScreenOverlay(ide.getCurrentCodePane(), CaptureButton.this); if(delay!=0) ide.setVisible(true); } }; t.start(); } public void actionPerformed(ActionEvent e) { Debug.log("capture!"); UserPreferences pref = UserPreferences.getInstance(); int delay = (int)(pref.getCaptureDelay() * 1000.0) +1; capture(delay); } } class ScreenOverlay extends JWindow{ static Rectangle fullscreenRect = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() ); static Color _overlayColor = new Color(0F,0F,0F,0.6F); static GraphicsDevice _gdev; SikuliPane _parentPane; CaptureButton _captureBtn = null; ButtonSubregion _subregionBtn = null; BufferedImage _screen = null; BufferedImage _darker_screen = null; Rectangle rectSelection; BasicStroke bs; int srcx, srcy, destx, desty; BasicStroke _StrokeCross = new BasicStroke (1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1, new float [] { 2f }, 0); private void captureScreen() throws AWTException{ Robot _robot = new Robot(); _screen = _robot.createScreenCapture(fullscreenRect); float scaleFactor = .6f; RescaleOp op = new RescaleOp(scaleFactor, 0, null); _darker_screen = op.filter(_screen, null); } private void drawSelection(Graphics2D g2d){ if (srcx != destx || srcy != desty) { int x1 = (srcx < destx) ? srcx : destx; int y1 = (srcy < desty) ? srcy : desty; int x2 = (srcx > destx) ? srcx : destx; int y2 = (srcy > desty) ? srcy : desty; rectSelection.x = x1; rectSelection.y = y1; rectSelection.width = (x2-x1)+1; rectSelection.height = (y2-y1)+1; g2d.setColor(Color.white); g2d.setStroke(bs); g2d.draw(rectSelection); int cx = (x1+x2)/2; int cy = (y1+y2)/2; g2d.setStroke(_StrokeCross); g2d.drawLine(cx, y1, cx, y2); g2d.drawLine(x1, cy, x2, cy); } } public void paint(Graphics g) { if( _screen != null ){ Graphics2D g2d = (Graphics2D)g; g2d.drawImage(_darker_screen,0,0,this); drawSelection(g2d); setVisible(true); } else setVisible(false); } void init(){ rectSelection = new Rectangle (); bs = new BasicStroke (3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float [] { 12, 12 }, 0); addMouseListener(new MouseAdapter(){ public void mousePressed(java.awt.event.MouseEvent e){ if (_screen == null) return; destx = srcx = e.getX(); desty = srcy = e.getY(); repaint(); } public void mouseReleased(java.awt.event.MouseEvent e){ if (_screen == null) return; if( e.getButton() == java.awt.event.MouseEvent.BUTTON3 ){ close(); return; } if( _captureBtn!=null){ BufferedImage cropImg = cropSelection(); String filename = Utils.saveImage(cropImg, _parentPane.getSrcBundle()); if( filename != null){ close(); String fullpath = _parentPane.getFileInBundle(filename).getAbsolutePath(); _captureBtn.captureCompleted(Utils.slashify(fullpath,false)); } } else{ int x = rectSelection.x, y = rectSelection.y; int w = rectSelection.width, h = rectSelection.height; close(); _subregionBtn.complete(x, y, w, h); } } }); //doesn't work.. (no focus?) addKeyListener(new KeyAdapter(){ public void keyReleased(java.awt.event.KeyEvent e){ System.out.println("release: " + e.getKeyCode()); if( e.getKeyCode() == java.awt.event.KeyEvent.VK_ESCAPE ){ ScreenOverlay.this.close(); } } }); addMouseMotionListener( new MouseMotionAdapter(){ public void mouseDragged(java.awt.event.MouseEvent e) { if (_screen == null) return; destx = e.getX(); desty = e.getY(); repaint(); } }); } private void close(){ _gdev.setFullScreenWindow(null); this.setVisible(false); this.dispose(); } private BufferedImage cropSelection(){ int w = rectSelection.width, h = rectSelection.height; BufferedImage crop = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D crop_g2d = crop.createGraphics(); try { crop_g2d.drawImage( _screen.getSubimage(rectSelection.x, rectSelection.y, w, h), null, 0, 0 ); } catch (RasterFormatException e) { e.printStackTrace(); } crop_g2d.dispose(); return crop; } public ScreenOverlay(SikuliPane parent, JButton btn){ _parentPane = parent; // FIXME: replace this with a common parent of capture button & subregion button if( btn instanceof CaptureButton ) _captureBtn = (CaptureButton)btn; else _subregionBtn = (ButtonSubregion)btn; init(); try{ captureScreen(); } catch(AWTException e){ e.printStackTrace(); } _gdev = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); if( _gdev.isFullScreenSupported() ){ _gdev.setFullScreenWindow(this); } else{ Debug.log("Fullscreen mode is not supported."); } setLocation(0,0); } } //FIXME: extract a suffix filter class ImageFileFilter extends FileFilter{ public boolean accept(File f) { if (f.isDirectory()) return true; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length()-1){ String ext = s.substring(i+1).toLowerCase(); if(ext.equals("png") ) return true; } return false; } public String getDescription(){ return "PNG Image files (*.png)"; } } class SourceFileFilter extends FileFilter{ public boolean accept(File f) { if (f.isDirectory()) return true; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length()-1){ String ext = s.substring(i+1).toLowerCase(); if(ext.equals("sikuli") ) return true; } return false; } public String getDescription(){ return "Sikuli source files (*.sikuli)"; } } class RegionButton extends JButton { SikuliPane _pane; int _x, _y, _w, _h; public RegionButton(SikuliPane pane, int x, int y, int w, int h){ _pane = pane; _x = x; _y = y; _w = w; _h = h; try{ String imgFilename = Utils.saveTmpImage(getRegionImage(x,y,w,h)); setIcon(new ImageIcon(imgFilename)); } catch(Exception e){ e.printStackTrace(); } setBorderPainted(true); setToolTipText( this.toString() ); } public String toString(){ return String.format("Subregion(%d,%d,%d,%d)", _x, _y, _w, _h); } static Rectangle fullscreenRect = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize() ); private BufferedImage getRegionImage(int x, int y, int w, int h) throws AWTException{ Robot _robot = new Robot(); BufferedImage _screen = _robot.createScreenCapture(fullscreenRect); int scr_w = _screen.getWidth(), scr_h = _screen.getHeight(); int max_h = 80; float scale = (float)max_h/scr_h; scr_w *= scale; scr_h *= scale; BufferedImage screen = new BufferedImage(scr_w, scr_h, BufferedImage.TYPE_INT_RGB); Graphics2D screen_g2d = screen.createGraphics(); try { screen_g2d.drawImage(_screen, 0, 0, scr_w, scr_h, null); int sx = (int)(x*scale), sy = (int)(y*scale), sw = (int)(w*scale), sh = (int)(h*scale); screen_g2d.setColor(new Color(255,0,0, 150)); screen_g2d.fillRect(sx, sy, sw, sh); } catch (RasterFormatException e) { e.printStackTrace(); } screen_g2d.dispose(); return screen; } } class ImageButton extends JButton implements ActionListener /*, MouseListener*/ { static final int DEFAULT_NUM_MATCHES = 10; static final float DEFAULT_SIMILARITY = 0.7f; private String _imgFilename, _thumbFname; private JTextPane _pane; private float _similarity; private boolean _exact; private int _numMatches; private boolean _showText; private PatternWindow pwin = null; /* public void mousePressed(java.awt.event.MouseEvent e) {} public void mouseReleased(java.awt.event.MouseEvent e) {} public void mouseClicked(java.awt.event.MouseEvent e) {} public void mouseEntered(java.awt.event.MouseEvent e) { } public void mouseExited(java.awt.event.MouseEvent e) { } */ public void setParameters(boolean exact, float similarity, int numMatches){ Debug.log("setParameters: " + exact + "," + similarity + "," + numMatches); _exact = exact; if(similarity>=0) _similarity = similarity; if(numMatches>=0) _numMatches = numMatches; setToolTipText( this.toString() ); } private String createThumbnail(String imgFname){ final int max_h = 40; Image img = new ImageIcon(imgFname).getImage(); int w = img.getWidth(null), h = img.getHeight(null); if(max_h >= h) return imgFname; float scale = (float)max_h/h; w *= scale; h *= scale; BufferedImage thumb = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = thumb.createGraphics(); g2d.drawImage(img, 0, 0, w, h, null); g2d.dispose(); return Utils.saveTmpImage(thumb); } public ImageButton(JTextPane pane, String imgFilename){ _pane = pane; _imgFilename = imgFilename; _showText = true; _exact = false; _similarity = DEFAULT_SIMILARITY; _numMatches = DEFAULT_NUM_MATCHES; _thumbFname = createThumbnail(imgFilename); setIcon(new ImageIcon(_thumbFname)); setBorderPainted(true); setCursor(new Cursor (Cursor.HAND_CURSOR)); addActionListener(this); //addMouseListener(this); setToolTipText( this.toString() ); } private boolean useThumbnail(){ return !_imgFilename.equals(_thumbFname); } public void paint(Graphics g){ super.paint(g); Graphics2D g2d = (Graphics2D)g; drawText(g2d); if( useThumbnail() ){ g2d.setColor( new Color(0, 128, 128, 128) ); g2d.drawRoundRect(3, 3, getWidth()-7, getHeight()-7, 5, 5); } } private static Font textFont = new Font("arial", Font.BOLD, 12); private void drawText(Graphics2D g2d){ String str = ""; _showText = false; if( !_exact && _similarity != DEFAULT_SIMILARITY){ _showText = true; str += _similarity + " "; } if(_numMatches != DEFAULT_NUM_MATCHES){ _showText = true; str += "(" + _numMatches + ")"; } if( !_showText ) return; final int w = g2d.getFontMetrics().stringWidth(str); final int fontH = g2d.getFontMetrics().getMaxAscent(); final int x = getWidth() - w - 3, y = 0; final int borderW = 2; g2d.setFont( textFont ); g2d.setColor( new Color(0, 128, 0, 128) ); g2d.fillRoundRect(x-borderW, y, w+borderW*2, fontH+borderW*2, 3, 3); g2d.setColor( Color.white ); g2d.drawString(str, x, y+fontH+1); } public void actionPerformed(ActionEvent e) { Debug.log("click on image"); pwin = new PatternWindow(this, _exact, _similarity, _numMatches); } public String getImageFilename(){ return _imgFilename; } public String toString(){ String img = new File(_imgFilename).getName(); if( _exact || _similarity != DEFAULT_SIMILARITY || _numMatches != DEFAULT_NUM_MATCHES ){ String ret = "Pattern(\"" + img + "\")"; if(_exact) ret += ".exact()"; else ret += String.format(".similar(%.2f)", _similarity); if(_numMatches != DEFAULT_NUM_MATCHES) ret += String.format(".firstN(%d)", _numMatches); return ret; } else return "\"" + img + "\""; } }
true
true
boolean replaceWithImage(int startOff, int endOff) throws BadLocationException{ Document doc = getDocument(); String imgStr = doc.getText(startOff, endOff - startOff); String filename = imgStr.substring(1,endOff-startOff-1);; boolean useParameters = false; boolean exact = false; int numMatches = -1; float similarity = -1f; //Debug.log("imgStr: " + imgStr); //Debug.log("filename " + filename); if( imgStr.startsWith("Pattern") ){ useParameters = true; String[] tokens = imgStr.split("\\)\\s*\\.?"); for(String str : tokens){ //System.out.println("token: " + str); if( str.startsWith("exact") ) exact = true; if( str.startsWith("Pattern") ) filename = str.substring( str.indexOf("\"")+1,str.lastIndexOf("\"")); if( str.startsWith("similar") ){ String strArg = str.substring(str.lastIndexOf("(")+1); similarity = Float.valueOf(strArg); } if( str.startsWith("firstN") ){ String strArg = str.substring(str.lastIndexOf("(")+1); numMatches = Integer.valueOf(strArg); } } } else if( imgStr.startsWith("Subregion") ){ String[] tokens = imgStr.split("[(),]"); int x = Integer.valueOf(tokens[1]), y = Integer.valueOf(tokens[2]), w = Integer.valueOf(tokens[3]), h = Integer.valueOf(tokens[4]); this.select(startOff, endOff); RegionButton icon = new RegionButton(this, x, y, w, h); this.insertComponent(icon); return true; } else if( patHistoryBtnStr.matcher(imgStr).matches() ){ Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(startOff); Element line = root.getElement(lineIdx); try{ CaptureButton btnCapture = (CaptureButton)_historyBtnClass.newInstance(); if( imgStr.indexOf("DIFF") >= 0 ) btnCapture.setDiffMode(true); btnCapture.setSrcElement(line); btnCapture.setParentPane(this); //System.out.println("new btn: " + btnCapture.getSrcElement()); this.select(startOff, endOff); if( btnCapture.hasNext() ){ int pos = startOff; doc.insertString(pos++, "[", null); this.insertComponent(btnCapture); pos++; while(btnCapture.hasNext()){ CaptureButton btn = btnCapture.getNextDiffButton(); doc.insertString(pos++, ",", null); this.insertComponent(btn); pos++; } doc.insertString(pos, "]", null); } else this.insertComponent(btnCapture); } catch(Exception e){ e.printStackTrace(); } return true; } File f = getFileInBundle(filename); Debug.log(7,"replaceWithImage: " + filename); if( f.exists() ){ this.select(startOff, endOff); ImageButton icon = new ImageButton(this, f.getAbsolutePath()); if(useParameters) icon.setParameters(exact, similarity, numMatches); this.insertComponent(icon); return true; } return false; }
boolean replaceWithImage(int startOff, int endOff) throws BadLocationException{ Document doc = getDocument(); String imgStr = doc.getText(startOff, endOff - startOff); String filename = imgStr.substring(1,endOff-startOff-1);; boolean useParameters = false; boolean exact = false; int numMatches = -1; float similarity = -1f; //Debug.log("imgStr: " + imgStr); //Debug.log("filename " + filename); if( imgStr.startsWith("Pattern") ){ useParameters = true; String[] tokens = imgStr.split("\\)\\s*\\.?"); for(String str : tokens){ //System.out.println("token: " + str); if( str.startsWith("exact") ) exact = true; if( str.startsWith("Pattern") ) filename = str.substring( str.indexOf("\"")+1,str.lastIndexOf("\"")); if( str.startsWith("similar") ){ String strArg = str.substring(str.lastIndexOf("(")+1); similarity = Float.valueOf(strArg); } if( str.startsWith("firstN") ){ String strArg = str.substring(str.lastIndexOf("(")+1); numMatches = Integer.valueOf(strArg); } } } else if( imgStr.startsWith("Subregion") ){ String[] tokens = imgStr.split("[(),]"); int x = Integer.valueOf(tokens[1]), y = Integer.valueOf(tokens[2]), w = Integer.valueOf(tokens[3]), h = Integer.valueOf(tokens[4]); this.select(startOff, endOff); RegionButton icon = new RegionButton(this, x, y, w, h); this.insertComponent(icon); return true; } else if( patHistoryBtnStr.matcher(imgStr).matches() ){ Element root = doc.getDefaultRootElement(); int lineIdx = root.getElementIndex(startOff); Element line = root.getElement(lineIdx); try{ CaptureButton btnCapture = (CaptureButton)_historyBtnClass.newInstance(); if( imgStr.indexOf("DIFF") >= 0 ) btnCapture.setDiffMode(true); btnCapture.setSrcElement(line); btnCapture.setParentPane(this); //System.out.println("new btn: " + btnCapture.getSrcElement()); this.select(startOff, endOff); if( btnCapture.hasNext() ){ int pos = startOff; doc.insertString(pos++, "[", null); this.insertComponent(btnCapture); pos++; while(btnCapture.hasNext()){ CaptureButton btn = btnCapture.getNextDiffButton(); doc.insertString(pos++, ",", null); this.insertComponent(btn); pos++; } doc.insertString(pos, "]", null); } else this.insertComponent(btnCapture); } catch(Exception e){ e.printStackTrace(); } return true; } File f = getFileInBundle(filename); Debug.log(7,"replaceWithImage: " + filename); if( f != null && f.exists() ){ this.select(startOff, endOff); ImageButton icon = new ImageButton(this, f.getAbsolutePath()); if(useParameters) icon.setParameters(exact, similarity, numMatches); this.insertComponent(icon); return true; } return false; }
diff --git a/patches/target-build/bi-platform-web-servlet/src/pt/webdetails/cdf/NavigateComponent.java b/patches/target-build/bi-platform-web-servlet/src/pt/webdetails/cdf/NavigateComponent.java index 99462e1d..90bba730 100755 --- a/patches/target-build/bi-platform-web-servlet/src/pt/webdetails/cdf/NavigateComponent.java +++ b/patches/target-build/bi-platform-web-servlet/src/pt/webdetails/cdf/NavigateComponent.java @@ -1,430 +1,430 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pt.webdetails.cdf; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.dom4j.Element; import org.pentaho.platform.engine.core.system.PentahoBase; import org.pentaho.platform.api.repository.ISolutionRepository; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.engine.core.system.PentahoSystem; import org.pentaho.platform.api.engine.ICacheManager; import org.pentaho.platform.repository.solution.SolutionRepositoryBase; import org.pentaho.platform.util.xml.dom4j.XmlDom4JHelper; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.Log; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.XPath; import org.pentaho.platform.api.engine.ISolutionFile; import org.json.JSONObject; import org.json.JSONArray; import org.json.XML; import org.json.JSONException; /** * * @author pedro */ public class NavigateComponent extends PentahoBase { private static final String NAVIGATOR = "navigator"; private static final String CONTENTLIST = "contentList"; private static final String TYPE_DIR = "FOLDER"; private static final String TYPE_XACTION = "XACTION"; private static final String TYPE_URL = "URL"; private static final String CACHE_NAVIGATOR = "CDF_NAVIGATOR_JSON"; protected static final Log logger = LogFactory.getLog(NavigateComponent.class); ISolutionRepository solutionRepository = null; IPentahoSession userSession; ICacheManager cacheManager; boolean cachingAvailable; public NavigateComponent(IPentahoSession userSession) { solutionRepository = PentahoSystem.get(ISolutionRepository.class,userSession);// PentahoSystem.getSolutionRepository(userSession);// g etSolutionRepository(userSession); this.userSession = userSession; cacheManager = PentahoSystem.getCacheManager(userSession); cachingAvailable = cacheManager != null && cacheManager.cacheEnabled(); } public String getNavigationElements(String mode, String solution, String path) throws JSONException { if (mode.equals(NAVIGATOR)) { return getNavigatorJSON(solution, path); } else if (mode.equals(CONTENTLIST)) { return getContentListJSON(solution, path); } else { logger.warn("Invalid mode: " + mode); return ""; } } @Override public Log getLogger() { return logger; } private String getNavigatorJSON(String solution, String path) throws JSONException { String jsonString = null; if (cachingAvailable && (jsonString = (String) cacheManager.getFromSessionCache(userSession, CACHE_NAVIGATOR)) != null) { debug("Navigator found in cache"); } else { Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE); // Get it and build the tree JSONObject json = new JSONObject(); Node tree = navDoc.getRootElement(); JSONArray array = processTree(tree); json.put("solution", array.get(0)); jsonString = json.toString(2); // Store in cache: cacheManager.putInSessionCache(userSession, CACHE_NAVIGATOR, jsonString); } return jsonString; } private JSONArray processTree(Node tree) throws JSONException { String xPathDir = "./branch[@isDir='true']"; //$NON-NLS-1$ JSONArray array = null; try { List nodes = tree.selectNodes(xPathDir); //$NON-NLS-1$ if (!nodes.isEmpty()) { array = new JSONArray(); } Iterator nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Node node = (Node) nodeIterator.next(); boolean processChildren = true; // String name = node.getText(); String path = node.valueOf("@id"); String name = node.valueOf("branchText"); //debug("Processing branch: " + path); JSONObject json = new JSONObject(); json.put("name", name); json.put("id", path); // put solution and path String[] pathArray = path.split("\\/"); path = path.replace(pathArray[1], "solution"); String solutionName = pathArray.length > 2 ? pathArray[2] : ""; String solutionPath = pathArray.length > 3 ? path.substring(path.indexOf("/", 10) + 1) : ""; json.put("solution", solutionName); json.put("path", solutionPath); json.put("type", TYPE_DIR); if (path.startsWith("/solution/")) { String resourcePath = path.substring(9); //try { String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME; if (solutionRepository.resourceExists(resourceName)) { System.out.println("Processing folder " + resourcePath); ISolutionFile file = solutionRepository.getFileByPath(resourceName); Document indexFile = solutionRepository.getResourceAsDocument(resourceName); solutionRepository.localizeDoc(indexFile, file); boolean visible = Boolean.parseBoolean(indexFile.valueOf("/index/visible")); json.put("visible", visible); json.put("title", indexFile.valueOf("/index/name")); json.put("description", indexFile.valueOf("/index/description")); if (!visible) { processChildren = false; } //System.out.println("... done processing folder " + resourcePath); } else { json.put("visible", false); json.put("title", "Hidden"); processChildren = false; } } else { // root dir json.put("visible", true); json.put("title", "Solution"); } //System.out.println(" Processing getting children "); if (processChildren) { JSONArray children = processTree(node); if (children != null) { json.put("folders", children); } } array.put(json); } } catch (Exception e) { System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage()); warn("Error: " + e.getClass().getName() + " - " + e.getMessage()); } return array; } private String getContentListJSON(String _solution, String _path) throws JSONException { Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE); // Get it and build the tree JSONObject contentListJSON = new JSONObject(); Node tree = navDoc.getRootElement(); String solutionPrefix = tree.valueOf("/tree/branch/@id"); StringBuffer _id = new StringBuffer(solutionPrefix); if (_solution.length() > 0) { _id.append("/" + _solution); } if (_path.length() > 0) { _id.append("/" + _path); } //branch[@id='/solution/admin' and @isDir='true']/leaf String xPathDirBranch = "//branch[@id='" + _id.toString() + "' and @isDir='true']/branch"; String xPathDirLeaf = "//branch[@id='" + _id.toString() + "' and @isDir='true']/leaf"; JSONArray array = null; // Iterate through branches try { List nodes = tree.selectNodes(xPathDirBranch); //$NON-NLS-1$ if (!nodes.isEmpty()) { array = new JSONArray(); } Iterator nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Node node = (Node) nodeIterator.next(); // String name = node.getText(); String path = node.valueOf("@id"); String name = node.valueOf("branchText"); //debug("Processing branch: " + path); JSONObject json = new JSONObject(); json.put("name", name); json.put("id", path); json.put("solution", _solution); json.put("path", _path + (_path.length() > 0 ? "/" : "") + name); json.put("type", TYPE_DIR); if (path.startsWith((solutionPrefix + "/"))) { String resourcePath = path.substring(9); //try { String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME; if (solutionRepository.resourceExists(resourceName)) { System.out.println("Processing folder " + resourcePath); ISolutionFile file = solutionRepository.getFileByPath(resourceName); Document indexFile = solutionRepository.getResourceAsDocument(resourceName); solutionRepository.localizeDoc(indexFile, file); json.put("visible", new Boolean(indexFile.valueOf("/index/visible"))); json.put("title", indexFile.valueOf("/index/name")); json.put("description", indexFile.valueOf("/index/description")); //System.out.println("... done processing folder " + resourcePath); } else { json.put("visible", false); json.put("title", "Hidden"); } } else { // root dir json.put("visible", true); json.put("title", "Solution"); } array.put(json); } } catch (Exception e) { System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage()); warn("Error: " + e.getClass().getName() + " - " + e.getMessage()); } // Iterate through leaves try { List nodes = tree.selectNodes(xPathDirLeaf); //$NON-NLS-1$ if (array == null && !nodes.isEmpty()) { array = new JSONArray(); } Iterator nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Element node = (Element) nodeIterator.next(); // String name = node.getText(); String path = node.valueOf("path"); String name = node.valueOf("leafText"); JSONObject json = new JSONObject(); json.put("name", name); json.put("id", path); json.put("solution", _solution); json.put("path", _path); json.put("action", name); // we only care for: .xactions and .url files if (name.toLowerCase().endsWith(".xaction")) { json.put("type", TYPE_XACTION); String resourcePath = path.replace(solutionPrefix,"solution").substring(9); String resourceName = resourcePath; if (solutionRepository.resourceExists(resourceName)) { System.out.println("Processing file " + resourcePath); ISolutionFile file = solutionRepository.getFileByPath(resourceName); Document indexFile = solutionRepository.getResourceAsDocument(resourceName); solutionRepository.localizeDoc(indexFile, file); - json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 ? Boolean.FALSE : Boolean.TRUE); + json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 || indexFile.valueOf("/action-sequence/documentation/result-type").equals("none") ? Boolean.FALSE : Boolean.TRUE); json.put("title", indexFile.valueOf("/action-sequence/title")); json.put("description", indexFile.valueOf("/action-sequence/documentation/description")); //System.out.println("... done processing folder " + resourcePath); } else { json.put("visible", false); json.put("title", "Hidden"); } } else if (name.toLowerCase().endsWith(".url")) { json.put("type", TYPE_URL); String resourcePath = path.replace(solutionPrefix,"solution").substring(9); String resourceName = resourcePath; ISolutionFile file = solutionRepository.getFileByPath(resourceName); processUrl(file, node, resourceName); json.put("visible", new Boolean(node.valueOf("file/@visible"))); json.put("title", node.valueOf("file/title")); json.put("description", node.valueOf("file/description")); json.put("url", node.valueOf("file/url")); } else { //ignore other files continue; } array.put(json); } } catch (Exception e) { System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage()); warn("Error: " + e.getClass().getName() + " - " + e.getMessage()); } contentListJSON.put("content", array); String jsonString = contentListJSON.toString(2); //debug("Finished processing tree"); //RepositoryFile file = (RepositoryFile) getFileByPath(fullPath); return jsonString; } private void processUrl(ISolutionFile file, Element parentNode, String resourceName) { // parse the .url file to get the contents try { String urlContent = solutionRepository.getResourceAsString(resourceName); StringTokenizer tokenizer = new StringTokenizer(urlContent, "\n"); //$NON-NLS-1$ String title = null; String url = null; String description = null; String target = null; while (tokenizer.hasMoreTokens()) { String line = tokenizer.nextToken(); int pos = line.indexOf('='); if (pos > 0) { String name = line.substring(0, pos); String value = line.substring(pos + 1); if ((value != null) && (value.length() > 0) && (value.charAt(value.length() - 1) == '\r')) { value = value.substring(0, value.length() - 1); } if ("URL".equalsIgnoreCase(name)) { //$NON-NLS-1$ url = value; } if ("name".equalsIgnoreCase(name)) { //$NON-NLS-1$ title = value; } if ("description".equalsIgnoreCase(name)) { //$NON-NLS-1$ description = value; } if ("target".equalsIgnoreCase(name)) { //$NON-NLS-1$ target = value; } } } if (url != null) { // now create an entry for the database Element dirNode = parentNode.addElement("file"); //$NON-NLS-1$ dirNode.addAttribute("type", TYPE_URL); //$NON-NLS-1$ dirNode.addElement("filename").setText(title); //$NON-NLS-1$ dirNode.addElement("title").setText(title); //$NON-NLS-1$ if (target != null) { dirNode.addElement("target").setText(target); //$NON-NLS-1$ } if (description != null) { dirNode.addElement("description").setText(description); //$NON-NLS-1$ } dirNode.addElement("url").setText(url); //$NON-NLS-1$ dirNode.addAttribute("visible", "true"); //$NON-NLS-1$ //$NON-NLS-2$ solutionRepository.localizeDoc(dirNode, file); } } catch (IOException e) { warn("Error processing url file: " + e.getClass().getName() + " - " + e.getMessage()); } } }
true
true
private String getContentListJSON(String _solution, String _path) throws JSONException { Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE); // Get it and build the tree JSONObject contentListJSON = new JSONObject(); Node tree = navDoc.getRootElement(); String solutionPrefix = tree.valueOf("/tree/branch/@id"); StringBuffer _id = new StringBuffer(solutionPrefix); if (_solution.length() > 0) { _id.append("/" + _solution); } if (_path.length() > 0) { _id.append("/" + _path); } //branch[@id='/solution/admin' and @isDir='true']/leaf String xPathDirBranch = "//branch[@id='" + _id.toString() + "' and @isDir='true']/branch"; String xPathDirLeaf = "//branch[@id='" + _id.toString() + "' and @isDir='true']/leaf"; JSONArray array = null; // Iterate through branches try { List nodes = tree.selectNodes(xPathDirBranch); //$NON-NLS-1$ if (!nodes.isEmpty()) { array = new JSONArray(); } Iterator nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Node node = (Node) nodeIterator.next(); // String name = node.getText(); String path = node.valueOf("@id"); String name = node.valueOf("branchText"); //debug("Processing branch: " + path); JSONObject json = new JSONObject(); json.put("name", name); json.put("id", path); json.put("solution", _solution); json.put("path", _path + (_path.length() > 0 ? "/" : "") + name); json.put("type", TYPE_DIR); if (path.startsWith((solutionPrefix + "/"))) { String resourcePath = path.substring(9); //try { String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME; if (solutionRepository.resourceExists(resourceName)) { System.out.println("Processing folder " + resourcePath); ISolutionFile file = solutionRepository.getFileByPath(resourceName); Document indexFile = solutionRepository.getResourceAsDocument(resourceName); solutionRepository.localizeDoc(indexFile, file); json.put("visible", new Boolean(indexFile.valueOf("/index/visible"))); json.put("title", indexFile.valueOf("/index/name")); json.put("description", indexFile.valueOf("/index/description")); //System.out.println("... done processing folder " + resourcePath); } else { json.put("visible", false); json.put("title", "Hidden"); } } else { // root dir json.put("visible", true); json.put("title", "Solution"); } array.put(json); } } catch (Exception e) { System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage()); warn("Error: " + e.getClass().getName() + " - " + e.getMessage()); } // Iterate through leaves try { List nodes = tree.selectNodes(xPathDirLeaf); //$NON-NLS-1$ if (array == null && !nodes.isEmpty()) { array = new JSONArray(); } Iterator nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Element node = (Element) nodeIterator.next(); // String name = node.getText(); String path = node.valueOf("path"); String name = node.valueOf("leafText"); JSONObject json = new JSONObject(); json.put("name", name); json.put("id", path); json.put("solution", _solution); json.put("path", _path); json.put("action", name); // we only care for: .xactions and .url files if (name.toLowerCase().endsWith(".xaction")) { json.put("type", TYPE_XACTION); String resourcePath = path.replace(solutionPrefix,"solution").substring(9); String resourceName = resourcePath; if (solutionRepository.resourceExists(resourceName)) { System.out.println("Processing file " + resourcePath); ISolutionFile file = solutionRepository.getFileByPath(resourceName); Document indexFile = solutionRepository.getResourceAsDocument(resourceName); solutionRepository.localizeDoc(indexFile, file); json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 ? Boolean.FALSE : Boolean.TRUE); json.put("title", indexFile.valueOf("/action-sequence/title")); json.put("description", indexFile.valueOf("/action-sequence/documentation/description")); //System.out.println("... done processing folder " + resourcePath); } else { json.put("visible", false); json.put("title", "Hidden"); } } else if (name.toLowerCase().endsWith(".url")) { json.put("type", TYPE_URL); String resourcePath = path.replace(solutionPrefix,"solution").substring(9); String resourceName = resourcePath; ISolutionFile file = solutionRepository.getFileByPath(resourceName); processUrl(file, node, resourceName); json.put("visible", new Boolean(node.valueOf("file/@visible"))); json.put("title", node.valueOf("file/title")); json.put("description", node.valueOf("file/description")); json.put("url", node.valueOf("file/url")); } else { //ignore other files continue; } array.put(json); } } catch (Exception e) { System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage()); warn("Error: " + e.getClass().getName() + " - " + e.getMessage()); } contentListJSON.put("content", array); String jsonString = contentListJSON.toString(2); //debug("Finished processing tree"); //RepositoryFile file = (RepositoryFile) getFileByPath(fullPath); return jsonString; }
private String getContentListJSON(String _solution, String _path) throws JSONException { Document navDoc = solutionRepository.getSolutionTree(ISolutionRepository.ACTION_EXECUTE); // Get it and build the tree JSONObject contentListJSON = new JSONObject(); Node tree = navDoc.getRootElement(); String solutionPrefix = tree.valueOf("/tree/branch/@id"); StringBuffer _id = new StringBuffer(solutionPrefix); if (_solution.length() > 0) { _id.append("/" + _solution); } if (_path.length() > 0) { _id.append("/" + _path); } //branch[@id='/solution/admin' and @isDir='true']/leaf String xPathDirBranch = "//branch[@id='" + _id.toString() + "' and @isDir='true']/branch"; String xPathDirLeaf = "//branch[@id='" + _id.toString() + "' and @isDir='true']/leaf"; JSONArray array = null; // Iterate through branches try { List nodes = tree.selectNodes(xPathDirBranch); //$NON-NLS-1$ if (!nodes.isEmpty()) { array = new JSONArray(); } Iterator nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Node node = (Node) nodeIterator.next(); // String name = node.getText(); String path = node.valueOf("@id"); String name = node.valueOf("branchText"); //debug("Processing branch: " + path); JSONObject json = new JSONObject(); json.put("name", name); json.put("id", path); json.put("solution", _solution); json.put("path", _path + (_path.length() > 0 ? "/" : "") + name); json.put("type", TYPE_DIR); if (path.startsWith((solutionPrefix + "/"))) { String resourcePath = path.substring(9); //try { String resourceName = resourcePath + "/" + SolutionRepositoryBase.INDEX_FILENAME; if (solutionRepository.resourceExists(resourceName)) { System.out.println("Processing folder " + resourcePath); ISolutionFile file = solutionRepository.getFileByPath(resourceName); Document indexFile = solutionRepository.getResourceAsDocument(resourceName); solutionRepository.localizeDoc(indexFile, file); json.put("visible", new Boolean(indexFile.valueOf("/index/visible"))); json.put("title", indexFile.valueOf("/index/name")); json.put("description", indexFile.valueOf("/index/description")); //System.out.println("... done processing folder " + resourcePath); } else { json.put("visible", false); json.put("title", "Hidden"); } } else { // root dir json.put("visible", true); json.put("title", "Solution"); } array.put(json); } } catch (Exception e) { System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage()); warn("Error: " + e.getClass().getName() + " - " + e.getMessage()); } // Iterate through leaves try { List nodes = tree.selectNodes(xPathDirLeaf); //$NON-NLS-1$ if (array == null && !nodes.isEmpty()) { array = new JSONArray(); } Iterator nodeIterator = nodes.iterator(); while (nodeIterator.hasNext()) { Element node = (Element) nodeIterator.next(); // String name = node.getText(); String path = node.valueOf("path"); String name = node.valueOf("leafText"); JSONObject json = new JSONObject(); json.put("name", name); json.put("id", path); json.put("solution", _solution); json.put("path", _path); json.put("action", name); // we only care for: .xactions and .url files if (name.toLowerCase().endsWith(".xaction")) { json.put("type", TYPE_XACTION); String resourcePath = path.replace(solutionPrefix,"solution").substring(9); String resourceName = resourcePath; if (solutionRepository.resourceExists(resourceName)) { System.out.println("Processing file " + resourcePath); ISolutionFile file = solutionRepository.getFileByPath(resourceName); Document indexFile = solutionRepository.getResourceAsDocument(resourceName); solutionRepository.localizeDoc(indexFile, file); json.put("visible", indexFile.selectNodes("/action-sequence/documentation/result-type").size() == 0 || indexFile.valueOf("/action-sequence/documentation/result-type").equals("none") ? Boolean.FALSE : Boolean.TRUE); json.put("title", indexFile.valueOf("/action-sequence/title")); json.put("description", indexFile.valueOf("/action-sequence/documentation/description")); //System.out.println("... done processing folder " + resourcePath); } else { json.put("visible", false); json.put("title", "Hidden"); } } else if (name.toLowerCase().endsWith(".url")) { json.put("type", TYPE_URL); String resourcePath = path.replace(solutionPrefix,"solution").substring(9); String resourceName = resourcePath; ISolutionFile file = solutionRepository.getFileByPath(resourceName); processUrl(file, node, resourceName); json.put("visible", new Boolean(node.valueOf("file/@visible"))); json.put("title", node.valueOf("file/title")); json.put("description", node.valueOf("file/description")); json.put("url", node.valueOf("file/url")); } else { //ignore other files continue; } array.put(json); } } catch (Exception e) { System.out.println("Error: " + e.getClass().getName() + " - " + e.getMessage()); warn("Error: " + e.getClass().getName() + " - " + e.getMessage()); } contentListJSON.put("content", array); String jsonString = contentListJSON.toString(2); //debug("Finished processing tree"); //RepositoryFile file = (RepositoryFile) getFileByPath(fullPath); return jsonString; }
diff --git a/src/org/plovr/cli/SoyWebCommand.java b/src/org/plovr/cli/SoyWebCommand.java index 3b936fb41..5c1039ac1 100644 --- a/src/org/plovr/cli/SoyWebCommand.java +++ b/src/org/plovr/cli/SoyWebCommand.java @@ -1,64 +1,64 @@ package org.plovr.cli; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Map; import org.plovr.soy.server.Config; import org.plovr.soy.server.Server; import org.plovr.util.SoyDataUtil; import com.google.common.collect.ImmutableMap; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.template.soy.data.SoyData; public class SoyWebCommand extends AbstractCommandRunner<SoyWebCommandOptions> { @Override SoyWebCommandOptions createOptions() { return new SoyWebCommandOptions(); } @Override int runCommandWithOptions(SoyWebCommandOptions options) throws IOException { String pathToGlobals = options.getCompileTimeGlobalsFile(); Map<String, ?> globals; if (pathToGlobals == null) { globals = ImmutableMap.of(); } else { File globalsFile = new File(pathToGlobals); if (!globalsFile.exists()) { throw new RuntimeException("Could not find file: " + pathToGlobals); } JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new FileReader(globalsFile)); if (!root.isJsonObject()) { throw new RuntimeException("Root of globals file must be a map"); } JsonObject json = root.getAsJsonObject(); ImmutableMap.Builder<String, SoyData> builder = ImmutableMap.builder(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { JsonElement el = entry.getValue(); builder.put(entry.getKey(), SoyDataUtil.jsonToSoyData(el)); } globals = builder.build(); } Config config = new Config( options.getPort(), new File(options.getDir()), options.isStatic(), globals); Server server = new Server(config); server.run(); - return 0; + return STATUS_NO_EXIT; } @Override String getUsageIntro() { return "Specify a directory that contains Soy files"; } }
true
true
int runCommandWithOptions(SoyWebCommandOptions options) throws IOException { String pathToGlobals = options.getCompileTimeGlobalsFile(); Map<String, ?> globals; if (pathToGlobals == null) { globals = ImmutableMap.of(); } else { File globalsFile = new File(pathToGlobals); if (!globalsFile.exists()) { throw new RuntimeException("Could not find file: " + pathToGlobals); } JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new FileReader(globalsFile)); if (!root.isJsonObject()) { throw new RuntimeException("Root of globals file must be a map"); } JsonObject json = root.getAsJsonObject(); ImmutableMap.Builder<String, SoyData> builder = ImmutableMap.builder(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { JsonElement el = entry.getValue(); builder.put(entry.getKey(), SoyDataUtil.jsonToSoyData(el)); } globals = builder.build(); } Config config = new Config( options.getPort(), new File(options.getDir()), options.isStatic(), globals); Server server = new Server(config); server.run(); return 0; }
int runCommandWithOptions(SoyWebCommandOptions options) throws IOException { String pathToGlobals = options.getCompileTimeGlobalsFile(); Map<String, ?> globals; if (pathToGlobals == null) { globals = ImmutableMap.of(); } else { File globalsFile = new File(pathToGlobals); if (!globalsFile.exists()) { throw new RuntimeException("Could not find file: " + pathToGlobals); } JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new FileReader(globalsFile)); if (!root.isJsonObject()) { throw new RuntimeException("Root of globals file must be a map"); } JsonObject json = root.getAsJsonObject(); ImmutableMap.Builder<String, SoyData> builder = ImmutableMap.builder(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { JsonElement el = entry.getValue(); builder.put(entry.getKey(), SoyDataUtil.jsonToSoyData(el)); } globals = builder.build(); } Config config = new Config( options.getPort(), new File(options.getDir()), options.isStatic(), globals); Server server = new Server(config); server.run(); return STATUS_NO_EXIT; }
diff --git a/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java b/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java index eca5d38..8fefecc 100644 --- a/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java +++ b/src/org/irmacard/web/restapi/resources/VerificationProtocolResource.java @@ -1,108 +1,119 @@ package org.irmacard.web.restapi.resources; import net.sourceforge.scuba.smartcards.ProtocolCommand; import net.sourceforge.scuba.smartcards.ProtocolResponse; import net.sourceforge.scuba.smartcards.ProtocolResponses; import org.irmacard.credentials.Attributes; import org.irmacard.credentials.CredentialsException; import org.irmacard.credentials.Nonce; import org.irmacard.credentials.idemix.IdemixCredentials; import org.irmacard.credentials.idemix.IdemixNonce; import org.irmacard.credentials.idemix.spec.IdemixVerifySpecification; import org.irmacard.credentials.idemix.util.VerifyCredentialInformation; import org.irmacard.web.restapi.ProtocolState; import org.irmacard.web.restapi.util.ProtocolCommandSerializer; import org.irmacard.web.restapi.util.ProtocolResponseDeserializer; import org.irmacard.web.restapi.util.ProtocolStep; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class VerificationProtocolResource extends ProtocolBaseResource { // TODO: the ISSUER and CRED_NAME should be deduced from the // proofspec, but the credentials API doesn't support that yet. private static final String ISSUER = "MijnOverheid"; private static final String CRED_NAME = "ageLower"; @Override public String handleProtocolStep(String id, int step, String value) { String verifier = (String) getRequestAttributes().get("verifier"); String specName = (String) getRequestAttributes().get("specname"); Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(ProtocolCommand.class, new ProtocolCommandSerializer()).create(); VerifyCredentialInformation vci = new VerifyCredentialInformation( ISSUER, CRED_NAME, verifier, specName); IdemixVerifySpecification vspec = vci.getIdemixVerifySpecification(); ProtocolStep ps = null; switch (step) { case 0: ps = createVerificationProtocolStep(id, vspec); ps.responseurl = makeResponseURL(id, step+1); ProtocolState.putStatus(id, "step1"); break; case 1: ps = new ProtocolStep(); ps.protocolDone = true; ps.status = "failure"; try { Attributes attr = processVerificationResponse(id, vspec, value); if (attr != null) { ps.status = "success"; if (verifier.equalsIgnoreCase("NYTimes")) { - ps.result = "http://www.nytimes.com"; + String age = new String(attr.get("over12")); + if (age.equalsIgnoreCase("yes")) { + ps.result = "http://www.nytimes.com"; + ProtocolState.putResult(id, ps.result); + } else { + ps.status = "failure"; + } } else { - ps.result = "http://spuitenenslikken.bnn.nl"; + String age = new String(attr.get("over16")); + if (age.equalsIgnoreCase("yes")) { + ps.result = "http://spuitenenslikken.bnn.nl"; + ProtocolState.putResult(id, ps.result); + } else { + ps.status = "failure"; + } } - ProtocolState.putResult(id, ps.result); } } catch (CredentialsException e) { e.printStackTrace(); } break; default: break; } ProtocolState.putStatus(id, ps.status); return gson.toJson(ps); } public static ProtocolStep createVerificationProtocolStep(String id, IdemixVerifySpecification vspec) { ProtocolStep ps = new ProtocolStep(); IdemixCredentials ic = new IdemixCredentials(null); try { Nonce nonce = ic.generateNonce(vspec); ps.commands = ic.requestProofCommands(vspec, nonce); ps.feedbackMessage = "Verifying"; ProtocolState.putNonce(id, ((IdemixNonce) nonce).getNonce()); } catch (CredentialsException e) { e.printStackTrace(); } return ps; } public static Attributes processVerificationResponse(String id, IdemixVerifySpecification vspec, String value) throws CredentialsException { Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(ProtocolResponse.class, new ProtocolResponseDeserializer()).create(); IdemixNonce nonce = new IdemixNonce(ProtocolState.getNonce(id)); ProtocolResponses responses = gson.fromJson(value, ProtocolResponses.class); IdemixCredentials ic = new IdemixCredentials(null); return ic.verifyProofResponses(vspec, nonce, responses); } }
false
true
public String handleProtocolStep(String id, int step, String value) { String verifier = (String) getRequestAttributes().get("verifier"); String specName = (String) getRequestAttributes().get("specname"); Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(ProtocolCommand.class, new ProtocolCommandSerializer()).create(); VerifyCredentialInformation vci = new VerifyCredentialInformation( ISSUER, CRED_NAME, verifier, specName); IdemixVerifySpecification vspec = vci.getIdemixVerifySpecification(); ProtocolStep ps = null; switch (step) { case 0: ps = createVerificationProtocolStep(id, vspec); ps.responseurl = makeResponseURL(id, step+1); ProtocolState.putStatus(id, "step1"); break; case 1: ps = new ProtocolStep(); ps.protocolDone = true; ps.status = "failure"; try { Attributes attr = processVerificationResponse(id, vspec, value); if (attr != null) { ps.status = "success"; if (verifier.equalsIgnoreCase("NYTimes")) { ps.result = "http://www.nytimes.com"; } else { ps.result = "http://spuitenenslikken.bnn.nl"; } ProtocolState.putResult(id, ps.result); } } catch (CredentialsException e) { e.printStackTrace(); } break; default: break; } ProtocolState.putStatus(id, ps.status); return gson.toJson(ps); }
public String handleProtocolStep(String id, int step, String value) { String verifier = (String) getRequestAttributes().get("verifier"); String specName = (String) getRequestAttributes().get("specname"); Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(ProtocolCommand.class, new ProtocolCommandSerializer()).create(); VerifyCredentialInformation vci = new VerifyCredentialInformation( ISSUER, CRED_NAME, verifier, specName); IdemixVerifySpecification vspec = vci.getIdemixVerifySpecification(); ProtocolStep ps = null; switch (step) { case 0: ps = createVerificationProtocolStep(id, vspec); ps.responseurl = makeResponseURL(id, step+1); ProtocolState.putStatus(id, "step1"); break; case 1: ps = new ProtocolStep(); ps.protocolDone = true; ps.status = "failure"; try { Attributes attr = processVerificationResponse(id, vspec, value); if (attr != null) { ps.status = "success"; if (verifier.equalsIgnoreCase("NYTimes")) { String age = new String(attr.get("over12")); if (age.equalsIgnoreCase("yes")) { ps.result = "http://www.nytimes.com"; ProtocolState.putResult(id, ps.result); } else { ps.status = "failure"; } } else { String age = new String(attr.get("over16")); if (age.equalsIgnoreCase("yes")) { ps.result = "http://spuitenenslikken.bnn.nl"; ProtocolState.putResult(id, ps.result); } else { ps.status = "failure"; } } } } catch (CredentialsException e) { e.printStackTrace(); } break; default: break; } ProtocolState.putStatus(id, ps.status); return gson.toJson(ps); }
diff --git a/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java b/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java index 72b278d..8ae0ae1 100644 --- a/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java +++ b/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java @@ -1,1001 +1,1001 @@ /* * Copyright 2012 LinkedIn Corp. * * 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 azkaban.viewer.reportal; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.joda.time.DateTime; import azkaban.executor.ExecutableFlow; import azkaban.executor.ExecutableNode; import azkaban.executor.ExecutionOptions; import azkaban.executor.ExecutorManagerAdapter; import azkaban.executor.ExecutorManagerException; import azkaban.flow.Flow; import azkaban.project.Project; import azkaban.project.ProjectManager; import azkaban.project.ProjectManagerException; import azkaban.reportal.util.IStreamProvider; import azkaban.reportal.util.Reportal; import azkaban.reportal.util.Reportal.Query; import azkaban.reportal.util.Reportal.Variable; import azkaban.reportal.util.ReportalHelper; import azkaban.reportal.util.ReportalUtil; import azkaban.reportal.util.StreamProviderHDFS; import azkaban.scheduler.ScheduleManager; import azkaban.scheduler.ScheduleManagerException; import azkaban.security.commons.HadoopSecurityManager; import azkaban.user.Permission.Type; import azkaban.user.User; import azkaban.utils.FileIOUtils.LogData; import azkaban.utils.Props; import azkaban.webapp.AzkabanWebServer; import azkaban.webapp.servlet.LoginAbstractAzkabanServlet; import azkaban.webapp.servlet.Page; import azkaban.webapp.session.Session; public class ReportalServlet extends LoginAbstractAzkabanServlet { private static final String REPORTAL_VARIABLE_PREFIX = "reportal.variable."; private static final String HADOOP_SECURITY_MANAGER_CLASS_PARAM = "hadoop.security.manager.class"; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(ReportalServlet.class); private CleanerThread cleanerThread; private File reportalMailDirectory; private AzkabanWebServer server; private Props props; private boolean shouldProxy; private String viewerName; private String reportalStorageUser; private File webResourcesFolder; private int itemsPerPage = 20; private boolean showNav; // private String viewerPath; private HadoopSecurityManager hadoopSecurityManager; public ReportalServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); reportalStorageUser = props.getString("reportal.storage.user", "reportal"); itemsPerPage = props.getInt("reportal.items_per_page", 20); showNav = props.getBoolean("reportal.show.navigation", false); reportalMailDirectory = new File(props.getString("reportal.mail.temp.directory", "/tmp/reportal")); reportalMailDirectory.mkdirs(); ReportalMailCreator.reportalMailDirectory = reportalMailDirectory; ReportalMailCreator.outputLocation = props.getString("reportal.output.location", "/tmp/reportal"); ReportalMailCreator.outputFileSystem = props.getString("reportal.output.filesystem", "local"); ReportalMailCreator.reportalStorageUser = reportalStorageUser; webResourcesFolder = new File(new File(props.getSource()).getParentFile().getParentFile(), "web"); webResourcesFolder.mkdirs(); setResourceDirectory(webResourcesFolder); System.out.println("Reportal web resources: " + webResourcesFolder.getAbsolutePath()); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); server = (AzkabanWebServer)getApplication(); cleanerThread = new CleanerThread(); cleanerThread.start(); ReportalMailCreator.azkaban = server; shouldProxy = props.getBoolean("azkaban.should.proxy", false); logger.info("Hdfs browser should proxy: " + shouldProxy); try { hadoopSecurityManager = loadHadoopSecurityManager(props, logger); ReportalMailCreator.hadoopSecurityManager = hadoopSecurityManager; } catch (RuntimeException e) { e.printStackTrace(); throw new RuntimeException("Failed to get hadoop security manager!" + e.getCause()); } } private HadoopSecurityManager loadHadoopSecurityManager(Props props, Logger logger) throws RuntimeException { Class<?> hadoopSecurityManagerClass = props.getClass(HADOOP_SECURITY_MANAGER_CLASS_PARAM, true, ReportalServlet.class.getClassLoader()); logger.info("Initializing hadoop security manager " + hadoopSecurityManagerClass.getName()); HadoopSecurityManager hadoopSecurityManager = null; try { Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class); hadoopSecurityManager = (HadoopSecurityManager)getInstanceMethod.invoke(hadoopSecurityManagerClass, props); } catch (InvocationTargetException e) { logger.error("Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName() + e.getCause()); throw new RuntimeException(e.getCause()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getCause()); } return hadoopSecurityManager; } @Override protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { if (hasParam(req, "ajax")) { handleAJAXAction(req, resp, session); } else { if (hasParam(req, "view")) { try { handleViewReportal(req, resp, session); } catch (Exception e) { e.printStackTrace(); } } else if (hasParam(req, "new")) { handleNewReportal(req, resp, session); } else if (hasParam(req, "edit")) { handleEditReportal(req, resp, session); } else if (hasParam(req, "run")) { handleRunReportal(req, resp, session); } else { handleListReportal(req, resp, session); } } } private void handleAJAXAction(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { HashMap<String, Object> ret = new HashMap<String, Object>(); String ajaxName = getParam(req, "ajax"); User user = session.getUser(); int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); // Delete reportal if (ajaxName.equals("delete")) { if (!project.hasPermission(user, Type.ADMIN)) { ret.put("error", "You do not have permissions to delete this reportal."); } else { try { ScheduleManager scheduleManager = server.getScheduleManager(); reportal.removeSchedules(scheduleManager); projectManager.removeProject(project, user); } catch (Exception e) { e.printStackTrace(); ret.put("error", "An exception occured while deleting this reportal."); } ret.put("result", "success"); } } // Bookmark reportal else if (ajaxName.equals("bookmark")) { boolean wasBookmarked = ReportalHelper.isBookmarkProject(project, user); try { if (wasBookmarked) { ReportalHelper.unBookmarkProject(server, project, user); ret.put("result", "success"); ret.put("bookmark", false); } else { ReportalHelper.bookmarkProject(server, project, user); ret.put("result", "success"); ret.put("bookmark", true); } } catch (ProjectManagerException e) { e.printStackTrace(); ret.put("error", "Error bookmarking reportal. " + e.getMessage()); } } // Subscribe reportal else if (ajaxName.equals("subscribe")) { boolean wasSubscribed = ReportalHelper.isSubscribeProject(project, user); if (!wasSubscribed && !project.hasPermission(user, Type.READ)) { ret.put("error", "You do not have permissions to view this reportal."); } else { try { if (wasSubscribed) { ReportalHelper.unSubscribeProject(server, project, user); ret.put("result", "success"); ret.put("subscribe", false); } else { ReportalHelper.subscribeProject(server, project, user, user.getEmail()); ret.put("result", "success"); ret.put("subscribe", true); } } catch (ProjectManagerException e) { e.printStackTrace(); ret.put("error", "Error subscribing to reportal. " + e.getMessage()); } } } // Set graph else if (ajaxName.equals("graph")) { if (reportal.getAccessViewers().size() > 0 && !project.hasPermission(user, Type.READ)) { ret.put("error", "You do not have permissions to view this reportal."); } else { String hash = getParam(req, "hash"); project.getMetadata().put("graphHash", hash); try { server.getProjectManager().updateProjectSetting(project); ret.put("result", "success"); ret.put("message", "Default graph saved."); } catch (ProjectManagerException e) { e.printStackTrace(); ret.put("error", "Error saving graph. " + e.getMessage()); } } } // Get a portion of logs else if (ajaxName.equals("log")) { int execId = getIntParam(req, "execId"); String jobId = getParam(req, "jobId"); int offset = getIntParam(req, "offset"); int length = getIntParam(req, "length"); ExecutableFlow exec; ExecutorManagerAdapter executorManager = server.getExecutorManager(); try { exec = executorManager.getExecutableFlow(execId); } catch (Exception e) { ret.put("error", "Log does not exist or isn't created yet."); return; } LogData data; try { data = executorManager.getExecutionJobLog(exec, jobId, offset, length, exec.getExecutableNode(jobId).getAttempt()); } catch (Exception e) { e.printStackTrace(); ret.put("error", "Log does not exist or isn't created yet."); return; } if (data != null) { ret.put("result", "success"); ret.put("log", data.getData()); ret.put("offset", data.getOffset()); ret.put("length", data.getLength()); ret.put("completed", exec.getEndTime() != -1); } else { // Return an empty result to indicate the end ret.put("result", "success"); ret.put("log", ""); ret.put("offset", offset); ret.put("length", 0); ret.put("completed", exec.getEndTime() != -1); } } if (ret != null) { this.writeJSON(resp, ret); } } private void handleListReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportallistpage.vm"); preparePage(page, session); List<Project> projects = ReportalHelper.getReportalProjects(server); page.add("ReportalHelper", ReportalHelper.class); page.add("user", session.getUser()); String startDate = DateTime.now().minusWeeks(1).toString("yyyy-MM-dd"); String endDate = DateTime.now().toString("yyyy-MM-dd"); page.add("startDate", startDate); page.add("endDate", endDate); if (!projects.isEmpty()) { page.add("projects", projects); } else { page.add("projects", false); } page.render(); } private void handleViewReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, Exception { int id = getIntParam(req, "id"); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaldatapage.vm"); preparePage(page, session); ProjectManager projectManager = server.getProjectManager(); ExecutorManagerAdapter executorManager = server.getExecutorManager(); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); Flow flow = project.getFlows().get(0); if (reportal == null) { page.add("errorMsg", "Report not found"); page.render(); return; } if (reportal.getAccessViewers().size() > 0 && !project.hasPermission(session.getUser(), Type.READ)) { page.add("errorMsg", "You are not allowed to view this report."); page.render(); return; } page.add("project", project); page.add("title", project.getMetadata().get("title")); if (hasParam(req, "execid")) { int execId = getIntParam(req, "execid"); page.add("execid", execId); // Show logs if (hasParam(req, "logs")) { ExecutableFlow exec; try { exec = executorManager.getExecutableFlow(execId); } catch (ExecutorManagerException e) { e.printStackTrace(); page.add("errorMsg", "ExecutableFlow not found. " + e.getMessage()); page.render(); return; } // View single log if (hasParam(req, "log")) { page.add("view-log", true); String jobId = getParam(req, "log"); page.add("execid", execId); page.add("jobId", jobId); } // List files else { page.add("view-logs", true); List<ExecutableNode> jobs = exec.getExecutableNodes(); // Sort list of jobs by level (which is the same as execution order // since Reportal flows are all linear). Collections.sort(jobs, new Comparator<ExecutableNode>() { public int compare(ExecutableNode a, ExecutableNode b) { return a.getLevel() < b.getLevel() ? -1 : 1; } public boolean equals(Object obj) { return this.equals(obj); } }); List<String> logList = new ArrayList<String>(); boolean showDataCollector = hasParam(req, "debug"); for (ExecutableNode node: jobs) { String jobId = node.getJobId(); if (!showDataCollector && !jobId.equals("data-collector")) { logList.add(jobId); } } if (logList.size() == 1) { resp.sendRedirect("/reportal?view&logs&id=" + project.getId() + "&execid=" + execId + "&log=" + logList.get(0)); } page.add("logs", logList); } } // Show data files else { String outputFileSystem = props.getString("reportal.output.filesystem", "local"); String outputBase = props.getString("reportal.output.location", "/tmp/reportal"); String locationFull = (outputBase + "/" + execId).replace("//", "/"); IStreamProvider streamProvider = ReportalUtil.getStreamProvider(outputFileSystem); if (streamProvider instanceof StreamProviderHDFS) { StreamProviderHDFS hdfsStreamProvider = (StreamProviderHDFS)streamProvider; hdfsStreamProvider.setHadoopSecurityManager(hadoopSecurityManager); hdfsStreamProvider.setUser(reportalStorageUser); } try { // Preview file if (hasParam(req, "preview")) { page.add("view-preview", true); String fileName = getParam(req, "preview"); String filePath = locationFull + "/" + fileName; InputStream csvInputStream = streamProvider.getFileInputStream(filePath); Scanner rowScanner = new Scanner(csvInputStream); ArrayList<Object> lines = new ArrayList<Object>(); int lineNumber = 0; while (rowScanner.hasNextLine() && lineNumber < 100) { String csvLine = rowScanner.nextLine(); String[] data = csvLine.split("\",\""); ArrayList<String> line = new ArrayList<String>(); for (String item: data) { line.add(item.replace("\"", "")); } lines.add(line); lineNumber++; } rowScanner.close(); page.add("preview", lines); Object graphHash = project.getMetadata().get("graphHash"); if (graphHash != null) { page.add("graphHash", graphHash); } } else if (hasParam(req, "download")) { String fileName = getParam(req, "download"); String filePath = locationFull + "/" + fileName; InputStream csvInputStream = null; OutputStream out = null; try { csvInputStream = streamProvider.getFileInputStream(filePath); resp.setContentType("application/octet-stream"); out = resp.getOutputStream(); IOUtils.copy(csvInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(csvInputStream); } return; } // List files else { page.add("view-files", true); try { String[] fileList = streamProvider.getFileList(locationFull); String[] dataList = ReportalHelper.filterCSVFile(fileList); Arrays.sort(dataList); if (dataList.length > 0) { page.add("files", dataList); } } catch (FileNotFoundException e) { } } } finally { streamProvider.cleanUp(); } } } // List executions and their data else { page.add("view-executions", true); ArrayList<ExecutableFlow> exFlows = new ArrayList<ExecutableFlow>(); int pageNumber = 0; boolean hasNextPage = false; if (hasParam(req, "page")) { pageNumber = getIntParam(req, "page") - 1; } if (pageNumber < 0) { pageNumber = 0; } try { executorManager.getExecutableFlows(project.getId(), flow.getId(), pageNumber * itemsPerPage, itemsPerPage, exFlows); ArrayList<ExecutableFlow> tmp = new ArrayList<ExecutableFlow>(); executorManager.getExecutableFlows(project.getId(), flow.getId(), (pageNumber + 1) * itemsPerPage, 1, tmp); if (!tmp.isEmpty()) { hasNextPage = true; } } catch (ExecutorManagerException e) { page.add("error", "Error retrieving executable flows"); } if (!exFlows.isEmpty()) { ArrayList<Object> history = new ArrayList<Object>(); for (ExecutableFlow exFlow: exFlows) { HashMap<String, Object> flowInfo = new HashMap<String, Object>(); flowInfo.put("execId", exFlow.getExecutionId()); flowInfo.put("status", exFlow.getStatus().toString()); flowInfo.put("startTime", exFlow.getStartTime()); history.add(flowInfo); } page.add("executions", history); } if (pageNumber > 0) { page.add("pagePrev", pageNumber); } page.add("page", pageNumber + 1); if (hasNextPage) { page.add("pageNext", pageNumber + 2); } } page.render(); } private void handleRunReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportalrunpage.vm"); preparePage(page, session); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); if (reportal == null) { page.add("errorMsg", "Report not found"); page.render(); return; } if (reportal.getAccessExecutors().size() > 0 && !project.hasPermission(session.getUser(), Type.EXECUTE)) { page.add("errorMsg", "You are not allowed to run this report."); page.render(); return; } page.add("project", project); page.add("title", reportal.title); page.add("description", reportal.description); if (reportal.variables.size() > 0) { page.add("variableNumber", reportal.variables.size()); page.add("variables", reportal.variables); } page.render(); } private void handleNewReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("new", true); page.add("project", false); page.add("title", ""); page.add("description", ""); page.add("queryNumber", 1); List<Map<String, Object>> queryList = new ArrayList<Map<String, Object>>(); page.add("queries", queryList); Map<String, Object> query = new HashMap<String, Object>(); queryList.add(query); query.put("title", ""); query.put("type", ""); query.put("script", ""); page.add("accessViewer", ""); page.add("accessExecutor", ""); page.add("accessOwner", ""); page.add("notifications", ""); page.render(); } private void handleEditReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); if (reportal == null) { page.add("errorMsg", "Report not found"); page.render(); return; } if (!project.hasPermission(session.getUser(), Type.ADMIN)) { page.add("errorMsg", "You are not allowed to edit this report."); page.render(); return; } page.add("project", project); page.add("title", reportal.title); page.add("description", reportal.description); page.add("queryNumber", reportal.queries.size()); page.add("queries", reportal.queries); page.add("variableNumber", reportal.variables.size()); page.add("variables", reportal.variables); page.add("schedule", reportal.schedule); page.add("scheduleEnabled", reportal.scheduleEnabled); page.add("scheduleInterval", reportal.scheduleInterval); page.add("scheduleTime", reportal.scheduleTime); page.add("notifications", reportal.notifications); page.add("accessViewer", reportal.accessViewer); page.add("accessExecutor", reportal.accessExecutor); page.add("accessOwner", reportal.accessOwner); page.render(); } @Override protected void handlePost(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { if (hasParam(req, "ajax")) { HashMap<String, Object> ret = new HashMap<String, Object>(); handleRunReportalWithVariables(req, ret, session); if (ret != null) { this.writeJSON(resp, ret); } } else { handleEditAddReportal(req, resp, session); } } private void handleEditAddReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { ProjectManager projectManager = server.getProjectManager(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); boolean isEdit = hasParam(req, "id"); Project project = null; Reportal report = new Reportal(); report.title = getParam(req, "title"); report.description = getParam(req, "description"); page.add("title", report.title); page.add("description", report.description); report.schedule = hasParam(req, "schedule"); report.scheduleEnabled = hasParam(req, "scheduleEnabled"); report.scheduleInterval = getParam(req, "schedule-interval"); report.scheduleTime = getIntParam(req, "schedule-time"); page.add("schedule", report.schedule); page.add("scheduleEnabled", report.scheduleEnabled); page.add("scheduleInterval", report.scheduleInterval); page.add("scheduleTime", report.scheduleTime); report.accessViewer = getParam(req, "access-viewer"); report.accessExecutor = getParam(req, "access-executor"); report.accessOwner = getParam(req, "access-owner"); page.add("accessViewer", report.accessViewer); page.add("accessExecutor", report.accessExecutor); page.add("accessOwner", report.accessOwner); report.notifications = getParam(req, "notifications"); page.add("notifications", report.notifications); - int queries = getIntParam(req, "queryNumber"); - page.add("queryNumber", queries); - List<Query> queryList = new ArrayList<Query>(queries); + int numQueries = getIntParam(req, "queryNumber"); + page.add("queryNumber", numQueries); + List<Query> queryList = new ArrayList<Query>(numQueries); page.add("queries", queryList); report.queries = queryList; String typeError = null; String typePermissionError = null; - for (int i = 0; i < queries; i++) { + for (int i = 0; i < numQueries; i++) { Query query = new Query(); query.title = getParam(req, "query" + i + "title"); query.type = getParam(req, "query" + i + "type"); query.script = getParam(req, "query" + i + "script"); // Type check ReportalType type = ReportalType.getTypeByName(query.type); if (type == null && typeError == null) { typeError = query.type; } if (!type.checkPermission(session.getUser())) { typePermissionError = query.type; } queryList.add(query); } int variables = getIntParam(req, "variableNumber"); page.add("variableNumber", variables); List<Variable> variableList = new ArrayList<Variable>(variables); page.add("variables", variableList); report.variables = variableList; boolean variableErrorOccurred = false; for (int i = 0; i < variables; i++) { Variable variable = new Variable(); variable.title = getParam(req, "variable" + i + "title"); variable.name = getParam(req, "variable" + i + "name"); if (variable.title.isEmpty() || variable.name.isEmpty()) { variableErrorOccurred = true; } variableList.add(variable); } // Make sure title isn't empty if (report.title.isEmpty()) { page.add("errorMsg", "Title must not be empty."); page.render(); return; } // Make sure description isn't empty if (report.description.isEmpty()) { page.add("errorMsg", "Description must not be empty."); page.render(); return; } // Empty query check - if (queries <= 0) { + if (numQueries <= 0) { page.add("errorMsg", "There needs to have at least one query."); page.render(); return; } // Type error check if (typeError != null) { page.add("errorMsg", "Type " + typeError + " is invalid."); page.render(); return; } // Type permission check if (typePermissionError != null && report.schedule && report.scheduleEnabled) { page.add("errorMsg", "You do not have permission to schedule Type " + typePermissionError + "."); page.render(); return; } // Variable error check if (variableErrorOccurred) { page.add("errorMsg", "Variable title and name cannot be empty."); page.render(); return; } // Attempt to get a project object if (isEdit) { // Editing mode, load project int projectId = getIntParam(req, "id"); project = projectManager.getProject(projectId); report.loadImmutableFromProject(project); } else { // Creation mode, create project try { User user = session.getUser(); project = ReportalHelper.createReportalProject(server, report.title, report.description, user); report.reportalUser = user.getUserId(); report.ownerEmail = user.getEmail(); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating report. " + e.getMessage()); page.render(); return; } // Project already exists if (project == null) { page.add("errorMsg", "A Report with the same name already exists."); page.render(); return; } } if (project == null) { page.add("errorMsg", "Internal Error: Report not found"); page.render(); return; } report.project = project; page.add("project", project); report.updatePermissions(); try { report.createZipAndUpload(projectManager, session.getUser(), reportalStorageUser); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating Azkaban jobs. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, session.getUser()); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return; } // Prepare flow Flow flow = project.getFlows().get(0); project.getMetadata().put("flowName", flow.getId()); // Set reportal mailer flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); // Create/Save schedule ScheduleManager scheduleManager = server.getScheduleManager(); try { report.updateSchedules(report, scheduleManager, session.getUser(), flow); } catch (ScheduleManagerException e2) { // TODO Auto-generated catch block e2.printStackTrace(); page.add("errorMsg", e2.getMessage()); page.render(); return; } report.saveToProject(project); try { ReportalHelper.updateProjectNotifications(project, projectManager); projectManager.updateProjectSetting(project); projectManager.updateFlow(project, flow); } catch (ProjectManagerException e) { e.printStackTrace(); page.add("errorMsg", "Error while updating report. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, session.getUser()); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return; } this.setSuccessMessageInCookie(resp, "Report Saved."); resp.sendRedirect(req.getRequestURI() + "?edit&id=" + project.getId()); } private void handleRunReportalWithVariables(HttpServletRequest req, HashMap<String, Object> ret, Session session) throws ServletException, IOException { int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Project project = projectManager.getProject(id); Reportal report = Reportal.loadFromProject(project); User user = session.getUser(); if (report.getAccessExecutors().size() > 0 && !project.hasPermission(user, Type.EXECUTE)) { ret.put("error", "You are not allowed to run this report."); return; } for (Query query: report.queries) { String jobType = query.type; ReportalType type = ReportalType.getTypeByName(jobType); if (!type.checkPermission(user)) { ret.put("error", "You are not allowed to run this report as you don't have permission to run job type " + type.toString() + "."); return; } } Flow flow = project.getFlows().get(0); ExecutableFlow exflow = new ExecutableFlow(flow); exflow.setSubmitUser(user.getUserId()); exflow.addAllProxyUsers(project.getProxyUsers()); ExecutionOptions options = exflow.getExecutionOptions(); int i = 0; for (Variable variable: report.variables) { options.getFlowParameters().put(REPORTAL_VARIABLE_PREFIX + i + ".from", variable.name); options.getFlowParameters().put(REPORTAL_VARIABLE_PREFIX + i + ".to", getParam(req, "variable" + i)); i++; } options.getFlowParameters().put("reportal.execution.user", user.getUserId()); // Add the execution user's email to the list of success and failure emails. String email = user.getEmail(); if (email != null) { options.getSuccessEmails().add(email); options.getFailureEmails().add(email); } options.getFlowParameters().put("reportal.title", report.title); try { String message = server.getExecutorManager().submitExecutableFlow(exflow, session.getUser().getUserId()) + "."; ret.put("message", message); ret.put("result", "success"); ret.put("redirect", "/reportal?view&logs&id=" + project.getId() + "&execid=" + exflow.getExecutionId()); } catch (ExecutorManagerException e) { e.printStackTrace(); ret.put("error", "Error running report " + report.title + ". " + e.getMessage()); } } private void preparePage(Page page, Session session) { page.add("viewerName", viewerName); page.add("hideNavigation", !showNav); page.add("userid", session.getUser().getUserId()); } private class CleanerThread extends Thread { // Every hour, clean execution dir. private static final long EXECUTION_DIR_CLEAN_INTERVAL_MS = 60 * 60 * 1000; private boolean shutdown = false; private long lastExecutionDirCleanTime = -1; private long executionDirRetention = 1 * 24 * 60 * 60 * 1000; public CleanerThread() { this.setName("Reportal-Cleaner-Thread"); } @SuppressWarnings("unused") public void shutdown() { shutdown = true; this.interrupt(); } public void run() { while (!shutdown) { synchronized (this) { long currentTime = System.currentTimeMillis(); if (currentTime - EXECUTION_DIR_CLEAN_INTERVAL_MS > lastExecutionDirCleanTime) { logger.info("Cleaning old execution dirs"); cleanOldReportalDirs(); lastExecutionDirCleanTime = currentTime; } } } } private void cleanOldReportalDirs() { File dir = reportalMailDirectory; final long pastTimeThreshold = System.currentTimeMillis() - executionDirRetention; File[] executionDirs = dir.listFiles(new FileFilter() { @Override public boolean accept(File path) { if (path.isDirectory() && path.lastModified() < pastTimeThreshold) { return true; } return false; } }); for (File exDir: executionDirs) { try { FileUtils.deleteDirectory(exDir); } catch (IOException e) { logger.error("Error cleaning execution dir " + exDir.getPath(), e); } } } } }
false
true
private void handleEditAddReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { ProjectManager projectManager = server.getProjectManager(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); boolean isEdit = hasParam(req, "id"); Project project = null; Reportal report = new Reportal(); report.title = getParam(req, "title"); report.description = getParam(req, "description"); page.add("title", report.title); page.add("description", report.description); report.schedule = hasParam(req, "schedule"); report.scheduleEnabled = hasParam(req, "scheduleEnabled"); report.scheduleInterval = getParam(req, "schedule-interval"); report.scheduleTime = getIntParam(req, "schedule-time"); page.add("schedule", report.schedule); page.add("scheduleEnabled", report.scheduleEnabled); page.add("scheduleInterval", report.scheduleInterval); page.add("scheduleTime", report.scheduleTime); report.accessViewer = getParam(req, "access-viewer"); report.accessExecutor = getParam(req, "access-executor"); report.accessOwner = getParam(req, "access-owner"); page.add("accessViewer", report.accessViewer); page.add("accessExecutor", report.accessExecutor); page.add("accessOwner", report.accessOwner); report.notifications = getParam(req, "notifications"); page.add("notifications", report.notifications); int queries = getIntParam(req, "queryNumber"); page.add("queryNumber", queries); List<Query> queryList = new ArrayList<Query>(queries); page.add("queries", queryList); report.queries = queryList; String typeError = null; String typePermissionError = null; for (int i = 0; i < queries; i++) { Query query = new Query(); query.title = getParam(req, "query" + i + "title"); query.type = getParam(req, "query" + i + "type"); query.script = getParam(req, "query" + i + "script"); // Type check ReportalType type = ReportalType.getTypeByName(query.type); if (type == null && typeError == null) { typeError = query.type; } if (!type.checkPermission(session.getUser())) { typePermissionError = query.type; } queryList.add(query); } int variables = getIntParam(req, "variableNumber"); page.add("variableNumber", variables); List<Variable> variableList = new ArrayList<Variable>(variables); page.add("variables", variableList); report.variables = variableList; boolean variableErrorOccurred = false; for (int i = 0; i < variables; i++) { Variable variable = new Variable(); variable.title = getParam(req, "variable" + i + "title"); variable.name = getParam(req, "variable" + i + "name"); if (variable.title.isEmpty() || variable.name.isEmpty()) { variableErrorOccurred = true; } variableList.add(variable); } // Make sure title isn't empty if (report.title.isEmpty()) { page.add("errorMsg", "Title must not be empty."); page.render(); return; } // Make sure description isn't empty if (report.description.isEmpty()) { page.add("errorMsg", "Description must not be empty."); page.render(); return; } // Empty query check if (queries <= 0) { page.add("errorMsg", "There needs to have at least one query."); page.render(); return; } // Type error check if (typeError != null) { page.add("errorMsg", "Type " + typeError + " is invalid."); page.render(); return; } // Type permission check if (typePermissionError != null && report.schedule && report.scheduleEnabled) { page.add("errorMsg", "You do not have permission to schedule Type " + typePermissionError + "."); page.render(); return; } // Variable error check if (variableErrorOccurred) { page.add("errorMsg", "Variable title and name cannot be empty."); page.render(); return; } // Attempt to get a project object if (isEdit) { // Editing mode, load project int projectId = getIntParam(req, "id"); project = projectManager.getProject(projectId); report.loadImmutableFromProject(project); } else { // Creation mode, create project try { User user = session.getUser(); project = ReportalHelper.createReportalProject(server, report.title, report.description, user); report.reportalUser = user.getUserId(); report.ownerEmail = user.getEmail(); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating report. " + e.getMessage()); page.render(); return; } // Project already exists if (project == null) { page.add("errorMsg", "A Report with the same name already exists."); page.render(); return; } } if (project == null) { page.add("errorMsg", "Internal Error: Report not found"); page.render(); return; } report.project = project; page.add("project", project); report.updatePermissions(); try { report.createZipAndUpload(projectManager, session.getUser(), reportalStorageUser); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating Azkaban jobs. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, session.getUser()); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return; } // Prepare flow Flow flow = project.getFlows().get(0); project.getMetadata().put("flowName", flow.getId()); // Set reportal mailer flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); // Create/Save schedule ScheduleManager scheduleManager = server.getScheduleManager(); try { report.updateSchedules(report, scheduleManager, session.getUser(), flow); } catch (ScheduleManagerException e2) { // TODO Auto-generated catch block e2.printStackTrace(); page.add("errorMsg", e2.getMessage()); page.render(); return; } report.saveToProject(project); try { ReportalHelper.updateProjectNotifications(project, projectManager); projectManager.updateProjectSetting(project); projectManager.updateFlow(project, flow); } catch (ProjectManagerException e) { e.printStackTrace(); page.add("errorMsg", "Error while updating report. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, session.getUser()); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return; } this.setSuccessMessageInCookie(resp, "Report Saved."); resp.sendRedirect(req.getRequestURI() + "?edit&id=" + project.getId()); }
private void handleEditAddReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { ProjectManager projectManager = server.getProjectManager(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); boolean isEdit = hasParam(req, "id"); Project project = null; Reportal report = new Reportal(); report.title = getParam(req, "title"); report.description = getParam(req, "description"); page.add("title", report.title); page.add("description", report.description); report.schedule = hasParam(req, "schedule"); report.scheduleEnabled = hasParam(req, "scheduleEnabled"); report.scheduleInterval = getParam(req, "schedule-interval"); report.scheduleTime = getIntParam(req, "schedule-time"); page.add("schedule", report.schedule); page.add("scheduleEnabled", report.scheduleEnabled); page.add("scheduleInterval", report.scheduleInterval); page.add("scheduleTime", report.scheduleTime); report.accessViewer = getParam(req, "access-viewer"); report.accessExecutor = getParam(req, "access-executor"); report.accessOwner = getParam(req, "access-owner"); page.add("accessViewer", report.accessViewer); page.add("accessExecutor", report.accessExecutor); page.add("accessOwner", report.accessOwner); report.notifications = getParam(req, "notifications"); page.add("notifications", report.notifications); int numQueries = getIntParam(req, "queryNumber"); page.add("queryNumber", numQueries); List<Query> queryList = new ArrayList<Query>(numQueries); page.add("queries", queryList); report.queries = queryList; String typeError = null; String typePermissionError = null; for (int i = 0; i < numQueries; i++) { Query query = new Query(); query.title = getParam(req, "query" + i + "title"); query.type = getParam(req, "query" + i + "type"); query.script = getParam(req, "query" + i + "script"); // Type check ReportalType type = ReportalType.getTypeByName(query.type); if (type == null && typeError == null) { typeError = query.type; } if (!type.checkPermission(session.getUser())) { typePermissionError = query.type; } queryList.add(query); } int variables = getIntParam(req, "variableNumber"); page.add("variableNumber", variables); List<Variable> variableList = new ArrayList<Variable>(variables); page.add("variables", variableList); report.variables = variableList; boolean variableErrorOccurred = false; for (int i = 0; i < variables; i++) { Variable variable = new Variable(); variable.title = getParam(req, "variable" + i + "title"); variable.name = getParam(req, "variable" + i + "name"); if (variable.title.isEmpty() || variable.name.isEmpty()) { variableErrorOccurred = true; } variableList.add(variable); } // Make sure title isn't empty if (report.title.isEmpty()) { page.add("errorMsg", "Title must not be empty."); page.render(); return; } // Make sure description isn't empty if (report.description.isEmpty()) { page.add("errorMsg", "Description must not be empty."); page.render(); return; } // Empty query check if (numQueries <= 0) { page.add("errorMsg", "There needs to have at least one query."); page.render(); return; } // Type error check if (typeError != null) { page.add("errorMsg", "Type " + typeError + " is invalid."); page.render(); return; } // Type permission check if (typePermissionError != null && report.schedule && report.scheduleEnabled) { page.add("errorMsg", "You do not have permission to schedule Type " + typePermissionError + "."); page.render(); return; } // Variable error check if (variableErrorOccurred) { page.add("errorMsg", "Variable title and name cannot be empty."); page.render(); return; } // Attempt to get a project object if (isEdit) { // Editing mode, load project int projectId = getIntParam(req, "id"); project = projectManager.getProject(projectId); report.loadImmutableFromProject(project); } else { // Creation mode, create project try { User user = session.getUser(); project = ReportalHelper.createReportalProject(server, report.title, report.description, user); report.reportalUser = user.getUserId(); report.ownerEmail = user.getEmail(); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating report. " + e.getMessage()); page.render(); return; } // Project already exists if (project == null) { page.add("errorMsg", "A Report with the same name already exists."); page.render(); return; } } if (project == null) { page.add("errorMsg", "Internal Error: Report not found"); page.render(); return; } report.project = project; page.add("project", project); report.updatePermissions(); try { report.createZipAndUpload(projectManager, session.getUser(), reportalStorageUser); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating Azkaban jobs. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, session.getUser()); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return; } // Prepare flow Flow flow = project.getFlows().get(0); project.getMetadata().put("flowName", flow.getId()); // Set reportal mailer flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); // Create/Save schedule ScheduleManager scheduleManager = server.getScheduleManager(); try { report.updateSchedules(report, scheduleManager, session.getUser(), flow); } catch (ScheduleManagerException e2) { // TODO Auto-generated catch block e2.printStackTrace(); page.add("errorMsg", e2.getMessage()); page.render(); return; } report.saveToProject(project); try { ReportalHelper.updateProjectNotifications(project, projectManager); projectManager.updateProjectSetting(project); projectManager.updateFlow(project, flow); } catch (ProjectManagerException e) { e.printStackTrace(); page.add("errorMsg", "Error while updating report. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, session.getUser()); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return; } this.setSuccessMessageInCookie(resp, "Report Saved."); resp.sendRedirect(req.getRequestURI() + "?edit&id=" + project.getId()); }
diff --git a/plugin/fiji/ffmpeg/Exporter.java b/plugin/fiji/ffmpeg/Exporter.java index c0830cb..b8e3d7a 100644 --- a/plugin/fiji/ffmpeg/Exporter.java +++ b/plugin/fiji/ffmpeg/Exporter.java @@ -1,68 +1,72 @@ package fiji.ffmpeg; /* * Simple movie writer for ImageJ using ffmpeg-java; based on Libavformat API * example from FFMPEG * * Based on the example "output_example.c" provided with FFMPEG. LGPL version * (no SWSCALE) by Uwe Mannl. */ import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.WindowManager; import ij.gui.GenericDialog; import ij.io.SaveDialog; import ij.plugin.PlugIn; import java.io.IOException; public class Exporter implements PlugIn { public void run(String arg) { IO io; try { io = new IO(new IJProgress()); } catch (IOException e) { IJ.error("This plugin needs ffmpeg to be installed!"); return; } ImagePlus image = WindowManager.getCurrentImage(); if (image == null) { IJ.error("No image is open"); return; } // TODO: transform on the fly if (image.getType() != ImagePlus.COLOR_RGB) { IJ.error("Need a color image"); return; } String name = IJ.getImage().getTitle(); SaveDialog sd = new SaveDialog("Export via FFMPEG", name, ".mpg"); name = sd.getFileName(); String directory = sd.getDirectory(); String path = directory+name; GenericDialog gd = new GenericDialog("FFMPEG Exporter"); gd.addNumericField("Framerate: ", 25, 0); gd.showDialog(); if (gd.wasCanceled()) return; int frameRate = (int)gd.getNextNumber(); try { io.writeMovie(image, path, frameRate); IJ.showStatus("Saved " + path + "."); + } catch (OutOfMemoryError e) { + io.free(); + IJ.error("Could not write " + path + ": " + e); } catch (IOException e) { + io.free(); IJ.error("Could not write " + path + ": " + e); } } }
false
true
public void run(String arg) { IO io; try { io = new IO(new IJProgress()); } catch (IOException e) { IJ.error("This plugin needs ffmpeg to be installed!"); return; } ImagePlus image = WindowManager.getCurrentImage(); if (image == null) { IJ.error("No image is open"); return; } // TODO: transform on the fly if (image.getType() != ImagePlus.COLOR_RGB) { IJ.error("Need a color image"); return; } String name = IJ.getImage().getTitle(); SaveDialog sd = new SaveDialog("Export via FFMPEG", name, ".mpg"); name = sd.getFileName(); String directory = sd.getDirectory(); String path = directory+name; GenericDialog gd = new GenericDialog("FFMPEG Exporter"); gd.addNumericField("Framerate: ", 25, 0); gd.showDialog(); if (gd.wasCanceled()) return; int frameRate = (int)gd.getNextNumber(); try { io.writeMovie(image, path, frameRate); IJ.showStatus("Saved " + path + "."); } catch (IOException e) { IJ.error("Could not write " + path + ": " + e); } }
public void run(String arg) { IO io; try { io = new IO(new IJProgress()); } catch (IOException e) { IJ.error("This plugin needs ffmpeg to be installed!"); return; } ImagePlus image = WindowManager.getCurrentImage(); if (image == null) { IJ.error("No image is open"); return; } // TODO: transform on the fly if (image.getType() != ImagePlus.COLOR_RGB) { IJ.error("Need a color image"); return; } String name = IJ.getImage().getTitle(); SaveDialog sd = new SaveDialog("Export via FFMPEG", name, ".mpg"); name = sd.getFileName(); String directory = sd.getDirectory(); String path = directory+name; GenericDialog gd = new GenericDialog("FFMPEG Exporter"); gd.addNumericField("Framerate: ", 25, 0); gd.showDialog(); if (gd.wasCanceled()) return; int frameRate = (int)gd.getNextNumber(); try { io.writeMovie(image, path, frameRate); IJ.showStatus("Saved " + path + "."); } catch (OutOfMemoryError e) { io.free(); IJ.error("Could not write " + path + ": " + e); } catch (IOException e) { io.free(); IJ.error("Could not write " + path + ": " + e); } }